From b9f0467e58e102ff0595fbd1a4d7f4d4defbff53 Mon Sep 17 00:00:00 2001 From: aecsocket <43144841+aecsocket@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:44:03 +0000 Subject: [PATCH 1/7] setup nix devenv flake --- .gitignore | 5 + flake.lock | 336 +++++++++++++++++++++++++++++++++++++++++++++++++++++ flake.nix | 51 ++++++++ 3 files changed, 392 insertions(+) create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.gitignore b/.gitignore index 5eecee60aac..4e663d1bc56 100644 --- a/.gitignore +++ b/.gitignore @@ -70,6 +70,11 @@ generated !apps/app-frontend/src/generated/app-events/postcard/package.json .env +# Nix development environment +/.devenv/ +/.direnv/ +/result + # app testing dir app-playground-data/* diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000000..8713b712f74 --- /dev/null +++ b/flake.lock @@ -0,0 +1,336 @@ +{ + "nodes": { + "crate2nix": { + "flake": false, + "locked": { + "lastModified": 1772186516, + "narHash": "sha256-8s28pzmQ6TOIUzznwFibtW1CMieMUl1rYJIxoQYor58=", + "owner": "rossng", + "repo": "crate2nix", + "rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e", + "type": "github" + }, + "original": { + "owner": "rossng", + "repo": "crate2nix", + "rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e", + "type": "github" + } + }, + "devenv": { + "inputs": { + "crate2nix": "crate2nix", + "flake-compat": "flake-compat", + "flake-parts": "flake-parts", + "ghostty": "ghostty", + "git-hooks": "git-hooks", + "nix": "nix", + "nixd": "nixd", + "nixpkgs": [ + "nixpkgs" + ], + "rust-overlay": "rust-overlay" + }, + "locked": { + "lastModified": 1794419745, + "narHash": "sha256-mGdiUY24F3Owpfn5wa3VkXomrQCNnI9kDy7rXJiFgm8=", + "owner": "cachix", + "repo": "devenv", + "rev": "215e857bd3403963855a4ff718822be0949a41e6", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1790898470, + "narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "024633cd702b10285db5cb19b40ad48d2399ba60", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "flake-parts_2": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1793576659, + "narHash": "sha256-V1h85lUaJBQoHFrB2vpXZOE0Ju1MYSnIpsehoVZYlDo=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "ea2630b7470978622c7689a1ff75d2b389175399", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "ghostty": { + "flake": false, + "locked": { + "lastModified": 1786026742, + "narHash": "sha256-tRtgTg/i3w1nFdRHU2IGekfJN8EyP+HARW4MtoUZyqk=", + "owner": "ghostty-org", + "repo": "ghostty", + "rev": "22d13172cde98a0a4dda05d3d6a3fcb0dd8ed018", + "type": "github" + }, + "original": { + "owner": "ghostty-org", + "repo": "ghostty", + "rev": "22d13172cde98a0a4dda05d3d6a3fcb0dd8ed018", + "type": "github" + } + }, + "git-hooks": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1791909798, + "narHash": "sha256-VAhpCOmrun/KXimYfR8NM88bciKCui7CqHHhThSzgag=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "1ba1dbfe28738c9a71c266be6efa5b89e75491a9", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, + "nix": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "flake-parts": [ + "devenv", + "flake-parts" + ], + "git-hooks-nix": [ + "devenv", + "git-hooks" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-23-11": [ + "devenv" + ], + "nixpkgs-regression": [ + "devenv" + ] + }, + "locked": { + "lastModified": 1792603708, + "narHash": "sha256-9KB9OFCP71d8n4Gg09saO6H1VuVzHdjusheiHtgn9jc=", + "owner": "cachix", + "repo": "nix", + "rev": "082f14105a3e545e1d60bbbc9028dba19f114a0d", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "devenv-2.35", + "repo": "nix", + "type": "github" + } + }, + "nixd": { + "inputs": { + "flake-parts": [ + "devenv", + "flake-parts" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "treefmt-nix": "treefmt-nix" + }, + "locked": { + "lastModified": 1792826393, + "narHash": "sha256-oUBZXzDvTAh/b0xzHrhXzX7W8ZgPXLTdgS9L9ol6buc=", + "owner": "nix-community", + "repo": "nixd", + "rev": "87012f56073f179c544fde6379bc954584217555", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixd", + "type": "github" + } + }, + "nixpkgs": { + "inputs": { + "nixpkgs-src": "nixpkgs-src" + }, + "locked": { + "lastModified": 1793043970, + "narHash": "sha256-m14odYTdkBUEkJOiEYs2zjGjn8fcjvdCJsm45+k084U=", + "owner": "cachix", + "repo": "devenv-nixpkgs", + "rev": "d97234e58d4e90e3bf77c082fc3b546e51200938", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "rolling", + "repo": "devenv-nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1793504054, + "narHash": "sha256-ThkfL3D/FhCiZFc9+3BtxwuMmpuK+/bGtXCSo1+yVew=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "7851ba61fd862b277cb6a9cef37394bc18bb94e4", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixpkgs.lib", + "type": "github" + } + }, + "nixpkgs-src": { + "flake": false, + "locked": { + "lastModified": 1792812153, + "narHash": "sha256-T2+XBfNbf9pecLUWS4+RtuVNZ3W8K5taG5QdV71mWlk=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "674a2028661e550a97400c1cc992b9cca9a668a1", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "flake-parts": "flake-parts_2", + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay_2" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1793086596, + "narHash": "sha256-ObKS44vw4IIVpQ69YJzUGjZ0IwnpWoUlwjJSY7gefdo=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "c7e9d512653a35ef4d5879c3df4d44d7b78d0e6d", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "rust-overlay_2": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1794476126, + "narHash": "sha256-KBjfmgZIUqBpjsemRKp4GvrCf8DlNsldkmxphh4X9oo=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "d1e30fd696e1151603aa8adaa8f6b8c604fe3eb0", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "devenv", + "nixd", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1791885023, + "narHash": "sha256-C3alQ2MEt0zVrUSho5NUDo3jmhbff72++bfwoqT9Omo=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "0d6d739a833ba9a9c93034862e4a7b061a062a1c", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000000..11b323ce595 --- /dev/null +++ b/flake.nix @@ -0,0 +1,51 @@ +{ + description = "Labrinth backend development environment"; + + inputs = { + nixpkgs.url = "github:cachix/devenv-nixpkgs/rolling"; + devenv = { + url = "github:cachix/devenv"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + flake-parts.url = "github:hercules-ci/flake-parts"; + rust-overlay = { + url = "github:oxalica/rust-overlay"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = inputs@{ flake-parts, ... }: + flake-parts.lib.mkFlake { inherit inputs; } { + imports = [ inputs.devenv.flakeModule ]; + systems = [ "x86_64-linux" "aarch64-linux" ]; + + perSystem = { pkgs, system, ... }: { + _module.args.pkgs = import inputs.nixpkgs { + inherit system; + overlays = [ inputs.rust-overlay.overlays.default ]; + }; + + devenv.shells.default = { config, ... }: { + packages = with pkgs; [ + (rust-bin.fromRustupToolchainFile ./rust-toolchain.toml) + rustPlatform.bindgenHook + pkg-config + cmake + gnumake + perl + nasm + clang + openssl + zlib + postgresql_15 + redis + ]; + + # Fortify requires optimization, but Cargo debug builds compile native code with -O0. + hardeningDisable = [ "fortify" ]; + + env.SQLX_OFFLINE = "true"; + }; + }; + }; +} From 1e7fc73d1d0750366bf14329221571ae2e052bb0 Mon Sep 17 00:00:00 2001 From: aecsocket <43144841+aecsocket@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:45:42 +0000 Subject: [PATCH 2/7] remove maxmind crate --- Cargo.lock | 36 ---- Cargo.toml | 3 - packages/modrinth-maxmind/Cargo.toml | 25 --- packages/modrinth-maxmind/README.md | 1 - packages/modrinth-maxmind/examples/maxmind.rs | 37 ---- packages/modrinth-maxmind/src/lib.rs | 175 ------------------ 6 files changed, 277 deletions(-) delete mode 100644 packages/modrinth-maxmind/Cargo.toml delete mode 100644 packages/modrinth-maxmind/README.md delete mode 100644 packages/modrinth-maxmind/examples/maxmind.rs delete mode 100644 packages/modrinth-maxmind/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index ffaf74a0c49..d076b69dd7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6376,12 +6376,6 @@ dependencies = [ "serde", ] -[[package]] -name = "ipnetwork" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf370abdafd54d13e54a620e8c3e1145f28e46cc9d704bc6d94414559df41763" - [[package]] name = "is-docker" version = "0.2.0" @@ -8028,18 +8022,6 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" -[[package]] -name = "maxminddb" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b43d2458d977b610b04a3858e6504f06133663d303a1a0606601b530bfc9bc6" -dependencies = [ - "ipnetwork", - "memchr", - "serde", - "thiserror 2.0.21", -] - [[package]] name = "maybe-async" version = "0.2.11" @@ -8317,24 +8299,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "modrinth-maxmind" -version = "0.0.0" -dependencies = [ - "bytes", - "clap 4.6.7", - "directories", - "eyre", - "flate2", - "maxminddb", - "modrinth-util", - "reqwest 0.13.5", - "tar", - "tokio", - "tracing", - "tracing-subscriber", -] - [[package]] name = "modrinth-util" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index ca462e9d00d..8afd384d862 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,6 @@ members = [ "packages/minecraft-meta-model", "packages/modrinth-content-management", "packages/modrinth-log", - "packages/modrinth-maxmind", "packages/modrinth-util", "packages/neverbounce", "packages/path-util", @@ -147,7 +146,6 @@ lz4_flex = { version = "0.14.0", default-features = false, features = [ "safe-encode", "std", ] } -maxminddb = "0.32.0" minecraft-meta-manifest = { path = "packages/minecraft-meta-manifest" } minecraft-meta-model = { path = "packages/minecraft-meta-model" } modrinth-content-management = { path = "packages/modrinth-content-management" } @@ -225,7 +223,6 @@ strum = "0.28.0" subtle = "2.6.1" syn = { version = "3.0" } sysinfo = { version = "0.38.4", default-features = false } -tar = "0.4.46" tauri = "=2.11.5" tauri-build = "=2.6.3" tauri-plugin-deep-link = "=2.4.3" diff --git a/packages/modrinth-maxmind/Cargo.toml b/packages/modrinth-maxmind/Cargo.toml deleted file mode 100644 index 15f87aae677..00000000000 --- a/packages/modrinth-maxmind/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "modrinth-maxmind" -edition.workspace = true -rust-version.workspace = true -repository.workspace = true - -[dependencies] -bytes = { workspace = true } -directories = { workspace = true } -eyre = { workspace = true } -flate2 = { workspace = true } -maxminddb = { workspace = true } -modrinth-util = { workspace = true } -reqwest = { workspace = true, features = ["json"] } -tar = { workspace = true } -tokio = { workspace = true, features = ["fs"] } -tracing = { workspace = true } - -[dev-dependencies] -clap = { workspace = true, features = ["derive"] } -tokio = { workspace = true, features = ["full"] } -tracing-subscriber = { workspace = true } - -[lints] -workspace = true diff --git a/packages/modrinth-maxmind/README.md b/packages/modrinth-maxmind/README.md deleted file mode 100644 index 9884bf55abe..00000000000 --- a/packages/modrinth-maxmind/README.md +++ /dev/null @@ -1 +0,0 @@ -Allows opening and reading a MaxMind GeoIP database, for use in an `actix-web` app. diff --git a/packages/modrinth-maxmind/examples/maxmind.rs b/packages/modrinth-maxmind/examples/maxmind.rs deleted file mode 100644 index 28e9cbf4035..00000000000 --- a/packages/modrinth-maxmind/examples/maxmind.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! Example/testing binary for checking if a MaxMind database can be loaded from -//! the current environment. - -use std::net::IpAddr; - -use eyre::Result; -use maxminddb::geoip2; -use modrinth_util::Context; -use tracing::info; - -/// Looks up country details for an IP using the MaxMind database -#[derive(Debug, clap::Parser)] -struct Args { - /// IP address to look up - ip: IpAddr, -} - -#[tokio::main] -async fn main() -> Result<()> { - let args = ::parse(); - tracing_subscriber::fmt().init(); - - let maxmind = modrinth_maxmind::init_reader() - .await - .wrap_err("failed to create reader")?; - - let ip = args.ip; - let country = maxmind - .lookup(ip) - .wrap_err("failed to lookup country")? - .decode::() - .wrap_err("failed to decode country")?; - - info!("Country details for {ip:?}:\n{country:#?}"); - - Ok(()) -} diff --git a/packages/modrinth-maxmind/src/lib.rs b/packages/modrinth-maxmind/src/lib.rs deleted file mode 100644 index 6995984f75d..00000000000 --- a/packages/modrinth-maxmind/src/lib.rs +++ /dev/null @@ -1,175 +0,0 @@ -#![doc = include_str!("../README.md")] - -use std::{ - io::{Cursor, Read}, - net::IpAddr, - path::Path, - sync::Arc, -}; - -use flate2::read::GzDecoder; -pub use maxminddb::{self, geoip2}; - -use bytes::Bytes; -use eyre::{Result, bail, eyre}; -use modrinth_util::{Context, env_var}; -use tokio::fs; -use tracing::{debug, info, warn}; - -/// MaxMind GeoIP database reader for use as a `web::Data` parameter. -#[derive(Debug, Clone)] -pub struct MaxMind { - /// Database reader. - /// - /// If the backend was not configured with MaxMind, the reader will not be - /// available. - pub reader: Option>>, -} - -impl MaxMind { - /// Creates a [`MaxMind`] with no reader. - #[must_use] - pub const fn none() -> Self { - Self { reader: None } - } - - /// Attempts to create a [`MaxMind`] with a MaxMind GeoIP database reader. - /// - /// This reads creation and download parameters from environment variables. - /// - /// If the database could not be created or downloaded, this will make a - /// [`MaxMind`] with no reader. - pub async fn new() -> Self { - Self { - reader: init_reader() - .await - .inspect_err(|err| { - warn!("Failed to initialize MaxMind: {err:#}"); - }) - .map(Arc::new) - .ok(), - } - } - - /// Queries the MaxMind database for the ISO country code of an IP address. - /// - /// If MaxMind is not configured or the database could not be read, returns - /// [`None`]. - pub async fn query_country(&self, ip: impl Into) -> Option { - let reader = self.reader.as_ref()?; - reader - .lookup(ip.into()) - .ok()? - .decode::() - .ok()? - .and_then(|c| c.country.iso_code.map(|s| s.to_string())) - } -} - -/// Creates a [`maxminddb::Reader`] for use in [`MaxMind::reader`]. -/// -/// # Errors -/// -/// Errors if the database is not present, or could not be downloaded (i.e. -/// missing license key). -pub async fn init_reader() -> Result> { - let db = if let Ok(db_path) = env_var("MAXMIND_DB") { - info!("Using MaxMind database at {db_path:?}"); - - fs::read(&db_path) - .await - .map(Bytes::from) - .wrap_err_with(|| { - eyre!("failed to read database from {db_path:?}") - })? - } else { - let account_id = env_var("MAXMIND_ACCOUNT_ID")?; - let license_key = env_var("MAXMIND_LICENSE_KEY")?; - - let dirs = directories::ProjectDirs::from( - "com.modrinth", - "Modrinth", - "modrinth-backend", - ) - .wrap_err("failed to get cache directory")?; - let cache_dir = dirs.cache_dir(); - let db_path = cache_dir.join("geolite.mmdb"); - - match fs::read(&db_path).await { - Ok(db) => { - info!("Using cached MaxMind database at {db_path:?}"); - Bytes::from(db) - } - Err(err) => { - debug!( - "Failed to read MaxMind database from {db_path:?}, will download: {err}" - ); - - let db = download(&account_id, &license_key).await?; - - match write_to_cache(cache_dir, &db_path, &db).await { - Ok(()) => { - info!("Wrote GeoIP database cache to {db_path:?}"); - } - Err(err) => warn!( - "Failed to write GeoIP database cache to {db_path:?}: {err:?}", - ), - } - - info!("Downloaded and cached database"); - db - } - } - }; - - maxminddb::Reader::from_source(db).wrap_err("failed to create reader") -} - -async fn download(account_id: &str, license_key: &str) -> Result { - info!("Downloading MaxMind GeoIP database"); - let db = reqwest::Client::new() - .get("https://download.maxmind.com/geoip/databases/GeoLite2-Country/download?suffix=tar.gz") - .basic_auth(account_id, Some(license_key)) - .send() - .await - .wrap_err("failed to begin downloading GeoIP database")? - .error_for_status() - .wrap_err("failed to download GeoIP database")? - .bytes() - .await - .wrap_err("failed to finish downloading GeoIP database")?; - - let db = GzDecoder::new(Cursor::new(db)); - let mut archive = tar::Archive::new(db); - - let entries = archive.entries().wrap_err("failed to read entries")?; - for entry in entries { - let mut entry = entry.wrap_err("failed to read entry")?; - let Ok(path) = entry.header().path() else { - continue; - }; - if path.extension().and_then(|x| x.to_str()) == Some("mmdb") { - let mut buf = Vec::new(); - entry - .read_to_end(&mut buf) - .wrap_err("failed to read entry")?; - return Ok(Bytes::from(buf)); - } - } - - bail!("no entries in archive"); -} - -async fn write_to_cache( - cache_dir: &Path, - db_path: &Path, - db: &[u8], -) -> Result<()> { - fs::create_dir_all(cache_dir) - .await - .wrap_err("failed to create parent directories")?; - fs::write(db_path, db) - .await - .wrap_err("failed to write to file")?; - Ok(()) -} From bf37464f3abf0f43df554bff0bf8a471a3fc5b52 Mon Sep 17 00:00:00 2001 From: aecsocket <43144841+aecsocket@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:17:41 +0000 Subject: [PATCH 3/7] switch eyre to anyhow --- Cargo.lock | 61 +- Cargo.toml | 2 - apps/labrinth/AGENTS.md | 12 +- apps/labrinth/Cargo.toml | 3 +- apps/labrinth/src/auth/checks.rs | 27 +- apps/labrinth/src/auth/mod.rs | 2 +- apps/labrinth/src/auth/oauth/errors.rs | 4 +- apps/labrinth/src/background_task.rs | 38 +- apps/labrinth/src/bin/check_project.rs | 39 +- .../src/bin/check_project/profanity.rs | 18 +- apps/labrinth/src/database/mod.rs | 4 +- .../database/models/analytics_event_item.rs | 24 +- .../src/database/models/categories.rs | 40 +- .../src/database/models/charge_item.rs | 38 +- .../src/database/models/collection_item.rs | 24 +- .../src/database/models/delphi_report_item.rs | 12 +- .../labrinth/src/database/models/flow_item.rs | 20 +- apps/labrinth/src/database/models/ids.rs | 10 +- .../src/database/models/image_item.rs | 18 +- .../src/database/models/loader_item.rs | 22 +- .../database/models/moderation_note_item.rs | 38 +- .../src/database/models/notification_item.rs | 60 +- .../models/notifications_deliveries_item.rs | 10 +- .../models/notifications_template_item.rs | 30 +- .../models/notifications_type_item.rs | 12 +- .../models/oauth_client_authorization_item.rs | 10 +- .../src/database/models/oauth_client_item.rs | 20 +- .../src/database/models/oauth_token_item.rs | 6 +- .../src/database/models/organization_item.rs | 30 +- .../src/database/models/passkey_item.rs | 16 +- apps/labrinth/src/database/models/pat_item.rs | 40 +- .../src/database/models/payout_item.rs | 10 +- .../models/payouts_values_notifications.rs | 4 +- .../src/database/models/product_item.rs | 54 +- .../models/products_tax_identifier_item.rs | 8 +- .../models/project_disclosure_item.rs | 24 +- .../src/database/models/project_flag_item.rs | 72 +-- .../src/database/models/project_item.rs | 109 ++-- .../src/database/models/report_item.rs | 12 +- .../src/database/models/session_item.rs | 34 +- .../labrinth/src/database/models/team_item.rs | 54 +- .../src/database/models/thread_issue_item.rs | 32 +- .../src/database/models/thread_item.rs | 36 +- .../labrinth/src/database/models/user_item.rs | 134 ++--- .../src/database/models/user_limits.rs | 10 +- .../src/database/models/user_lock_item.rs | 8 +- .../database/models/user_restriction_item.rs | 6 +- .../database/models/user_subscription_item.rs | 24 +- .../users_notifications_preferences_item.rs | 8 +- .../src/database/models/version_item.rs | 122 ++-- .../src/database/postgres_database.rs | 12 +- apps/labrinth/src/database/redis/mod.rs | 4 +- apps/labrinth/src/env.rs | 18 +- apps/labrinth/src/file_hosting/kafka_host.rs | 8 +- apps/labrinth/src/lib.rs | 9 +- apps/labrinth/src/main.rs | 1 - apps/labrinth/src/models/exp/component.rs | 8 +- apps/labrinth/src/models/exp/minecraft.rs | 13 +- apps/labrinth/src/models/exp/project.rs | 6 +- apps/labrinth/src/models/exp/version.rs | 4 +- apps/labrinth/src/models/minecraft.rs | 10 +- apps/labrinth/src/models/v2/projects.rs | 10 +- .../src/models/v3/moderation_notes.rs | 9 +- apps/labrinth/src/models/v3/notifications.rs | 5 +- apps/labrinth/src/queue/analytics/cache.rs | 16 +- apps/labrinth/src/queue/billing.rs | 135 ++--- apps/labrinth/src/queue/delphi_scan.rs | 22 +- apps/labrinth/src/queue/email.rs | 22 +- apps/labrinth/src/queue/email/templates.rs | 73 +-- apps/labrinth/src/queue/file_scan.rs | 111 ++-- .../src/queue/moderation/project_flag.rs | 55 +- .../moderation/project_flag_attribution.rs | 16 +- .../queue/moderation/project_flag_files.rs | 70 +-- .../src/queue/moderation/project_flag_run.rs | 96 ++-- apps/labrinth/src/queue/payouts/flow/mod.rs | 17 +- apps/labrinth/src/queue/payouts/flow/mural.rs | 32 +- .../labrinth/src/queue/payouts/flow/paypal.rs | 25 +- .../src/queue/payouts/flow/tremendous.rs | 28 +- apps/labrinth/src/queue/payouts/mod.rs | 63 +-- apps/labrinth/src/queue/payouts/mural.rs | 12 +- apps/labrinth/src/queue/server_ping.rs | 39 +- apps/labrinth/src/queue/session.rs | 26 +- apps/labrinth/src/routes/debug/mod.rs | 12 +- apps/labrinth/src/routes/debug/pprof.rs | 24 +- apps/labrinth/src/routes/internal/admin.rs | 8 +- .../routes/internal/admin/user_credentials.rs | 62 +- .../src/routes/internal/admin/user_lock.rs | 42 +- .../routes/internal/admin/user_sessions.rs | 22 +- .../src/routes/internal/analytics_event.rs | 36 +- .../src/routes/internal/attribution.rs | 176 +++--- apps/labrinth/src/routes/internal/billing.rs | 363 ++++++------ .../src/routes/internal/billing/payments.rs | 128 ++--- .../internal/billing/update_subscriptions.rs | 8 +- .../src/routes/internal/blocked_users.rs | 11 +- apps/labrinth/src/routes/internal/campaign.rs | 86 +-- .../src/routes/internal/delphi/mod.rs | 48 +- .../src/routes/internal/delphi/rescan.rs | 8 +- .../internal/delphi/tech_review_queue.rs | 14 +- .../routes/internal/external_notifications.rs | 50 +- apps/labrinth/src/routes/internal/flows.rs | 530 +++++++++-------- apps/labrinth/src/routes/internal/gdpr.rs | 44 +- .../labrinth/src/routes/internal/gotenberg.rs | 16 +- apps/labrinth/src/routes/internal/medal.rs | 21 +- .../moderation/copyright_archives/mod.rs | 44 +- .../internal/moderation/external_license.rs | 79 ++- .../src/routes/internal/moderation/mod.rs | 160 +++--- .../routes/internal/moderation/ownership.rs | 16 +- .../moderation/project_flag/project.rs | 6 +- .../internal/moderation/project_flag/rule.rs | 96 ++-- .../moderation/project_flag/schema_example.rs | 6 +- .../routes/internal/moderation/tech_review.rs | 144 +++-- .../internal/moderation/tech_review/global.rs | 28 +- .../internal/moderation/tech_review/rules.rs | 48 +- .../moderation/tech_review/rules_scan.rs | 96 ++-- .../internal/moderation/user_restrictions.rs | 26 +- apps/labrinth/src/routes/internal/mural.rs | 4 +- apps/labrinth/src/routes/internal/pats.rs | 71 ++- apps/labrinth/src/routes/internal/privacy.rs | 14 +- apps/labrinth/src/routes/internal/search.rs | 4 +- .../src/routes/internal/server_ping.rs | 4 +- apps/labrinth/src/routes/internal/session.rs | 43 +- apps/labrinth/src/routes/internal/statuses.rs | 35 +- apps/labrinth/src/routes/maven.rs | 73 +-- apps/labrinth/src/routes/mod.rs | 70 +-- apps/labrinth/src/routes/updates.rs | 13 +- apps/labrinth/src/routes/v2/notifications.rs | 4 +- apps/labrinth/src/routes/v2/projects.rs | 36 +- apps/labrinth/src/routes/v2/reports.rs | 8 +- apps/labrinth/src/routes/v2/statistics.rs | 2 +- apps/labrinth/src/routes/v2/tags.rs | 8 +- apps/labrinth/src/routes/v2/teams.rs | 6 +- apps/labrinth/src/routes/v2/threads.rs | 2 +- apps/labrinth/src/routes/v2/users.rs | 20 +- .../src/routes/v2/version_creation.rs | 2 +- apps/labrinth/src/routes/v2/version_file.rs | 12 +- apps/labrinth/src/routes/v2/versions.rs | 43 +- .../labrinth/src/routes/v3/analytics_event.rs | 2 +- .../routes/v3/analytics_get/facets/fixed.rs | 2 +- .../src/routes/v3/analytics_get/facets/mod.rs | 4 +- .../metrics/project_downloads.rs | 14 +- .../analytics_get/metrics/project_playtime.rs | 6 +- .../analytics_get/metrics/project_revenue.rs | 11 +- .../v3/analytics_get/metrics/project_views.rs | 6 +- .../src/routes/v3/analytics_get/mod.rs | 66 +-- apps/labrinth/src/routes/v3/blocked_users.rs | 30 +- apps/labrinth/src/routes/v3/collections.rs | 116 ++-- apps/labrinth/src/routes/v3/content/mod.rs | 29 +- apps/labrinth/src/routes/v3/disclosures.rs | 42 +- apps/labrinth/src/routes/v3/friends.rs | 59 +- apps/labrinth/src/routes/v3/images.rs | 55 +- apps/labrinth/src/routes/v3/limits.rs | 12 +- apps/labrinth/src/routes/v3/notifications.rs | 67 +-- apps/labrinth/src/routes/v3/oauth_clients.rs | 103 ++-- apps/labrinth/src/routes/v3/organizations.rs | 251 +++++---- apps/labrinth/src/routes/v3/payouts.rs | 191 +++---- .../src/routes/v3/project_creation.rs | 5 +- .../src/routes/v3/project_creation/new.rs | 38 +- apps/labrinth/src/routes/v3/projects/mod.rs | 532 +++++++++--------- .../src/routes/v3/projects/mutation.rs | 56 +- .../src/routes/v3/projects/validate.rs | 30 +- apps/labrinth/src/routes/v3/reports.rs | 137 +++-- apps/labrinth/src/routes/v3/statistics.rs | 8 +- apps/labrinth/src/routes/v3/tags.rs | 13 +- apps/labrinth/src/routes/v3/teams.rs | 237 ++++---- apps/labrinth/src/routes/v3/threads.rs | 175 +++--- apps/labrinth/src/routes/v3/users.rs | 258 ++++----- .../src/routes/v3/version_creation.rs | 18 +- apps/labrinth/src/routes/v3/version_file.rs | 107 ++-- apps/labrinth/src/routes/v3/versions.rs | 149 +++-- apps/labrinth/src/search/backend/common.rs | 8 +- .../search/backend/elasticsearch/filter.rs | 23 +- .../src/search/backend/elasticsearch/mod.rs | 99 ++-- apps/labrinth/src/search/incremental.rs | 2 +- .../src/search/incremental/consume.rs | 40 +- apps/labrinth/src/search/indexing.rs | 30 +- apps/labrinth/src/search/mod.rs | 14 +- apps/labrinth/src/test/db.rs | 10 +- apps/labrinth/src/util/avalara1099.rs | 19 +- apps/labrinth/src/util/captcha.rs | 13 +- apps/labrinth/src/util/cel.rs | 10 +- apps/labrinth/src/util/error.rs | 169 +++--- apps/labrinth/src/util/gotenberg.rs | 28 +- apps/labrinth/src/util/img.rs | 32 +- apps/labrinth/src/util/kafka.rs | 66 +-- apps/labrinth/src/util/minecraft_meta.rs | 12 +- apps/labrinth/src/util/neverbounce.rs | 12 +- apps/labrinth/src/util/ratelimit.rs | 7 +- apps/labrinth/src/util/refreshed_data.rs | 2 +- apps/labrinth/src/util/routes.rs | 13 +- apps/labrinth/src/util/stripe.rs | 13 +- apps/labrinth/src/util/tags.rs | 2 +- apps/labrinth/src/util/tiltify.rs | 12 +- apps/labrinth/src/util/usercheck.rs | 10 +- apps/labrinth/src/util/webhook.rs | 21 +- apps/labrinth/src/validate/fabric.rs | 4 +- apps/labrinth/src/validate/mod.rs | 5 +- apps/labrinth/src/validate/project/mod.rs | 2 +- .../src/validate/project/server_settings.rs | 2 +- apps/labrinth/tests/redis.rs | 25 +- packages/modrinth-log/Cargo.toml | 2 +- packages/modrinth-log/src/lib.rs | 10 +- packages/modrinth-util/Cargo.toml | 2 +- packages/modrinth-util/src/error.rs | 109 ++-- packages/modrinth-util/src/lib.rs | 6 +- packages/xredis/Cargo.toml | 2 +- packages/xredis/src/blocking.rs | 18 +- packages/xredis/src/cache.rs | 54 +- packages/xredis/src/cache/locking/local.rs | 4 +- packages/xredis/src/commands.rs | 31 +- packages/xredis/src/config.rs | 8 +- packages/xredis/src/connection.rs | 28 +- packages/xredis/src/lib.rs | 32 +- packages/xredis/src/metrics.rs | 20 +- packages/xredis/src/pubsub.rs | 12 +- 214 files changed, 4563 insertions(+), 4667 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d076b69dd7f..59ae0769915 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2871,33 +2871,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "color-eyre" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5920befb47832a6d61ee3a3a846565cfa39b331331e68a3b1d1116630f2f26d" -dependencies = [ - "backtrace", - "color-spantrace", - "eyre", - "indenter", - "once_cell", - "owo-colors 4.4.0", - "tracing-error", -] - -[[package]] -name = "color-spantrace" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8b88ea9df13354b55bc7234ebcce36e6ef896aca2e42a15de9e10edce01b427" -dependencies = [ - "once_cell", - "owo-colors 4.4.0", - "tracing-core", - "tracing-error", -] - [[package]] name = "color-thief" version = "0.2.2" @@ -4493,17 +4466,6 @@ dependencies = [ "zune-inflate", ] -[[package]] -name = "eyre" -version = "0.6.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08309dbcc659c5549a24ddb9b27027640641b282ef5768267c7e675558986a3" -dependencies = [ - "autocfg", - "indenter", - "once_cell", -] - [[package]] name = "fallible-iterator" version = "0.2.0" @@ -6182,12 +6144,6 @@ dependencies = [ "quote", ] -[[package]] -name = "indenter" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" - [[package]] name = "index_vec" version = "0.1.4" @@ -6725,6 +6681,7 @@ dependencies = [ "actix-web", "actix-web-prom", "actix-ws", + "anyhow", "arc-swap", "argon2", "ariadne", @@ -6747,7 +6704,6 @@ dependencies = [ "chumsky", "clap 4.6.7", "clickhouse", - "color-eyre", "color-thief", "component-derive", "const_format", @@ -6757,7 +6713,6 @@ dependencies = [ "dotenv-build", "dotenvy", "either", - "eyre", "futures", "futures-util", "heck 0.5.0", @@ -8291,8 +8246,8 @@ dependencies = [ name = "modrinth-log" version = "0.0.0" dependencies = [ + "anyhow", "dotenvy", - "eyre", "sentry", "tracing", "tracing-ecs", @@ -8304,9 +8259,9 @@ name = "modrinth-util" version = "0.0.0" dependencies = [ "actix-web", + "anyhow", "derive_more 2.1.1", "dotenvy", - "eyre", "modrinth-log", "rust_decimal", "serde", @@ -9276,12 +9231,6 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" -[[package]] -name = "owo-colors" -version = "4.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" - [[package]] name = "p256" version = "0.14.0" @@ -12314,7 +12263,7 @@ dependencies = [ "cfg-if", "generator", "hex", - "owo-colors 3.5.0", + "owo-colors", "rand 0.8.8", "rand_core 0.6.4", "rand_pcg 0.3.1", @@ -16837,11 +16786,11 @@ checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" name = "xredis" version = "0.1.0" dependencies = [ + "anyhow", "ariadne", "chrono", "dashmap", "deadpool-redis", - "eyre", "futures", "lz4_flex", "postcard", diff --git a/Cargo.toml b/Cargo.toml index 8afd384d862..9feb67aad55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,6 @@ chumsky = "0.13.0" cidre = { version = "0.29.0", default-features = false, features = ["macos_15_0"] } clap = "4.6.7" clickhouse = "0.15.3" -color-eyre = "0.6.5" color-thief = "0.2.2" component-derive = { path = "packages/component-derive" } const_format = "0.2.36" @@ -94,7 +93,6 @@ dunce = "1.0.5" either = "1.19.0" encoding_rs = "0.8.42" enumset = "1.1.14" -eyre = "0.6.14" figment = { version = "0.10.19" } flate2 = "1.1.10" fs4 = { version = "1.1.0", default-features = false } diff --git a/apps/labrinth/AGENTS.md b/apps/labrinth/AGENTS.md index bc49e1cc938..d2ce34609a5 100644 --- a/apps/labrinth/AGENTS.md +++ b/apps/labrinth/AGENTS.md @@ -8,16 +8,16 @@ - `ApiError::Request` instead of `ApiError::InvalidInput` - `ApiError::Auth` instead of `ApiError::CustomAuthentication` - `ApiError::Internal` for database errors, 3rd party service errors, anything else internal - - Use `eyre!` to construct a value for `Internal`, `Request`, and `Auth` variants + - Use `anyhow!` to construct a value for `Internal`, `Request`, and `Auth` variants - Error messages (both for errors and exceptions) must be formatted as per the Rust API guidelines: - lowercase message - no trailing punctuation - wrap code items e.g. type names in backticks -- Prefer `wrap_internal_err`, `wrap_request_err` when attaching context to an existing error (like Anyhow `context` or Eyre `wrap_err`) -- Prefer importing `eyre::Result` and using `Result` instead of `eyre::Result` -- Prefer `eyre::Ok(value)` instead of `Ok::<_, eyre::Report>(value)` when an explicit Eyre result type is needed +- Prefer `internal_context`, `request_context` when attaching context to an existing error (like Anyhow `context`) +- Prefer importing `anyhow::Result` and using `Result` instead of `anyhow::Result` +- Prefer `anyhow::Ok(value)` instead of `Ok::<_, anyhow::Error>(value)` when an explicit Anyhow result type is needed - All operations should ideally have some context attached - - Database operations can have a message like `.wrap_internal_err("fetching XYZ")` + - Database operations can have a message like `.internal_context("fetching XYZ")` - You can perform real-time queries against the databases in the Docker Compose - `docker exec labrinth-postgres psql -c "select 1"` - `docker exec labrinth-redis redis-cli flushall` @@ -28,7 +28,7 @@ - `Authorization: Bearer mra_user` for a regular user - `Modrinth-Admin: feedbeef` as admin key - When using `sqlx::query` etc. always use the macro form like `sqlx::query!` or `sqlx::query_scalar!` - never the plain function form. Avoid using `query_as!`. -- Do not use `()` as an error type for operations, unless you have a very good reason. Either make a new error type, or use `eyre::Report`. +- Do not use `()` as an error type for operations, unless you have a very good reason. Either make a new error type, or use `anyhow::Error`. - Do not run `cargo test`, even for a single specific test, unless explicitly prompted to by the user, since it takes a long time to run. - You can force a search reindex by: - Running `cd apps/labrinth && cargo run -p labrinth -- --run-background-task index-search` (prefer this if backend is running locally) diff --git a/apps/labrinth/Cargo.toml b/apps/labrinth/Cargo.toml index 0f0ab6158bf..4f2c7b3f441 100644 --- a/apps/labrinth/Cargo.toml +++ b/apps/labrinth/Cargo.toml @@ -11,6 +11,7 @@ name = "labrinth" path = "src/main.rs" [dependencies] +anyhow = { workspace = true } actix-cors = { workspace = true } actix-files = { workspace = true } actix-http = { workspace = true } @@ -52,7 +53,6 @@ chrono = { workspace = true, features = ["serde"] } chumsky = { workspace = true } clap = { workspace = true, features = ["derive"] } clickhouse = { workspace = true, features = ["time", "uuid"] } -color-eyre = { workspace = true } color-thief = { workspace = true } component-derive = { workspace = true } const_format = { workspace = true } @@ -61,7 +61,6 @@ derive_more = { workspace = true, features = ["deref", "deref_mut"] } dioxus-devtools = { workspace = true } dotenvy = { workspace = true } either = { workspace = true } -eyre = { workspace = true } futures = { workspace = true } futures-util = { workspace = true } heck = { workspace = true } diff --git a/apps/labrinth/src/auth/checks.rs b/apps/labrinth/src/auth/checks.rs index c2c095f5afb..785834104e8 100644 --- a/apps/labrinth/src/auth/checks.rs +++ b/apps/labrinth/src/auth/checks.rs @@ -15,13 +15,14 @@ use crate::queue::file_scan::get_files_missing_attribution; use crate::routes::ApiError; use crate::util::error::ApiContext as _; use crate::util::error::Context as _; +use anyhow::anyhow; use futures::TryStreamExt; use itertools::Itertools; use xredis::RedisPool; pub fn require_verified_email(user: &User) -> Result<(), ApiError> { if !user.email_verified.unwrap_or(false) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "Please verify your email before publishing!" ))); } @@ -96,7 +97,7 @@ pub async fn filter_visible_projects( hide_unlisted, ) .await - .wrap_api_err("filtering visible project ids")?; + .api_context("filtering visible project ids")?; projects.retain(|x| filtered_project_ids.contains(&x.inner.id)); Ok(projects.into_iter().map(|x| x.into()).collect()) } @@ -136,7 +137,7 @@ pub async fn filter_visible_project_ids( return_projects.extend( filter_enlisted_projects_ids(check_projects, user_option, pool) .await - .wrap_api_err("filtering enlisted projects ids")?, + .api_context("filtering enlisted projects ids")?, ); } @@ -187,7 +188,7 @@ pub async fn filter_enlisted_projects_ids( }) .try_collect::>() .await - .wrap_internal_err("fetching query results from database")?; + .internal_context("fetching query results from database")?; } Ok(return_projects) } @@ -235,7 +236,7 @@ pub async fn filter_visible_versions( redis, ) .await - .wrap_api_err("filtering visible version ids")?; + .api_context("filtering visible version ids")?; let filtered_version_ids = filtered_version_ids .into_iter() .collect::>(); @@ -292,7 +293,7 @@ impl ValidateAuthorized for models::DBOAuthClient { { Ok(()) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( "You don't have sufficient permissions to interact with this OAuth application", ))) }; @@ -319,7 +320,7 @@ pub async fn filter_visible_version_ids( let visible_project_ids = filter_visible_project_ids( DBProject::get_many_ids(&project_ids, pool, redis) .await - .wrap_internal_err("fetching projects for visibility filtering")? + .internal_context("fetching projects for visibility filtering")? .iter() .map(|x| &x.inner) .collect(), @@ -328,7 +329,7 @@ pub async fn filter_visible_version_ids( false, ) .await - .wrap_api_err("filtering visible project IDs")?; + .api_context("filtering visible project IDs")?; // Then, get enlisted versions (Versions that are a part of a project we are a member of) let enlisted_version_ids = filter_enlisted_version_ids( @@ -339,7 +340,7 @@ pub async fn filter_visible_version_ids( redis, ) .await - .wrap_api_err("filtering enlisted version ids")?; + .api_context("filtering enlisted version ids")?; let withheld_versions = get_files_missing_attribution( pool, @@ -388,7 +389,7 @@ pub async fn filter_enlisted_version_ids( let authorized_project_ids = filter_enlisted_projects_ids( DBProject::get_many_ids(&project_ids, pool, redis) .await - .wrap_internal_err("fetching projects for membership filtering")? + .internal_context("fetching projects for membership filtering")? .iter() .map(|x| &x.inner) .collect(), @@ -396,7 +397,7 @@ pub async fn filter_enlisted_version_ids( pool, ) .await - .wrap_api_err("filtering projects by membership")?; + .api_context("filtering projects by membership")?; for version in versions { if user_option @@ -478,7 +479,7 @@ pub async fn is_visible_organization( let members = DBTeamMember::get_from_team_full(organization.team_id, pool, redis) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; // This is meant to match the same projects as the `Project::is_searchable` method, but we're not using // it here because that'd entail pulling in all projects for the organization @@ -487,7 +488,7 @@ pub async fn is_visible_organization( organization.id as database::models::ids::DBOrganizationId ) .fetch_optional(pool) - .await.wrap_internal_err("checking organization for searchable projects")? + .await.internal_context("checking organization for searchable projects")? .flatten() .unwrap_or(false); diff --git a/apps/labrinth/src/auth/mod.rs b/apps/labrinth/src/auth/mod.rs index a63ff2970c9..67f80f58e85 100644 --- a/apps/labrinth/src/auth/mod.rs +++ b/apps/labrinth/src/auth/mod.rs @@ -21,7 +21,7 @@ use thiserror::Error; #[derive(Error, Debug)] pub enum AuthenticationError { #[error(transparent)] - Internal(#[from] eyre::Report), + Internal(#[from] anyhow::Error), #[error("An unknown database error occurred: {0}")] Sqlx(#[from] sqlx::Error), #[error("Error while parsing JSON: {0}")] diff --git a/apps/labrinth/src/auth/oauth/errors.rs b/apps/labrinth/src/auth/oauth/errors.rs index e178c9f6829..b847632c8da 100644 --- a/apps/labrinth/src/auth/oauth/errors.rs +++ b/apps/labrinth/src/auth/oauth/errors.rs @@ -155,8 +155,8 @@ pub enum OAuthErrorType { AccessDenied, } -impl From for OAuthErrorType { - fn from(value: eyre::Report) -> Self { +impl From for OAuthErrorType { + fn from(value: anyhow::Error) -> Self { OAuthErrorType::AuthenticationError(value.into()) } } diff --git a/apps/labrinth/src/background_task.rs b/apps/labrinth/src/background_task.rs index 5852e360fef..90e258ed876 100644 --- a/apps/labrinth/src/background_task.rs +++ b/apps/labrinth/src/background_task.rs @@ -11,8 +11,8 @@ use crate::queue::file_scan::scan_all_pending_files; use crate::search::SearchBackend; use crate::util::anrok; use actix_web::web; +use anyhow::Context; use clap::ValueEnum; -use eyre::WrapErr; use tracing::{info, instrument}; use xredis::RedisPool; @@ -57,7 +57,7 @@ impl BackgroundTask { stripe_client: stripe::Client, anrok_client: anrok::Client, email_queue: EmailQueue, - ) -> eyre::Result<()> { + ) -> anyhow::Result<()> { use BackgroundTask::*; match self { Migrations => run_migrations().await, @@ -122,7 +122,7 @@ impl BackgroundTask { } } -pub async fn run_email(email_queue: EmailQueue) -> eyre::Result<()> { +pub async fn run_email(email_queue: EmailQueue) -> anyhow::Result<()> { // Only index for 5 emails at a time, to reduce transaction length, // for a total of 100 emails. for _ in 0..20 { @@ -131,7 +131,7 @@ pub async fn run_email(email_queue: EmailQueue) -> eyre::Result<()> { let indexed = email_queue .index(5) .await - .wrap_err("failed to index email queue")?; + .context("failed to index email queue")?; if indexed { info!("Indexed email queue in {}ms", then.elapsed().as_millis()); } else { @@ -143,11 +143,11 @@ pub async fn run_email(email_queue: EmailQueue) -> eyre::Result<()> { Ok(()) } -pub async fn run_migrations() -> eyre::Result<()> { +pub async fn run_migrations() -> anyhow::Result<()> { database::check_for_migrations().await?; crate::clickhouse::run_migrations() .await - .wrap_err("failed to run ClickHouse migrations")?; + .context("failed to run ClickHouse migrations")?; Ok(()) } @@ -155,12 +155,12 @@ pub async fn index_search( ro_pool: PgPool, redis_pool: RedisPool, search_backend: web::Data, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { info!("Indexing local database"); search_backend.rebuild_index(ro_pool, redis_pool).await } -pub async fn release_scheduled(pool: PgPool) -> eyre::Result<()> { +pub async fn release_scheduled(pool: PgPool) -> anyhow::Result<()> { info!("Releasing scheduled versions/projects!"); sqlx::query!( @@ -173,7 +173,7 @@ pub async fn release_scheduled(pool: PgPool) -> eyre::Result<()> { ) .execute(&pool) .await - .wrap_err("failed syncing scheduled releases for projects")?; + .context("failed syncing scheduled releases for projects")?; sqlx::query!( " @@ -185,7 +185,7 @@ pub async fn release_scheduled(pool: PgPool) -> eyre::Result<()> { ) .execute(&pool) .await - .wrap_err("failed syncing scheduled releases for versions")?; + .context("failed syncing scheduled releases for versions")?; info!("Finished releasing scheduled versions/projects"); Ok(()) @@ -194,19 +194,19 @@ pub async fn release_scheduled(pool: PgPool) -> eyre::Result<()> { pub async fn discord_role_email_campaign( pool: PgPool, redis_pool: RedisPool, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { info!("Started indexing Discord role email campaign"); let mut txn = pool .begin() .await - .wrap_err("failed to begin Discord role email campaign transaction")?; + .context("failed to begin Discord role email campaign transaction")?; let lock_acquired = crate::database::advisory_lock::AdvisoryLock::DiscordRoleEmailCampaign .try_acquire(&mut txn) .await - .wrap_err("failed to acquire Discord role email campaign lock")?; + .context("failed to acquire Discord role email campaign lock")?; if !lock_acquired { info!("Discord role email campaign is already running"); @@ -243,7 +243,7 @@ pub async fn discord_role_email_campaign( ) .fetch_all(&mut txn) .await - .wrap_err("failed to fetch Discord role email campaign recipients")? + .context("failed to fetch Discord role email campaign recipients")? .into_iter() .map(DBUserId) .collect::>(); @@ -256,12 +256,12 @@ pub async fn discord_role_email_campaign( } .insert_many(user_ids, &mut txn, &redis_pool) .await - .wrap_err("failed to queue Discord role email notifications")?; + .context("failed to queue Discord role email notifications")?; } txn.commit() .await - .wrap_err("failed to commit Discord role email campaign transaction")?; + .context("failed to commit Discord role email campaign transaction")?; info!(count, "Finished indexing Discord role email campaign"); Ok(()) @@ -272,7 +272,7 @@ pub async fn ping_minecraft_java_servers( redis_pool: RedisPool, clickhouse: clickhouse::Client, kafka_client: web::Data, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { info!("Started pinging Minecraft Java servers"); let incremental_search_queue = @@ -287,11 +287,11 @@ pub async fn ping_minecraft_java_servers( server_ping_queue .ping_minecraft_java_servers() .await - .wrap_err("failed to ping Minecraft Java servers")?; + .context("failed to ping Minecraft Java servers")?; incremental_search_queue .drain() .await - .wrap_err("failed to drain incremental search queue")?; + .context("failed to drain incremental search queue")?; info!("Successfully pinged Minecraft Java servers"); info!("Done pinging Minecraft Java servers"); diff --git a/apps/labrinth/src/bin/check_project.rs b/apps/labrinth/src/bin/check_project.rs index 75af3fe2815..b9b64b212ff 100644 --- a/apps/labrinth/src/bin/check_project.rs +++ b/apps/labrinth/src/bin/check_project.rs @@ -4,8 +4,8 @@ use std::fs::File; use std::io::{BufReader, IsTerminal}; use std::path::{Path, PathBuf}; +use anyhow::{Context, Result, anyhow}; use clap::Parser; -use eyre::{Result, WrapErr, eyre}; use labrinth::models::projects::{Project, Version}; use labrinth::validate::project::{ ProjectNagKind, ProjectNagSeverity, is_project_description_non_english, @@ -167,7 +167,6 @@ impl BatchSummary { #[tokio::main] async fn main() -> Result<()> { - color_eyre::install().wrap_err("installing color-eyre")?; let args = Args::parse(); if let Some(report_path) = args.read_profanity_report.as_deref() { @@ -180,7 +179,7 @@ async fn main() -> Result<()> { if let Some(report_path) = args.write_profanity_report.as_deref() { let dataset_path = args.file.as_deref().ok_or_else(|| { - eyre!("`--write-profanity-report` requires `--file`") + anyhow!("`--write-profanity-report` requires `--file`") })?; return profanity::write_report(dataset_path, report_path); } @@ -214,7 +213,7 @@ async fn main() -> Result<()> { let project_id = args .project_id .as_deref() - .ok_or_else(|| eyre!("a project ID or `--file` is required"))?; + .ok_or_else(|| anyhow!("a project ID or `--file` is required"))?; check_api_project(project_id, args.token.as_deref()).await } @@ -227,9 +226,9 @@ fn find_all_nag_project_ids( path: &Path, ) -> Result>> { let file = File::open(path) - .wrap_err_with(|| format!("opening `{}`", path.display()))?; + .with_context(|| format!("opening `{}`", path.display()))?; let dataset: ProjectDataset = serde_json::from_reader(BufReader::new(file)) - .wrap_err_with(|| format!("reading `{}`", path.display()))?; + .with_context(|| format!("reading `{}`", path.display()))?; let worker_count = std::thread::available_parallelism() .map(usize::from) .unwrap_or(1); @@ -260,7 +259,7 @@ fn find_all_nag_project_ids( .map(|worker| { worker .join() - .map_err(|_| eyre!("project validation worker panicked")) + .map_err(|_| anyhow!("project validation worker panicked")) }) .collect::>>() })?; @@ -283,9 +282,9 @@ fn find_language_project_ids( is_non_english: fn(&Project) -> bool, ) -> Result>> { let file = File::open(path) - .wrap_err_with(|| format!("opening `{}`", path.display()))?; + .with_context(|| format!("opening `{}`", path.display()))?; let dataset: ProjectDataset = serde_json::from_reader(BufReader::new(file)) - .wrap_err_with(|| format!("reading `{}`", path.display()))?; + .with_context(|| format!("reading `{}`", path.display()))?; let worker_count = std::thread::available_parallelism() .map(usize::from) .unwrap_or(1); @@ -306,7 +305,7 @@ fn find_language_project_ids( .map(|worker| { worker .join() - .map_err(|_| eyre!("language detection worker panicked")) + .map_err(|_| anyhow!("language detection worker panicked")) }) .collect::>>() .map(|ids| ids.into_iter().flatten().collect()) @@ -326,7 +325,7 @@ async fn check_api_project( env!("LABRINTH_VERSION") )) .build() - .wrap_err("building HTTP client")?; + .context("building HTTP client")?; let project_url = api_url(&["project", project_id])?; let mut versions_url = api_url(&["project", project_id, "version"])?; @@ -346,17 +345,17 @@ fn summarize_file( description_profanity_sample_limit: usize, ) -> Result { let file = File::open(path) - .wrap_err_with(|| format!("opening `{}`", path.display()))?; + .with_context(|| format!("opening `{}`", path.display()))?; let mut deserializer = serde_json::Deserializer::from_reader(BufReader::new(file)); let summary = DatasetSeed { description_profanity_sample_limit, } .deserialize(&mut deserializer) - .wrap_err_with(|| format!("reading `{}`", path.display()))?; + .with_context(|| format!("reading `{}`", path.display()))?; deserializer .end() - .wrap_err_with(|| format!("reading `{}`", path.display()))?; + .with_context(|| format!("reading `{}`", path.display()))?; Ok(summary) } @@ -392,15 +391,15 @@ fn print_description_profanity_samples(samples: &[DescriptionProfanitySample]) { fn print_json(value: &impl Serialize) -> Result<()> { println!( "{}", - serde_json::to_string_pretty(value).wrap_err("serializing output")? + serde_json::to_string_pretty(value).context("serializing output")? ); Ok(()) } fn api_url(path: &[&str]) -> Result { - let mut url = Url::parse(API_BASE_URL).wrap_err("parsing API base URL")?; + let mut url = Url::parse(API_BASE_URL).context("parsing API base URL")?; url.path_segments_mut() - .map_err(|_| eyre!("API base URL cannot be a base URL"))? + .map_err(|_| anyhow!("API base URL cannot be a base URL"))? .extend(path); Ok(url) } @@ -418,14 +417,14 @@ async fn fetch( let response = request .send() .await - .wrap_err_with(|| format!("requesting `{url}`"))? + .with_context(|| format!("requesting `{url}`"))? .error_for_status() - .wrap_err_with(|| format!("requesting `{url}`"))?; + .with_context(|| format!("requesting `{url}`"))?; response .json() .await - .wrap_err_with(|| format!("deserializing response from `{url}`")) + .with_context(|| format!("deserializing response from `{url}`")) } struct DatasetSeed { diff --git a/apps/labrinth/src/bin/check_project/profanity.rs b/apps/labrinth/src/bin/check_project/profanity.rs index 58a6af8de83..ea32977db69 100644 --- a/apps/labrinth/src/bin/check_project/profanity.rs +++ b/apps/labrinth/src/bin/check_project/profanity.rs @@ -3,7 +3,7 @@ use std::fs::File; use std::io::{BufReader, BufWriter, IsTerminal}; use std::path::Path; -use eyre::{Result, WrapErr, eyre}; +use anyhow::{Context, Result, anyhow}; use labrinth::models::projects::Project; use rustrict::{Censor, Type}; use serde::de::{DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor}; @@ -178,9 +178,9 @@ pub(super) fn write_report( ) -> Result<()> { let report = scan_dataset(dataset_path)?; let output = File::create(report_path) - .wrap_err_with(|| format!("creating `{}`", report_path.display()))?; + .with_context(|| format!("creating `{}`", report_path.display()))?; serde_json::to_writer_pretty(BufWriter::new(output), &report) - .wrap_err_with(|| format!("writing `{}`", report_path.display()))?; + .with_context(|| format!("writing `{}`", report_path.display()))?; eprintln!( "wrote {} projects with profanity across {} fields to `{}`", @@ -197,12 +197,12 @@ pub(super) fn render_report( force_brackets: bool, ) -> Result<()> { let input = File::open(report_path) - .wrap_err_with(|| format!("opening `{}`", report_path.display()))?; + .with_context(|| format!("opening `{}`", report_path.display()))?; let report: ProfanityReport = serde_json::from_reader(BufReader::new(input)) - .wrap_err_with(|| format!("reading `{}`", report_path.display()))?; + .with_context(|| format!("reading `{}`", report_path.display()))?; if report.format_version != REPORT_FORMAT_VERSION { - return Err(eyre!( + return Err(anyhow!( "unsupported profanity report format version `{}`", report.format_version )); @@ -268,15 +268,15 @@ pub(super) fn highlight_text(text: &str, use_color: bool) -> String { fn scan_dataset(path: &Path) -> Result { let input = File::open(path) - .wrap_err_with(|| format!("opening `{}`", path.display()))?; + .with_context(|| format!("opening `{}`", path.display()))?; let mut deserializer = serde_json::Deserializer::from_reader(BufReader::new(input)); let report = ProfanityDatasetSeed .deserialize(&mut deserializer) - .wrap_err_with(|| format!("reading `{}`", path.display()))?; + .with_context(|| format!("reading `{}`", path.display()))?; deserializer .end() - .wrap_err_with(|| format!("reading `{}`", path.display()))?; + .with_context(|| format!("reading `{}`", path.display()))?; Ok(report) } diff --git a/apps/labrinth/src/database/mod.rs b/apps/labrinth/src/database/mod.rs index ddc28fae47c..671217b6663 100644 --- a/apps/labrinth/src/database/mod.rs +++ b/apps/labrinth/src/database/mod.rs @@ -1,4 +1,4 @@ -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; pub struct MinecraftMetaDb(pub toasty::Db); @@ -12,7 +12,7 @@ impl MinecraftMetaDb { .models(toasty::models!(minecraft_meta_model::*)) .connect(database_url.as_str()) .await - .wrap_err("connecting to Minecraft metadata database")?; + .context("connecting to Minecraft metadata database")?; Ok(Self(db)) } } diff --git a/apps/labrinth/src/database/models/analytics_event_item.rs b/apps/labrinth/src/database/models/analytics_event_item.rs index 614ce680ab6..6a73bf6b0b9 100644 --- a/apps/labrinth/src/database/models/analytics_event_item.rs +++ b/apps/labrinth/src/database/models/analytics_event_item.rs @@ -1,5 +1,5 @@ +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use futures::{StreamExt, TryStreamExt}; use sqlx::types::Json; use xredis::RedisPool; @@ -38,7 +38,7 @@ impl DBAnalyticsEvent { ) .execute(exec) .await - .wrap_err("inserting analytics event")?; + .context("inserting analytics event")?; Ok(()) } @@ -60,7 +60,7 @@ impl DBAnalyticsEvent { ) .execute(exec) .await - .wrap_err("updating analytics event")?; + .context("updating analytics event")?; Ok(result.rows_affected() > 0) } @@ -78,7 +78,7 @@ impl DBAnalyticsEvent { ) .execute(exec) .await - .wrap_err("removing analytics event")?; + .context("removing analytics event")?; Ok(result.rows_affected() > 0) } @@ -90,7 +90,7 @@ impl DBAnalyticsEvent { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for analytics events")?; + .context("connecting to redis for analytics events")?; let key = redis .key() .metadata(ANALYTICS_EVENTS_NAMESPACE, ANALYTICS_EVENTS_ALL_KEY); @@ -98,7 +98,7 @@ impl DBAnalyticsEvent { if let Some(events) = redis .get_deserialized(&key) .await - .wrap_err("getting cached analytics events")? + .context("getting cached analytics events")? { return Ok(events); } @@ -112,9 +112,9 @@ impl DBAnalyticsEvent { ) .fetch(exec) .map(|record| { - let record = record.wrap_err("reading analytics event record")?; + let record = record.context("reading analytics event record")?; - eyre::Ok(DBAnalyticsEvent { + anyhow::Ok(DBAnalyticsEvent { id: DBAnalyticsEventId(record.id), meta: record.meta.0, starts: record.starts, @@ -123,12 +123,12 @@ impl DBAnalyticsEvent { }) .try_collect::>() .await - .wrap_err("fetching analytics events from database")?; + .context("fetching analytics events from database")?; redis .set_serialized(&key, &events, None) .await - .wrap_err("caching analytics events")?; + .context("caching analytics events")?; Ok(events) } @@ -137,14 +137,14 @@ impl DBAnalyticsEvent { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear analytics event cache")?; + .context("connecting to redis to clear analytics event cache")?; let key = redis .key() .metadata(ANALYTICS_EVENTS_NAMESPACE, ANALYTICS_EVENTS_ALL_KEY); redis .delete(&key) .await - .wrap_err("clearing analytics event cache")?; + .context("clearing analytics event cache")?; Ok(()) } } diff --git a/apps/labrinth/src/database/models/categories.rs b/apps/labrinth/src/database/models/categories.rs index c6c9d7b25e0..4c5d9d4c6ab 100644 --- a/apps/labrinth/src/database/models/categories.rs +++ b/apps/labrinth/src/database/models/categories.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use futures::TryStreamExt; use xredis::RedisPool; @@ -48,7 +48,7 @@ impl Category { ) .fetch_all(exec) .await - .wrap_err("fetching category ids")?; + .context("fetching category ids")?; let mut map = HashMap::new(); for r in result { @@ -76,7 +76,7 @@ impl Category { ) .fetch_optional(exec) .await - .wrap_err("fetching category id")?; + .context("fetching category id")?; Ok(result.map(|r| CategoryId(r.id))) } @@ -92,13 +92,13 @@ impl Category { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for cached categories")?; + .context("connecting to redis for cached categories")?; let key = redis.key().metadata(TAGS_NAMESPACE, "category"); let res: Option> = redis .get_deserialized(&key) .await - .wrap_err("fetching cached categories")?; + .context("fetching cached categories")?; if let Some(res) = res { return Ok(res); @@ -123,18 +123,18 @@ impl Category { }) .try_collect::>() .await - .wrap_err("fetching categories")?; + .context("fetching categories")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache categories")?; + .context("connecting to redis to cache categories")?; let key = redis.key().metadata(TAGS_NAMESPACE, "category"); redis .set_serialized(&key, &result, None) .await - .wrap_err("caching categories")?; + .context("caching categories")?; Ok(result) } @@ -157,7 +157,7 @@ impl ReportType { ) .fetch_optional(exec) .await - .wrap_err("fetching report type id")?; + .context("fetching report type id")?; Ok(result.map(|r| ReportTypeId(r.id))) } @@ -170,14 +170,14 @@ impl ReportType { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for cached report types")?; + .context("connecting to redis for cached report types")?; let key = redis.key().metadata(TAGS_NAMESPACE, "report_type"); let res: Option> = redis .get_deserialized(&key) .await - .wrap_err("fetching cached report types")?; + .context("fetching cached report types")?; if let Some(res) = res { return Ok(res); @@ -193,18 +193,18 @@ impl ReportType { .map_ok(|c| c.name) .try_collect::>() .await - .wrap_err("fetching report types")?; + .context("fetching report types")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache report types")?; + .context("connecting to redis to cache report types")?; let key = redis.key().metadata(TAGS_NAMESPACE, "report_type"); redis .set_serialized(&key, &result, None) .await - .wrap_err("caching report types")?; + .context("caching report types")?; Ok(result) } @@ -227,7 +227,7 @@ impl ProjectType { ) .fetch_optional(exec) .await - .wrap_err("fetching project type id")?; + .context("fetching project type id")?; Ok(result.map(|r| ProjectTypeId(r.id))) } @@ -240,14 +240,14 @@ impl ProjectType { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for cached project types")?; + .context("connecting to redis for cached project types")?; let key = redis.key().metadata(TAGS_NAMESPACE, "project_type"); let res: Option> = redis .get_deserialized(&key) .await - .wrap_err("fetching cached project types")?; + .context("fetching cached project types")?; if let Some(res) = res { return Ok(res); @@ -263,18 +263,18 @@ impl ProjectType { .map_ok(|c| c.name) .try_collect::>() .await - .wrap_err("fetching project types")?; + .context("fetching project types")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache project types")?; + .context("connecting to redis to cache project types")?; let key = redis.key().metadata(TAGS_NAMESPACE, "project_type"); redis .set_serialized(&key, &result, None) .await - .wrap_err("caching project types")?; + .context("caching project types")?; Ok(result) } diff --git a/apps/labrinth/src/database/models/charge_item.rs b/apps/labrinth/src/database/models/charge_item.rs index 5f79d26a4ae..9ffa8624d80 100644 --- a/apps/labrinth/src/database/models/charge_item.rs +++ b/apps/labrinth/src/database/models/charge_item.rs @@ -5,8 +5,8 @@ use crate::database::models::{ use crate::models::billing::{ ChargeStatus, ChargeType, PaymentPlatform, PriceDuration, }; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use std::convert::{TryFrom, TryInto}; #[derive(Clone)] @@ -177,7 +177,7 @@ impl DBCharge { ) .execute(&mut *transaction) .await - .wrap_err("upserting charge")?; + .context("upserting charge")?; Ok(self.id) } @@ -190,7 +190,7 @@ impl DBCharge { let res = select_charges_with_predicate!("WHERE id = $1", id) .fetch_optional(exec) .await - .wrap_err("fetching charge")?; + .context("fetching charge")?; Ok(res.and_then(|r| r.try_into().ok())) } @@ -206,12 +206,12 @@ impl DBCharge { ) .fetch_all(exec) .await - .wrap_err("fetching charges for user")?; + .context("fetching charges for user")?; res.into_iter() .map(|r| r.try_into()) .collect::, serde_json::Error>>() - .wrap_err("parsing charges for user") + .context("parsing charges for user") } pub async fn get_children( @@ -225,12 +225,12 @@ impl DBCharge { ) .fetch_all(exec) .await - .wrap_err("fetching child charges")?; + .context("fetching child charges")?; res.into_iter() .map(|r| r.try_into()) .collect::, serde_json::Error>>() - .wrap_err("parsing child charges") + .context("parsing child charges") } pub async fn get_open_subscription( @@ -247,7 +247,7 @@ impl DBCharge { ) .fetch_optional(exec) .await - .wrap_err("fetching open subscription charge")?; + .context("fetching open subscription charge")?; Ok(res.and_then(|r| r.try_into().ok())) } @@ -269,12 +269,12 @@ impl DBCharge { ) .fetch_all(exec) .await - .wrap_err("fetching chargeable charges")?; + .context("fetching chargeable charges")?; res.into_iter() .map(|r| r.try_into()) .collect::, serde_json::Error>>() - .wrap_err("parsing chargeable charges") + .context("parsing chargeable charges") } pub async fn get_unprovision( @@ -297,12 +297,12 @@ impl DBCharge { ) .fetch_all(exec) .await - .wrap_err("fetching charges to unprovision")?; + .context("fetching charges to unprovision")?; res.into_iter() .map(|r| r.try_into()) .collect::, serde_json::Error>>() - .wrap_err("parsing charges to unprovision") + .context("parsing charges to unprovision") } pub async fn get_cancellable( @@ -319,12 +319,12 @@ impl DBCharge { ) .fetch_all(exec) .await - .wrap_err("fetching cancellable charges")?; + .context("fetching cancellable charges")?; res.into_iter() .map(|r| r.try_into()) .collect::, serde_json::Error>>() - .wrap_err("parsing cancellable charges") + .context("parsing cancellable charges") } /// Returns all charges that need to have their tax amount updated. @@ -357,12 +357,12 @@ impl DBCharge { ) .fetch_all(exec) .await - .wrap_err("fetching charges requiring tax updates")?; + .context("fetching charges requiring tax updates")?; res.into_iter() .map(|r| r.try_into()) .collect::, serde_json::Error>>() - .wrap_err("parsing charges requiring tax updates") + .context("parsing charges requiring tax updates") } /// Returns all charges which are missing a tax identifier, that is, are succeeded and haven't been assigned a tax identifier yet. @@ -389,12 +389,12 @@ impl DBCharge { ) .fetch_all(exec) .await - .wrap_err("fetching charges missing tax identifiers")?; + .context("fetching charges missing tax identifiers")?; res.into_iter() .map(|r| r.try_into()) .collect::, serde_json::Error>>() - .wrap_err("parsing charges missing tax identifiers") + .context("parsing charges missing tax identifiers") } pub async fn remove( @@ -410,7 +410,7 @@ impl DBCharge { ) .execute(&mut *transaction) .await - .wrap_err("removing charge")?; + .context("removing charge")?; Ok(()) } diff --git a/apps/labrinth/src/database/models/collection_item.rs b/apps/labrinth/src/database/models/collection_item.rs index 6d212cb56c1..286b8ee5dfe 100644 --- a/apps/labrinth/src/database/models/collection_item.rs +++ b/apps/labrinth/src/database/models/collection_item.rs @@ -1,9 +1,9 @@ use super::ids::*; use crate::database::{PgTransaction, models}; use crate::models::collections::CollectionStatus; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -41,7 +41,7 @@ impl CollectionBuilder { collection_struct .insert(transaction) .await - .wrap_err("inserting built collection")?; + .context("inserting built collection")?; Ok(self.collection_id) } @@ -88,7 +88,7 @@ impl DBCollection { ) .execute(&mut *transaction) .await - .wrap_err("inserting collection")?; + .context("inserting collection")?; let (collection_ids, project_ids): (Vec<_>, Vec<_>) = self.projects.iter().map(|p| (self.id.0, p.0)).unzip(); @@ -103,7 +103,7 @@ impl DBCollection { ) .execute(&mut *transaction) .await - .wrap_err("inserting collection projects")?; + .context("inserting collection projects")?; Ok(()) } @@ -115,7 +115,7 @@ impl DBCollection { ) -> Result> { let collection = Self::get(id, &mut *transaction, redis) .await - .wrap_err("fetching collection to remove")?; + .context("fetching collection to remove")?; if let Some(collection) = collection { sqlx::query!( @@ -127,7 +127,7 @@ impl DBCollection { ) .execute(&mut *transaction) .await - .wrap_err("deleting collection projects")?; + .context("deleting collection projects")?; sqlx::query!( " @@ -138,11 +138,11 @@ impl DBCollection { ) .execute(&mut *transaction) .await - .wrap_err("deleting collection")?; + .context("deleting collection")?; models::DBCollection::clear_cache(collection.id, redis) .await - .wrap_err("clearing removed collection cache")?; + .context("clearing removed collection cache")?; Ok(Some(())) } else { @@ -160,7 +160,7 @@ impl DBCollection { { DBCollection::get_many(&[id], executor, redis) .await - .wrap_err("fetching collection") + .context("fetching collection") .map(|x| x.into_iter().next()) } @@ -218,7 +218,7 @@ impl DBCollection { }, ) .await - .wrap_err("fetching cached collections")?; + .context("fetching cached collections")?; Ok(val) } @@ -230,13 +230,13 @@ impl DBCollection { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear collection cache")?; + .context("connecting to redis to clear collection cache")?; let key = redis.key().entity(COLLECTIONS_NAMESPACE, id.0); redis .delete(&key) .await - .wrap_err("clearing collection cache")?; + .context("clearing collection cache")?; Ok(()) } } diff --git a/apps/labrinth/src/database/models/delphi_report_item.rs b/apps/labrinth/src/database/models/delphi_report_item.rs index c954205e65a..3fef63b8945 100644 --- a/apps/labrinth/src/database/models/delphi_report_item.rs +++ b/apps/labrinth/src/database/models/delphi_report_item.rs @@ -3,8 +3,8 @@ use std::{ fmt::{self, Display, Formatter}, }; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; use sqlx::types::Json; @@ -53,7 +53,7 @@ impl DBDelphiReport { ) .fetch_one(&mut *transaction) .await - .wrap_err("upserting delphi report")?)) + .context("upserting delphi report")?)) } } @@ -206,7 +206,7 @@ impl DBDelphiReportIssue { ) .fetch_one(&mut *transaction) .await - .wrap_err("upserting delphi report issue")?, + .context("upserting delphi report issue")?, )) } @@ -226,7 +226,7 @@ impl DBDelphiReportIssue { ) .fetch_one(&mut *transaction) .await - .wrap_err("inserting delphi report issue")?, + .context("inserting delphi report issue")?, )) } } @@ -291,7 +291,7 @@ impl ReportIssueDetail { ) .fetch_one(&mut *transaction) .await - .wrap_err("inserting delphi report issue detail")?)) + .context("inserting delphi report issue detail")?)) } pub async fn remove_all_by_issue_id( @@ -304,7 +304,7 @@ impl ReportIssueDetail { ) .execute(&mut *transaction) .await - .wrap_err("removing delphi report issue details")? + .context("removing delphi report issue details")? .rows_affected()) } } diff --git a/apps/labrinth/src/database/models/flow_item.rs b/apps/labrinth/src/database/models/flow_item.rs index 0257ec6d0a2..6b1e42eb5f3 100644 --- a/apps/labrinth/src/database/models/flow_item.rs +++ b/apps/labrinth/src/database/models/flow_item.rs @@ -2,8 +2,8 @@ use super::ids::*; use crate::auth::oauth::uris::OAuthRedirectUris; use crate::models::pats::Scopes; use crate::{auth::AuthProvider, routes::internal::flows::TempUser}; +use anyhow::{Context, Result}; use chrono::Duration; -use eyre::{Result, WrapErr}; use rand::RngExt; use rand::distr::Alphanumeric; use rand_chacha::ChaCha20Rng; @@ -108,13 +108,13 @@ impl DBFlow { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to insert flow")?; + .context("connecting to redis to insert flow")?; let key = redis.key().entity(FLOWS_NAMESPACE, state); redis .set_serialized(&key, &self, Some(expires.num_seconds())) .await - .wrap_err("inserting flow into redis")?; + .context("inserting flow into redis")?; Ok(()) } @@ -131,7 +131,7 @@ impl DBFlow { self.insert_with_state(expires, redis, &state) .await - .wrap_err("inserting flow with generated state")?; + .context("inserting flow with generated state")?; Ok(state) } @@ -139,13 +139,13 @@ impl DBFlow { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to get flow")?; + .context("connecting to redis to get flow")?; let key = redis.key().entity(FLOWS_NAMESPACE, id); redis .get_deserialized(&key) .await - .wrap_err("getting flow from redis") + .context("getting flow from redis") } /// Gets the flow and removes it from the cache, but only removes if the flow was present and the predicate returned true @@ -157,13 +157,13 @@ impl DBFlow { ) -> Result> { let flow = Self::get(id, redis) .await - .wrap_err("getting flow before conditional removal")?; + .context("getting flow before conditional removal")?; if let Some(flow) = flow.as_ref() && predicate(flow) { Self::remove(id, redis) .await - .wrap_err("removing flow after predicate matched")?; + .context("removing flow after predicate matched")?; } Ok(flow) } @@ -172,13 +172,13 @@ impl DBFlow { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to remove flow")?; + .context("connecting to redis to remove flow")?; let key = redis.key().entity(FLOWS_NAMESPACE, id); redis .delete(&key) .await - .wrap_err("removing flow from redis")?; + .context("removing flow from redis")?; Ok(Some(())) } } diff --git a/apps/labrinth/src/database/models/ids.rs b/apps/labrinth/src/database/models/ids.rs index ae050ac2f82..a634f966c60 100644 --- a/apps/labrinth/src/database/models/ids.rs +++ b/apps/labrinth/src/database/models/ids.rs @@ -8,10 +8,10 @@ use crate::models::ids::{ ThreadId, ThreadIssueFacetId, ThreadIssueId, ThreadMessageId, UserSubscriptionId, VersionId, }; +use anyhow::{Context, Result, anyhow}; use ariadne::ids::base62_impl::to_base62; use ariadne::ids::{UserId, random_base62_rng, random_base62_rng_range}; use censor::Censor; -use eyre::{Result, WrapErr}; use paste::paste; use rand::SeedableRng; use rand_chacha::ChaCha20Rng; @@ -36,7 +36,7 @@ macro_rules! generate_ids { let results = sqlx::query!($select_stmnt, id as i64) .fetch_one(&mut *con) .await - .wrap_err("checking generated ID uniqueness")?; + .context("checking generated ID uniqueness")?; if results.exists.unwrap_or(true) || censor.check(&*to_base62(id)) @@ -48,7 +48,7 @@ macro_rules! generate_ids { retry_count += 1; if retry_count > ID_RETRY_COUNT { - return Err(eyre::eyre!( + return Err(anyhow!( "failed to generate a unique random ID" )); } @@ -79,7 +79,7 @@ macro_rules! generate_bulk_ids { let results = sqlx::query!($select_stmnt, &ids) .fetch_one(&mut *con) .await - .wrap_err("checking generated ID uniqueness")?; + .context("checking generated ID uniqueness")?; if !results.exists.unwrap_or(true) { return Ok(ids @@ -90,7 +90,7 @@ macro_rules! generate_bulk_ids { retry_count += 1; if retry_count > ID_RETRY_COUNT { - return Err(eyre::eyre!( + return Err(anyhow!( "failed to generate unique random IDs" )); } diff --git a/apps/labrinth/src/database/models/image_item.rs b/apps/labrinth/src/database/models/image_item.rs index ae24846222a..ab17fc3e0c3 100644 --- a/apps/labrinth/src/database/models/image_item.rs +++ b/apps/labrinth/src/database/models/image_item.rs @@ -1,9 +1,9 @@ use super::ids::*; use crate::database::PgTransaction; use crate::models::images::ImageContext; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -55,7 +55,7 @@ impl DBImage { ) .execute(&mut *transaction) .await - .wrap_err("inserting uploaded image")?; + .context("inserting uploaded image")?; Ok(()) } @@ -67,7 +67,7 @@ impl DBImage { ) -> Result> { let image = Self::get(id, &mut *transaction, redis) .await - .wrap_err("fetching uploaded image to remove")?; + .context("fetching uploaded image to remove")?; if let Some(image) = image { sqlx::query!( @@ -79,11 +79,11 @@ impl DBImage { ) .execute(&mut *transaction) .await - .wrap_err("deleting uploaded image")?; + .context("deleting uploaded image")?; DBImage::clear_cache(image.id, redis) .await - .wrap_err("clearing removed uploaded image cache")?; + .context("clearing removed uploaded image cache")?; Ok(Some(())) } else { @@ -177,7 +177,7 @@ impl DBImage { { DBImage::get_many(&[id], executor, redis) .await - .wrap_err("fetching uploaded image") + .context("fetching uploaded image") .map(|x| x.into_iter().next()) } @@ -227,7 +227,7 @@ impl DBImage { }, ) .await - .wrap_err("fetching cached uploaded images")?; + .context("fetching cached uploaded images")?; Ok(val) } @@ -236,13 +236,13 @@ impl DBImage { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear uploaded image cache")?; + .context("connecting to redis to clear uploaded image cache")?; let key = redis.key().entity(IMAGES_NAMESPACE, id.0); redis .delete(&key) .await - .wrap_err("clearing uploaded image cache")?; + .context("clearing uploaded image cache")?; Ok(()) } } diff --git a/apps/labrinth/src/database/models/loader_item.rs b/apps/labrinth/src/database/models/loader_item.rs index 92e6160ca15..9b445f7d7c9 100644 --- a/apps/labrinth/src/database/models/loader_item.rs +++ b/apps/labrinth/src/database/models/loader_item.rs @@ -1,5 +1,5 @@ use super::ids::LoaderId; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use futures::TryStreamExt; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -35,12 +35,12 @@ impl Loader { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for cached loader id")?; + .context("connecting to redis for cached loader id")?; let key = redis.key().metadata(LOADER_ID, name); let cached_id: Option = redis .get_deserialized(&key) .await - .wrap_err("fetching cached loader id")?; + .context("fetching cached loader id")?; if let Some(cached_id) = cached_id { return Ok(Some(LoaderId(cached_id))); } @@ -55,19 +55,19 @@ impl Loader { ) .fetch_optional(exec) .await - .wrap_err("fetching loader id")? + .context("fetching loader id")? .map(|r| LoaderId(r.id)); if let Some(result) = result { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache loader id")?; + .context("connecting to redis to cache loader id")?; let key = redis.key().metadata(LOADER_ID, name); redis .set_serialized(&key, &result.0, None) .await - .wrap_err("caching loader id")?; + .context("caching loader id")?; } Ok(result) @@ -81,12 +81,12 @@ impl Loader { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for cached loaders")?; + .context("connecting to redis for cached loaders")?; let key = redis.key().metadata(LOADERS_LIST_NAMESPACE, "all"); let cached_loaders: Option> = redis .get_deserialized(&key) .await - .wrap_err("fetching cached loaders")?; + .context("fetching cached loaders")?; if let Some(cached_loaders) = cached_loaders { return Ok(cached_loaders); } @@ -122,18 +122,18 @@ impl Loader { }) .try_collect::>() .await - .wrap_err("fetching loaders")?; + .context("fetching loaders")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache loaders")?; + .context("connecting to redis to cache loaders")?; let key = redis.key().metadata(LOADERS_LIST_NAMESPACE, "all"); redis .set_serialized(&key, &result, None) .await - .wrap_err("caching loaders")?; + .context("caching loaders")?; Ok(result) } diff --git a/apps/labrinth/src/database/models/moderation_note_item.rs b/apps/labrinth/src/database/models/moderation_note_item.rs index 5ddd580d08e..c31b4d5b317 100644 --- a/apps/labrinth/src/database/models/moderation_note_item.rs +++ b/apps/labrinth/src/database/models/moderation_note_item.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -34,7 +34,7 @@ impl DBModerationNote { E: crate::database::Executor<'a, Database = sqlx::Postgres>, { let cached = { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to redis to fetch user moderation notes", )?; let keys = user_ids @@ -46,7 +46,7 @@ impl DBModerationNote { redis .get_many_deserialized::(&keys) .await - .wrap_err("fetching cached user moderation notes")? + .context("fetching cached user moderation notes")? }; let mut notes = HashMap::new(); @@ -73,12 +73,12 @@ impl DBModerationNote { ) .fetch_all(exec) .await - .wrap_err("fetching user moderation notes")?; + .context("fetching user moderation notes")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache user moderation notes")?; + .context("connecting to redis to cache user moderation notes")?; for row in rows { let note = Self { user_id: row.user_id.map(DBUserId), @@ -98,7 +98,7 @@ impl DBModerationNote { redis .set_serialized(&key, ¬e, None) .await - .wrap_err("caching user moderation note")?; + .context("caching user moderation note")?; notes.insert(user_id, note); } } @@ -116,7 +116,7 @@ impl DBModerationNote { { Ok(Self::get_many_users(&[user_id], exec, redis) .await - .wrap_err("fetching user moderation note")? + .context("fetching user moderation note")? .remove(&user_id)) } @@ -129,7 +129,7 @@ impl DBModerationNote { E: crate::database::Executor<'a, Database = sqlx::Postgres>, { let cached = { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to redis to fetch organization moderation notes", )?; let keys = organization_ids @@ -143,7 +143,7 @@ impl DBModerationNote { redis .get_many_deserialized::(&keys) .await - .wrap_err("fetching cached organization moderation notes")? + .context("fetching cached organization moderation notes")? }; let mut notes = HashMap::new(); @@ -170,9 +170,9 @@ impl DBModerationNote { ) .fetch_all(exec) .await - .wrap_err("fetching organization moderation notes")?; + .context("fetching organization moderation notes")?; - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to redis to cache organization moderation notes", )?; for row in rows { @@ -195,7 +195,7 @@ impl DBModerationNote { redis .set_serialized(&key, ¬e, None) .await - .wrap_err("caching organization moderation note")?; + .context("caching organization moderation note")?; notes.insert(organization_id, note); } } @@ -214,7 +214,7 @@ impl DBModerationNote { Ok( Self::get_many_organizations(&[organization_id], exec, redis) .await - .wrap_err("fetching organization moderation note")? + .context("fetching organization moderation note")? .remove(&organization_id), ) } @@ -252,7 +252,7 @@ impl DBModerationNote { ) .fetch_optional(exec) .await - .wrap_err("inserting moderation note")?; + .context("inserting moderation note")?; Ok(result) } @@ -294,7 +294,7 @@ impl DBModerationNote { ) .fetch_optional(exec) .await - .wrap_err("updating moderation note")?; + .context("updating moderation note")?; Ok(result) } @@ -303,7 +303,7 @@ impl DBModerationNote { user_id: DBUserId, redis: &RedisPool, ) -> Result<()> { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to redis to clear user moderation note cache", )?; let key = redis @@ -312,14 +312,14 @@ impl DBModerationNote { redis .delete(&key) .await - .wrap_err("clearing user moderation note cache") + .context("clearing user moderation note cache") } pub async fn clear_organization_cache( organization_id: DBOrganizationId, redis: &RedisPool, ) -> Result<()> { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to redis to clear organization moderation note cache", )?; let key = redis.key().entity( @@ -329,6 +329,6 @@ impl DBModerationNote { redis .delete(&key) .await - .wrap_err("clearing organization moderation note cache") + .context("clearing organization moderation note cache") } } diff --git a/apps/labrinth/src/database/models/notification_item.rs b/apps/labrinth/src/database/models/notification_item.rs index 1bc9e86d041..ce1ba356ab2 100644 --- a/apps/labrinth/src/database/models/notification_item.rs +++ b/apps/labrinth/src/database/models/notification_item.rs @@ -3,8 +3,8 @@ use crate::database::PgTransaction; use crate::models::notifications::{ NotificationBody, NotificationChannel, NotificationDeliveryStatus, }; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -42,7 +42,7 @@ impl NotificationBuilder { ) -> Result<()> { self.insert_many(vec![user], transaction, redis) .await - .wrap_err("inserting notification")?; + .context("inserting notification")?; Ok(()) } @@ -54,10 +54,10 @@ impl NotificationBuilder { let notification_ids = generate_many_notification_ids(users.len(), &mut *transaction) .await - .wrap_err("generating notification ids")?; + .context("generating notification ids")?; let body = serde_json::value::to_value(&self.body) - .wrap_err("serializing notification body")?; + .context("serializing notification body")?; let bodies = notification_ids .iter() .map(|_| body.clone()) @@ -80,7 +80,7 @@ impl NotificationBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting notification records")?; + .context("inserting notification records")?; Ok(notification_ids) } @@ -94,7 +94,7 @@ impl NotificationBuilder { let notification_ids = self .insert_many_records(&users, transaction) .await - .wrap_err("inserting notification records")?; + .context("inserting notification records")?; let users_raw_ids = users.iter().map(|x| x.0).collect::>(); let notification_ids_raw = @@ -114,7 +114,7 @@ impl NotificationBuilder { &users, ) .await - .wrap_err("inserting notification deliveries")?; + .context("inserting notification deliveries")?; Ok(notification_ids) } @@ -130,10 +130,10 @@ impl NotificationBuilder { let notification_ids = self .insert_many_records(&users, transaction) .await - .wrap_err("inserting notification records without delivery")?; + .context("inserting notification records without delivery")?; DBNotification::clear_user_notifications_cache(&users, redis) .await - .wrap_err("clearing notification caches")?; + .context("clearing notification caches")?; Ok(notification_ids) } @@ -225,11 +225,11 @@ impl NotificationBuilder { query .execute(&mut *transaction) .await - .wrap_err("inserting notification deliveries")?; + .context("inserting notification deliveries")?; DBNotification::clear_user_notifications_cache(users, redis) .await - .wrap_err( + .context( "clearing notification caches after inserting deliveries", )?; @@ -351,7 +351,7 @@ impl DBNotification { }) .try_collect::>() .await - .wrap_err("fetching all user notifications")?; + .context("fetching all user notifications")?; Ok(db_notifications) } @@ -369,14 +369,14 @@ impl DBNotification { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for user notifications")?; + .context("connecting to redis for user notifications")?; let key = redis.key().entity(USER_NOTIFICATIONS_NAMESPACE, user_id.0); let cached_notifications: Option> = redis .get_deserialized(&key) .await - .wrap_err("fetching cached user notifications")?; + .context("fetching cached user notifications")?; if let Some(notifications) = cached_notifications { return Ok(notifications); @@ -426,18 +426,18 @@ impl DBNotification { }) .try_collect::>() .await - .wrap_err("fetching site-exposed user notifications")?; + .context("fetching site-exposed user notifications")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache user notifications")?; + .context("connecting to redis to cache user notifications")?; let key = redis.key().entity(USER_NOTIFICATIONS_NAMESPACE, user_id.0); redis .set_serialized(&key, &db_notifications, None) .await - .wrap_err("caching site-exposed user notifications")?; + .context("caching site-exposed user notifications")?; Ok(db_notifications) } @@ -449,7 +449,7 @@ impl DBNotification { ) -> Result> { Self::read_many(&[id], transaction, redis) .await - .wrap_err("marking notification as read") + .context("marking notification as read") } pub async fn read_many( @@ -473,14 +473,14 @@ impl DBNotification { .map_ok(|x| DBUserId(x.user_id)) .try_collect::>() .await - .wrap_err("marking notifications as read")?; + .context("marking notifications as read")?; DBNotification::clear_user_notifications_cache( affected_users.iter(), redis, ) .await - .wrap_err( + .context( "clearing notification caches after marking notifications as read", )?; @@ -494,7 +494,7 @@ impl DBNotification { ) -> Result> { Self::remove_many(&[id], transaction, redis) .await - .wrap_err("removing notification") + .context("removing notification") } pub async fn remove_many( @@ -514,7 +514,7 @@ impl DBNotification { ) .execute(&mut *transaction) .await - .wrap_err("removing notification deliveries")?; + .context("removing notification deliveries")?; sqlx::query!( " @@ -525,7 +525,7 @@ impl DBNotification { ) .execute(&mut *transaction) .await - .wrap_err("removing notification actions")?; + .context("removing notification actions")?; let affected_users = sqlx::query!( " @@ -539,16 +539,14 @@ impl DBNotification { .map_ok(|x| DBUserId(x.user_id)) .try_collect::>() .await - .wrap_err("removing notifications")?; + .context("removing notifications")?; DBNotification::clear_user_notifications_cache( affected_users.iter(), redis, ) .await - .wrap_err( - "clearing notification caches after removing notifications", - )?; + .context("clearing notification caches after removing notifications")?; Ok(Some(())) } @@ -575,7 +573,7 @@ impl DBNotification { .map_ok(|x| DBNotificationId(x.id)) .try_collect::>() .await - .wrap_err("fetching notifications matching body")?; + .context("fetching notifications matching body")?; if ids.is_empty() { return Ok(0); @@ -583,7 +581,7 @@ impl DBNotification { Self::remove_many(&ids, transaction, redis) .await - .wrap_err("removing notifications matching body")?; + .context("removing notifications matching body")?; Ok(ids.len()) } @@ -595,7 +593,7 @@ impl DBNotification { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear notification caches")?; + .context("connecting to redis to clear notification caches")?; let keys = user_ids .into_iter() .map(|id| redis.key().entity(USER_NOTIFICATIONS_NAMESPACE, id.0)) @@ -604,7 +602,7 @@ impl DBNotification { redis .delete_many(&keys) .await - .wrap_err("clearing notification caches")?; + .context("clearing notification caches")?; Ok(()) } diff --git a/apps/labrinth/src/database/models/notifications_deliveries_item.rs b/apps/labrinth/src/database/models/notifications_deliveries_item.rs index d463d417f2e..5248290d45a 100644 --- a/apps/labrinth/src/database/models/notifications_deliveries_item.rs +++ b/apps/labrinth/src/database/models/notifications_deliveries_item.rs @@ -2,8 +2,8 @@ use super::ids::*; use crate::models::v3::notifications::{ NotificationChannel, NotificationDeliveryStatus, }; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; pub struct DBNotificationDelivery { pub id: i64, @@ -69,7 +69,7 @@ impl DBNotificationDelivery { ) .fetch_all(exec) .await - .wrap_err("fetching notification deliveries for user")?; + .context("fetching notification deliveries for user")?; Ok(results.into_iter().map(|r| r.into()).collect()) } @@ -100,7 +100,7 @@ impl DBNotificationDelivery { ) .fetch_all(exec) .await - .wrap_err("locking processable notification deliveries")? + .context("locking processable notification deliveries")? .into_iter() .map(Into::into) .collect()) @@ -129,7 +129,7 @@ impl DBNotificationDelivery { ) .fetch_one(exec) .await - .wrap_err("inserting notification delivery")?; + .context("inserting notification delivery")?; self.id = id; @@ -159,7 +159,7 @@ impl DBNotificationDelivery { ) .execute(exec) .await - .wrap_err("updating notification delivery")?; + .context("updating notification delivery")?; Ok(()) } diff --git a/apps/labrinth/src/database/models/notifications_template_item.rs b/apps/labrinth/src/database/models/notifications_template_item.rs index f87df0bfd39..cc318ea0328 100644 --- a/apps/labrinth/src/database/models/notifications_template_item.rs +++ b/apps/labrinth/src/database/models/notifications_template_item.rs @@ -2,7 +2,7 @@ use crate::models::v3::notifications::{NotificationChannel, NotificationType}; use crate::routes::ApiError; use crate::util::error::ApiContext as _; use crate::util::error::Context as _; -use eyre::Result; +use anyhow::Result; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -59,14 +59,14 @@ impl NotificationTemplate { let mut redis = redis .connect() .await - .wrap_err("connecting to Redis for notification templates")?; + .context("connecting to Redis for notification templates")?; let key = redis.key().metadata(TEMPLATES_NAMESPACE, channel.as_str()); let maybe_cached_templates = redis .get_deserialized(&key) .await - .wrap_err("fetching notification templates from cache")?; + .context("fetching notification templates from cache")?; if let Some(cached) = maybe_cached_templates { return Ok(cached); @@ -82,20 +82,20 @@ impl NotificationTemplate { ) .fetch_all(exec) .await - .wrap_err("fetching notification templates")?; + .context("fetching notification templates")?; let templates = results.into_iter().map(Into::into).collect(); let mut redis = redis .connect() .await - .wrap_err("connecting to Redis to cache notification templates")?; + .context("connecting to Redis to cache notification templates")?; let key = redis.key().metadata(TEMPLATES_NAMESPACE, channel.as_str()); redis .set_serialized(&key, &templates, Some(TEMPLATES_CACHE_EXPIRY)) .await - .wrap_err("caching notification templates")?; + .context("caching notification templates")?; Ok(templates) } @@ -104,14 +104,14 @@ impl NotificationTemplate { &self, redis: &RedisPool, ) -> Result> { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to Redis for cached notification template HTML", )?; let key = redis.key().metadata(TEMPLATES_HTML_DATA_NAMESPACE, self.id); redis .get_deserialized(&key) .await - .wrap_err("fetching cached notification template HTML") + .context("fetching cached notification template HTML") } pub async fn set_cached_html_data( @@ -119,14 +119,14 @@ impl NotificationTemplate { data: String, redis: &RedisPool, ) -> Result<()> { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to Redis to cache notification template HTML", )?; let key = redis.key().metadata(TEMPLATES_HTML_DATA_NAMESPACE, self.id); redis .set_serialized(&key, &data, Some(HTML_DATA_CACHE_EXPIRY)) .await - .wrap_err("caching notification template HTML") + .context("caching notification template HTML") } } @@ -143,7 +143,7 @@ where html: String, } - let mut redis_conn = redis.connect().await.wrap_internal_err( + let mut redis_conn = redis.connect().await.internal_context( "connecting to redis for dynamic notification html", )?; let redis_key = redis_conn @@ -152,7 +152,7 @@ where if let Some(body) = redis_conn .get_deserialized::(&redis_key) .await - .wrap_internal_err("fetching dynamic notification html from redis")? + .internal_context("fetching dynamic notification html from redis")? { return Ok(body.html); } @@ -162,9 +162,9 @@ where let cached = HtmlBody { html: get() .await - .wrap_api_err("generating notification template HTML")?, + .api_context("generating notification template HTML")?, }; - let mut redis_conn = redis.connect().await.wrap_internal_err( + let mut redis_conn = redis.connect().await.internal_context( "connecting to redis for dynamic notification html", )?; let redis_key = redis_conn @@ -174,7 +174,7 @@ where redis_conn .set_serialized(&redis_key, &cached, Some(HTML_DATA_CACHE_EXPIRY)) .await - .wrap_internal_err("writing dynamic notification html to redis")?; + .internal_context("writing dynamic notification html to redis")?; Ok(cached.html) } diff --git a/apps/labrinth/src/database/models/notifications_type_item.rs b/apps/labrinth/src/database/models/notifications_type_item.rs index fb513d819e1..89b70ac9583 100644 --- a/apps/labrinth/src/database/models/notifications_type_item.rs +++ b/apps/labrinth/src/database/models/notifications_type_item.rs @@ -1,5 +1,5 @@ use crate::models::v3::notifications::NotificationType; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -43,13 +43,13 @@ impl NotificationTypeItem { let mut redis = redis .connect() .await - .wrap_err("connecting to Redis for notification types")?; + .context("connecting to Redis for notification types")?; let key = redis.key().metadata(NOTIFICATION_TYPES_NAMESPACE, "all"); let cached_types = redis .get_deserialized(&key) .await - .wrap_err("fetching notification types from cache")?; + .context("fetching notification types from cache")?; if let Some(types) = cached_types { return Ok(types); @@ -62,20 +62,20 @@ impl NotificationTypeItem { ) .fetch_all(exec) .await - .wrap_err("fetching notification types")?; + .context("fetching notification types")?; let types = results.into_iter().map(Into::into).collect(); let mut redis = redis .connect() .await - .wrap_err("connecting to Redis to cache notification types")?; + .context("connecting to Redis to cache notification types")?; let key = redis.key().metadata(NOTIFICATION_TYPES_NAMESPACE, "all"); redis .set_serialized(&key, &types, None) .await - .wrap_err("caching notification types")?; + .context("caching notification types")?; Ok(types) } diff --git a/apps/labrinth/src/database/models/oauth_client_authorization_item.rs b/apps/labrinth/src/database/models/oauth_client_authorization_item.rs index de692a3541a..7e97f6fdbc8 100644 --- a/apps/labrinth/src/database/models/oauth_client_authorization_item.rs +++ b/apps/labrinth/src/database/models/oauth_client_authorization_item.rs @@ -1,5 +1,5 @@ +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use itertools::Itertools; use serde::{Deserialize, Serialize}; @@ -54,7 +54,7 @@ impl DBOAuthClientAuthorization { ) .fetch_optional(exec) .await - .wrap_err("fetching oauth client authorization")?; + .context("fetching oauth client authorization")?; Ok(value.map(|r| r.into())) } @@ -74,7 +74,7 @@ impl DBOAuthClientAuthorization { ) .fetch_all(exec) .await - .wrap_err("fetching oauth client authorizations for user")?; + .context("fetching oauth client authorizations for user")?; Ok(results.into_iter().map(|r| r.into()).collect_vec()) } @@ -104,7 +104,7 @@ impl DBOAuthClientAuthorization { ) .execute(&mut *transaction) .await - .wrap_err("upserting oauth client authorization")?; + .context("upserting oauth client authorization")?; Ok(()) } @@ -124,7 +124,7 @@ impl DBOAuthClientAuthorization { ) .execute(exec) .await - .wrap_err("removing oauth client authorization")?; + .context("removing oauth client authorization")?; Ok(()) } diff --git a/apps/labrinth/src/database/models/oauth_client_item.rs b/apps/labrinth/src/database/models/oauth_client_item.rs index 6f70ffebae8..49ef1630299 100644 --- a/apps/labrinth/src/database/models/oauth_client_item.rs +++ b/apps/labrinth/src/database/models/oauth_client_item.rs @@ -1,5 +1,5 @@ +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use sha2::Digest; @@ -85,7 +85,7 @@ impl DBOAuthClient { ) -> Result> { Ok(Self::get_many(&[id], exec) .await - .wrap_err("fetching oauth client")? + .context("fetching oauth client")? .into_iter() .next()) } @@ -102,7 +102,7 @@ impl DBOAuthClient { ) .fetch_all(exec) .await - .wrap_err("fetching oauth clients")?; + .context("fetching oauth clients")?; Ok(results.into_iter().map(|r| r.into()).collect_vec()) } @@ -118,7 +118,7 @@ impl DBOAuthClient { ) .fetch_all(exec) .await - .wrap_err("fetching oauth clients for user")?; + .context("fetching oauth clients for user")?; Ok(clients.into_iter().map(|r| r.into()).collect()) } @@ -137,7 +137,7 @@ impl DBOAuthClient { ) .execute(exec) .await - .wrap_err("removing oauth client")?; + .context("removing oauth client")?; Ok(()) } @@ -165,11 +165,11 @@ impl DBOAuthClient { ) .execute(&mut *transaction) .await - .wrap_err("inserting oauth client")?; + .context("inserting oauth client")?; Self::insert_redirect_uris(&self.redirect_uris, &mut *transaction) .await - .wrap_err("inserting oauth client redirect uris")?; + .context("inserting oauth client redirect uris")?; Ok(()) } @@ -194,7 +194,7 @@ impl DBOAuthClient { ) .execute(exec) .await - .wrap_err("updating oauth client")?; + .context("updating oauth client")?; Ok(()) } @@ -214,7 +214,7 @@ impl DBOAuthClient { ) .execute(exec) .await - .wrap_err("removing oauth client redirect uris")?; + .context("removing oauth client redirect uris")?; Ok(()) } @@ -238,7 +238,7 @@ impl DBOAuthClient { ) .execute(exec) .await - .wrap_err("inserting oauth client redirect uris")?; + .context("inserting oauth client redirect uris")?; Ok(()) } diff --git a/apps/labrinth/src/database/models/oauth_token_item.rs b/apps/labrinth/src/database/models/oauth_token_item.rs index 34c733fdd07..41f58ae55b9 100644 --- a/apps/labrinth/src/database/models/oauth_token_item.rs +++ b/apps/labrinth/src/database/models/oauth_token_item.rs @@ -3,8 +3,8 @@ use super::{ DBUserId, }; use crate::models::pats::Scopes; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; use sha2::Digest; @@ -49,7 +49,7 @@ impl DBOAuthAccessToken { ) .fetch_optional(exec) .await - .wrap_err("fetching oauth access token")?; + .context("fetching oauth access token")?; Ok(value.map(|r| DBOAuthAccessToken { id: DBOAuthAccessTokenId(r.id), @@ -87,7 +87,7 @@ impl DBOAuthAccessToken { ) .fetch_one(exec) .await - .wrap_err("inserting oauth access token")?; + .context("inserting oauth access token")?; let (created, expires) = (r.created, r.expires); let time_until_expiration = expires - created; diff --git a/apps/labrinth/src/database/models/organization_item.rs b/apps/labrinth/src/database/models/organization_item.rs index b538db65c03..c209c42da98 100644 --- a/apps/labrinth/src/database/models/organization_item.rs +++ b/apps/labrinth/src/database/models/organization_item.rs @@ -1,7 +1,7 @@ use crate::database::PgTransaction; +use anyhow::{Context, Result}; use ariadne::ids::base62_impl::parse_base62; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use std::fmt::{Debug, Display}; use std::hash::Hash; @@ -58,7 +58,7 @@ impl DBOrganization { ) .execute(&mut *transaction) .await - .wrap_err("inserting organization")?; + .context("inserting organization")?; Ok(()) } @@ -73,7 +73,7 @@ impl DBOrganization { { Self::get_many(&[string], exec, redis) .await - .wrap_err("fetching organization") + .context("fetching organization") .map(|x| x.into_iter().next()) } @@ -87,7 +87,7 @@ impl DBOrganization { { Self::get_many_ids(&[id], exec, redis) .await - .wrap_err("fetching organization by id") + .context("fetching organization by id") .map(|x| x.into_iter().next()) } @@ -105,7 +105,7 @@ impl DBOrganization { .collect::>(); Self::get_many(&ids, exec, redis) .await - .wrap_err("fetching organizations by id") + .context("fetching organizations by id") } pub async fn get_many< @@ -167,7 +167,7 @@ impl DBOrganization { }, ) .await - .wrap_err("fetching cached organizations")?; + .context("fetching cached organizations")?; Ok(val) } @@ -192,7 +192,7 @@ impl DBOrganization { ) .fetch_optional(exec) .await - .wrap_err("fetching organization associated with project")?; + .context("fetching organization associated with project")?; if let Some(result) = result { Ok(Some(DBOrganization { @@ -231,7 +231,7 @@ impl DBOrganization { .map_ok(|m| DBProjectId(m.id)) .try_collect::>() .await - .wrap_err("fetching organization projects")?; + .context("fetching organization projects")?; Ok(db_projects) } @@ -243,7 +243,7 @@ impl DBOrganization { ) -> Result> { let organization = Self::get_id(id, &mut *transaction, redis) .await - .wrap_err("fetching organization to remove")?; + .context("fetching organization to remove")?; if let Some(organization) = organization { sqlx::query!( @@ -255,11 +255,11 @@ impl DBOrganization { ) .execute(&mut *transaction) .await - .wrap_err("deleting organization")?; + .context("deleting organization")?; DBTeamMember::clear_cache(organization.team_id, redis) .await - .wrap_err("clearing removed organization team cache")?; + .context("clearing removed organization team cache")?; sqlx::query!( " @@ -270,7 +270,7 @@ impl DBOrganization { ) .execute(&mut *transaction) .await - .wrap_err("deleting organization team members")?; + .context("deleting organization team members")?; sqlx::query!( " @@ -281,7 +281,7 @@ impl DBOrganization { ) .execute(&mut *transaction) .await - .wrap_err("deleting organization team")?; + .context("deleting organization team")?; Ok(Some(())) } else { @@ -297,7 +297,7 @@ impl DBOrganization { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear organization cache")?; + .context("connecting to redis to clear organization cache")?; let mut keys = vec![redis.key().entity(ORGANIZATIONS_NAMESPACE, id.0)]; if let Some(slug) = slug { keys.push( @@ -311,7 +311,7 @@ impl DBOrganization { redis .delete_many(&keys) .await - .wrap_err("clearing organization cache")?; + .context("clearing organization cache")?; Ok(()) } } diff --git a/apps/labrinth/src/database/models/passkey_item.rs b/apps/labrinth/src/database/models/passkey_item.rs index 48650696ed5..cfd2e8af173 100644 --- a/apps/labrinth/src/database/models/passkey_item.rs +++ b/apps/labrinth/src/database/models/passkey_item.rs @@ -1,7 +1,7 @@ use super::ids::*; use crate::database::PgTransaction; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use serde::{Deserialize, Serialize}; use sqlx::types::Json; @@ -42,7 +42,7 @@ impl DBPasskey { ) .execute(&mut *transaction) .await - .wrap_err("inserting passkey")?; + .context("inserting passkey")?; Ok(()) } @@ -66,7 +66,7 @@ impl DBPasskey { ) .fetch_optional(exec) .await - .wrap_err("fetching passkey by credential id")? + .context("fetching passkey by credential id")? .map(|x| DBPasskey { id: DBPasskeyId(x.id), user_id: DBUserId(x.user_id), @@ -110,7 +110,7 @@ impl DBPasskey { }) .try_collect::>() .await - .wrap_err("fetching passkeys for user")?; + .context("fetching passkeys for user")?; Ok(passkeys) } @@ -132,7 +132,7 @@ impl DBPasskey { ) .execute(&mut *transaction) .await - .wrap_err("renaming passkey")?; + .context("renaming passkey")?; Ok(result.rows_affected() > 0) } @@ -153,7 +153,7 @@ impl DBPasskey { ) .execute(&mut *transaction) .await - .wrap_err("updating passkey after authentication")?; + .context("updating passkey after authentication")?; Ok(result.rows_affected() > 0) } @@ -171,7 +171,7 @@ impl DBPasskey { ) .execute(&mut *transaction) .await - .wrap_err("removing passkey")?; + .context("removing passkey")?; Ok(result.rows_affected() > 0) } @@ -191,7 +191,7 @@ impl DBPasskey { ) .execute(&mut *transaction) .await - .wrap_err("removing passkey for user")?; + .context("removing passkey for user")?; Ok(result.rows_affected() > 0) } diff --git a/apps/labrinth/src/database/models/pat_item.rs b/apps/labrinth/src/database/models/pat_item.rs index 17ad45969dd..2767d16c3a7 100644 --- a/apps/labrinth/src/database/models/pat_item.rs +++ b/apps/labrinth/src/database/models/pat_item.rs @@ -2,10 +2,10 @@ use super::ids::*; use crate::database::PgTransaction; use crate::models::pats::Scopes; +use anyhow::{Context, Result}; use ariadne::ids::base62_impl::parse_base62; use chrono::{DateTime, Utc}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use serde::{Deserialize, Serialize}; use std::fmt::{Debug, Display}; @@ -53,7 +53,7 @@ impl DBPersonalAccessToken { ) .execute(&mut *transaction) .await - .wrap_err("inserting personal access token")?; + .context("inserting personal access token")?; Ok(()) } @@ -72,7 +72,7 @@ impl DBPersonalAccessToken { { Self::get_many(&[id], exec, redis) .await - .wrap_err("fetching personal access token") + .context("fetching personal access token") .map(|x| x.into_iter().next()) } @@ -90,7 +90,7 @@ impl DBPersonalAccessToken { .collect::>(); DBPersonalAccessToken::get_many(&ids, exec, redis) .await - .wrap_err("fetching personal access tokens by ID") + .context("fetching personal access tokens by ID") } pub async fn get_many< @@ -130,7 +130,7 @@ impl DBPersonalAccessToken { &slugs, ) .fetch(exec) - .map_err(eyre::Report::from) + .map_err(anyhow::Error::from) .try_fold(DashMap::new(), |acc, x| { let pat = DBPersonalAccessToken { id: DBPatId(x.id), @@ -144,15 +144,15 @@ impl DBPersonalAccessToken { }; acc.insert(x.id, (Some(x.access_token), pat)); - async move { eyre::Ok(acc) } + async move { anyhow::Ok(acc) } }) .await - .wrap_err("fetching personal access tokens from database")?; - eyre::Ok(pats) + .context("fetching personal access tokens from database")?; + anyhow::Ok(pats) }, ) .await - .wrap_err("fetching personal access tokens")?; + .context("fetching personal access tokens")?; Ok(val) } @@ -169,7 +169,7 @@ impl DBPersonalAccessToken { true, &[access_token], |_| async { - eyre::Ok(DashMap::< + anyhow::Ok(DashMap::< i64, (Option, DBPersonalAccessToken), >::new()) @@ -177,7 +177,7 @@ impl DBPersonalAccessToken { ) .await .map(|x| x.into_iter().next()) - .wrap_err("getting cached personal access token") + .context("getting cached personal access token") } pub async fn get_user_pats<'a, E>( @@ -189,7 +189,7 @@ impl DBPersonalAccessToken { E: crate::database::Executor<'a, Database = sqlx::Postgres>, { { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to Redis for user personal access tokens", )?; let key = redis.key().entity(PATS_USERS_NAMESPACE, user_id.0); @@ -197,7 +197,7 @@ impl DBPersonalAccessToken { let res = redis .get_deserialized::>(&key) .await - .wrap_err("fetching user personal access tokens from cache")?; + .context("fetching user personal access tokens from cache")?; if let Some(res) = res { return Ok(res.into_iter().map(DBPatId).collect()); @@ -217,9 +217,9 @@ impl DBPersonalAccessToken { .map_ok(|x| DBPatId(x.id)) .try_collect::>() .await - .wrap_err("fetching user personal access tokens from database")?; + .context("fetching user personal access tokens from database")?; - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to Redis to cache user personal access tokens", )?; let key = redis.key().entity(PATS_USERS_NAMESPACE, user_id.0); @@ -227,7 +227,7 @@ impl DBPersonalAccessToken { redis .set_serialized(&key, &db_pats, None) .await - .wrap_err("caching user personal access tokens")?; + .context("caching user personal access tokens")?; Ok(db_pats) } @@ -235,7 +235,7 @@ impl DBPersonalAccessToken { clear_pats: Vec<(Option, Option, Option)>, redis: &RedisPool, ) -> Result<()> { - let mut redis = redis.connect().await.wrap_err( + let mut redis = redis.connect().await.context( "connecting to Redis to clear personal access token cache", )?; @@ -262,7 +262,7 @@ impl DBPersonalAccessToken { redis .delete_many(&keys) .await - .wrap_err("clearing personal access token cache")?; + .context("clearing personal access token cache")?; Ok(()) } @@ -279,7 +279,7 @@ impl DBPersonalAccessToken { ) .execute(&mut *transaction) .await - .wrap_err("removing personal access token")?; + .context("removing personal access token")?; Ok(Some(())) } @@ -298,7 +298,7 @@ impl DBPersonalAccessToken { .map_ok(|x| (DBPatId(x.id), x.access_token)) .try_collect() .await - .wrap_err("removing user personal access tokens")?; + .context("removing user personal access tokens")?; Ok(pats) } diff --git a/apps/labrinth/src/database/models/payout_item.rs b/apps/labrinth/src/database/models/payout_item.rs index 48541a2dcef..dafd4c2531e 100644 --- a/apps/labrinth/src/database/models/payout_item.rs +++ b/apps/labrinth/src/database/models/payout_item.rs @@ -2,8 +2,8 @@ use crate::{ database::PgTransaction, models::payouts::{PayoutMethodType, PayoutStatus}, }; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; @@ -53,7 +53,7 @@ impl DBPayout { ) .execute(&mut *transaction) .await - .wrap_err("inserting payout")?; + .context("inserting payout")?; Ok(()) } @@ -67,7 +67,7 @@ impl DBPayout { { DBPayout::get_many(&[id], executor) .await - .wrap_err("fetching payout") + .context("fetching payout") .map(|x| x.into_iter().next()) } @@ -103,7 +103,7 @@ impl DBPayout { }) .try_collect::>() .await - .wrap_err("fetching payouts")?; + .context("fetching payouts")?; Ok(results) } @@ -122,7 +122,7 @@ impl DBPayout { ) .fetch_all(exec) .await - .wrap_err("fetching payouts for user")?; + .context("fetching payouts for user")?; Ok(results .into_iter() diff --git a/apps/labrinth/src/database/models/payouts_values_notifications.rs b/apps/labrinth/src/database/models/payouts_values_notifications.rs index 53ca1bcb6c7..5a13d3d650d 100644 --- a/apps/labrinth/src/database/models/payouts_values_notifications.rs +++ b/apps/labrinth/src/database/models/payouts_values_notifications.rs @@ -1,6 +1,6 @@ use crate::database::models::DBUserId; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; pub struct PayoutsValuesNotification { pub id: i32, @@ -23,7 +23,7 @@ impl PayoutsValuesNotification { ) .execute(exec) .await - .wrap_err("marking payout value notifications as notified")?; + .context("marking payout value notifications as notified")?; Ok(()) } diff --git a/apps/labrinth/src/database/models/product_item.rs b/apps/labrinth/src/database/models/product_item.rs index 687b72d9d3f..60a24aef1af 100644 --- a/apps/labrinth/src/database/models/product_item.rs +++ b/apps/labrinth/src/database/models/product_item.rs @@ -1,7 +1,7 @@ use crate::database::models::{DBProductId, DBProductPriceId, product_item}; use crate::models::billing::{Price, ProductMetadata}; +use anyhow::{Context, Result}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; @@ -60,7 +60,7 @@ impl DBProduct { ) -> Result> { Ok(Self::get_many(&[id], exec) .await - .wrap_err("fetching product")? + .context("fetching product")? .into_iter() .next()) } @@ -76,12 +76,12 @@ impl DBProduct { ) .fetch_optional(exec) .await - .wrap_err("fetching product by price")?; + .context("fetching product by price")?; maybe_row .map(TryInto::try_into) .transpose() - .wrap_err("deserializing product metadata") + .context("deserializing product metadata") } pub async fn get_by_type<'a, E>(exec: E, r#type: &str) -> Result> @@ -94,13 +94,13 @@ impl DBProduct { ) .fetch_all(exec) .await - .wrap_err("fetching products by type")?; + .context("fetching products by type")?; maybe_row .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing product metadata") + .context("deserializing product metadata") } pub async fn get_many( @@ -115,13 +115,13 @@ impl DBProduct { ) .fetch_all(exec) .await - .wrap_err("fetching products")?; + .context("fetching products")?; results .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing product metadata") + .context("deserializing product metadata") } pub async fn get_all( @@ -131,13 +131,13 @@ impl DBProduct { let results = select_products_with_predicate!("WHERE 1 = $1", one) .fetch_all(exec) .await - .wrap_err("fetching all products")?; + .context("fetching all products")?; results .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing product metadata") + .context("deserializing product metadata") } } @@ -164,13 +164,13 @@ impl QueryProductWithPrices { let mut redis = redis .connect() .await - .wrap_err("connecting to Redis for purchasable products")?; + .context("connecting to Redis for purchasable products")?; let key = redis.key().metadata(PRODUCTS_NAMESPACE, "all"); let res: Option> = redis .get_deserialized(&key) .await - .wrap_err("fetching purchasable products from cache")?; + .context("fetching purchasable products from cache")?; if let Some(res) = res { return Ok(res); @@ -179,14 +179,14 @@ impl QueryProductWithPrices { let all_products = product_item::DBProduct::get_all(exec) .await - .wrap_err("fetching all products")?; + .context("fetching all products")?; let prices = product_item::DBProductPrice::get_all_public_products_prices( &all_products.iter().map(|x| x.id).collect::>(), exec, ) .await - .wrap_err("fetching public product prices")?; + .context("fetching public product prices")?; let products = all_products .into_iter() @@ -214,13 +214,13 @@ impl QueryProductWithPrices { let mut redis = redis .connect() .await - .wrap_err("connecting to Redis to cache purchasable products")?; + .context("connecting to Redis to cache purchasable products")?; let key = redis.key().metadata(PRODUCTS_NAMESPACE, "all"); redis .set_serialized(&key, &products, None) .await - .wrap_err("caching purchasable products")?; + .context("caching purchasable products")?; Ok(products) } @@ -234,13 +234,13 @@ impl QueryProductWithPrices { { let all_products = DBProduct::get_by_type(exec, r#type) .await - .wrap_err("fetching products by type")?; + .context("fetching products by type")?; let prices = DBProductPrice::get_all_products_prices( &all_products.iter().map(|x| x.id).collect::>(), exec, ) .await - .wrap_err("fetching product prices")?; + .context("fetching product prices")?; let products = all_products .into_iter() @@ -324,7 +324,7 @@ impl DBProductPrice { ) -> Result> { Ok(Self::get_many(&[id], exec) .await - .wrap_err("fetching product price")? + .context("fetching product price")? .into_iter() .next()) } @@ -341,13 +341,13 @@ impl DBProductPrice { ) .fetch_all(exec) .await - .wrap_err("fetching product prices")?; + .context("fetching product prices")?; results .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing product prices") + .context("deserializing product prices") } pub async fn get_all_product_prices( @@ -356,7 +356,7 @@ impl DBProductPrice { ) -> Result> { let res = Self::get_all_products_prices(&[product_id], exec) .await - .wrap_err("fetching product prices")?; + .context("fetching product prices")?; Ok(res.remove(&product_id).map(|x| x.1).unwrap_or_default()) } @@ -367,7 +367,7 @@ impl DBProductPrice { ) -> Result> { let res = Self::get_all_public_products_prices(&[product_id], exec) .await - .wrap_err("fetching public product prices")?; + .context("fetching public product prices")?; Ok(res.remove(&product_id).map(|x| x.1).unwrap_or_default()) } @@ -384,7 +384,7 @@ impl DBProductPrice { exec, ) .await - .wrap_err("fetching public product prices") + .context("fetching public product prices") } pub async fn get_all_products_prices( @@ -393,7 +393,7 @@ impl DBProductPrice { ) -> Result>> { Self::get_all_products_prices_with_visibility(product_ids, None, exec) .await - .wrap_err("fetching product prices") + .context("fetching product prices") } async fn get_all_products_prices_with_visibility( @@ -425,7 +425,7 @@ impl DBProductPrice { .fetch(exec) .try_fold(DashMap::new(), predicate) .await - .wrap_err("fetching product prices")?, + .context("fetching product prices")?, Some(public) => select_prices_with_predicate!( "WHERE product_id = ANY($1::bigint[]) AND public = $2", @@ -435,7 +435,7 @@ impl DBProductPrice { .fetch(exec) .try_fold(DashMap::new(), predicate) .await - .wrap_err("fetching public product prices")?, + .context("fetching public product prices")?, }; Ok(prices) diff --git a/apps/labrinth/src/database/models/products_tax_identifier_item.rs b/apps/labrinth/src/database/models/products_tax_identifier_item.rs index 0a8a5a85e55..0f5330828db 100644 --- a/apps/labrinth/src/database/models/products_tax_identifier_item.rs +++ b/apps/labrinth/src/database/models/products_tax_identifier_item.rs @@ -20,7 +20,7 @@ impl DBProductsTaxIdentifier { ) .fetch_optional(exec) .await - .wrap_internal_err("querying database for `get_product`")?; + .internal_context("querying database for `get_product`")?; Ok(maybe_row.map(|row| DBProductsTaxIdentifier { id: row.id, @@ -44,7 +44,7 @@ impl DBProductsTaxIdentifier { ) .fetch_optional(exec) .await - .wrap_internal_err("querying database for `get_price`")?; + .internal_context("querying database for `get_price`")?; Ok(maybe_row.map(|row| DBProductsTaxIdentifier { id: row.id, @@ -76,7 +76,7 @@ pub async fn product_info_by_product_price_id( product_price_id.0 as i64, ) .fetch_optional(exec) - .await.wrap_internal_err("querying database for `product_info_by_product_price_id`")?; + .await.internal_context("querying database for `product_info_by_product_price_id`")?; match maybe_row { None => Ok(None), @@ -87,7 +87,7 @@ pub async fn product_info_by_product_price_id( product_id: DBProductId(row.product_id), }, product_metadata: serde_json::from_value(row.product_metadata) - .wrap_request_err("deserializing JSON data")?, + .request_context("deserializing JSON data")?, })), } } diff --git a/apps/labrinth/src/database/models/project_disclosure_item.rs b/apps/labrinth/src/database/models/project_disclosure_item.rs index 3f935b49a10..9e17038944e 100644 --- a/apps/labrinth/src/database/models/project_disclosure_item.rs +++ b/apps/labrinth/src/database/models/project_disclosure_item.rs @@ -1,8 +1,8 @@ use std::collections::{HashMap, HashSet}; use std::str::FromStr; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; use crate::{ @@ -31,7 +31,7 @@ impl DBProjectDisclosure { let (disclosure_type, metadata) = self .disclosure .to_parts() - .wrap_err("serializing project disclosure metadata")?; + .context("serializing project disclosure metadata")?; sqlx::query!( r#" @@ -54,7 +54,7 @@ impl DBProjectDisclosure { ) .execute(exec) .await - .wrap_err("upserting project disclosure")?; + .context("upserting project disclosure")?; Ok(()) } @@ -85,17 +85,17 @@ impl DBProjectDisclosure { ) .fetch_all(exec) .await - .wrap_err("fetching project disclosures")?; + .context("fetching project disclosures")?; rows.into_iter() .map(|row| { - eyre::Ok(DBProjectDisclosure { + anyhow::Ok(DBProjectDisclosure { project_id: DBProjectId(row.project_id), disclosure: ProjectDisclosure::from_parts( &row.disclosure_type, row.metadata, ) - .wrap_err("deserializing project disclosure metadata")?, + .context("deserializing project disclosure metadata")?, updated_at: row.updated_at, updated_by: DBUserId(row.updated_by), set_by_moderator: row.set_by_moderator, @@ -103,7 +103,7 @@ impl DBProjectDisclosure { lock_status: DisclosureLockStatus::from_str( &row.lock_status, ) - .wrap_err("parsing project disclosure lock status")?, + .context("parsing project disclosure lock status")?, }) }) .collect() @@ -127,7 +127,7 @@ impl DBProjectDisclosure { ) .fetch_all(exec) .await - .wrap_err("fetching projects with disclosure type")?; + .context("fetching projects with disclosure type")?; Ok(rows.into_iter().map(DBProjectId).collect()) } @@ -148,15 +148,15 @@ impl DBProjectDisclosure { ) .fetch_all(exec) .await - .wrap_err("fetching project disclosure lock statuses")?; + .context("fetching project disclosure lock statuses")?; rows.into_iter() .map(|row| { let lock_status = DisclosureLockStatus::from_str(&row.lock_status) - .wrap_err("parsing project disclosure lock status")?; + .context("parsing project disclosure lock status")?; - eyre::Ok((row.disclosure_type, lock_status)) + anyhow::Ok((row.disclosure_type, lock_status)) }) .collect() } @@ -181,7 +181,7 @@ impl DBProjectDisclosure { ) .execute(exec) .await - .wrap_err("removing project disclosure")?; + .context("removing project disclosure")?; Ok(result.rows_affected() > 0) } diff --git a/apps/labrinth/src/database/models/project_flag_item.rs b/apps/labrinth/src/database/models/project_flag_item.rs index 87ebc61df6a..d4dec4fc592 100644 --- a/apps/labrinth/src/database/models/project_flag_item.rs +++ b/apps/labrinth/src/database/models/project_flag_item.rs @@ -1,8 +1,8 @@ use std::collections::BTreeMap; +use anyhow::{Context, Result}; use ariadne::ids::random_base62; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use crate::database::{PgPool, ReadOnlyPgPool}; use regex::Regex; @@ -65,7 +65,7 @@ impl DBProjectFlagRule { ) .fetch_all(pool) .await - .wrap_err("snapshotting project flag rules")?; + .context("snapshotting project flag rules")?; Ok(rows .into_iter() @@ -99,7 +99,7 @@ impl DBProjectFlagRule { ) .fetch_all(&**pool) .await - .wrap_err("listing project flag rules")?; + .context("listing project flag rules")?; Ok(rows .into_iter() @@ -130,7 +130,7 @@ impl DBProjectFlagRule { ) .fetch_optional(&**pool) .await - .wrap_err("fetching project flag rule")?; + .context("fetching project flag rule")?; Ok(row.map(|row| Self { id: ProjectFlagRuleId(row.id), @@ -167,7 +167,7 @@ impl DBProjectFlagRule { ) .fetch_one(pool) .await - .wrap_err("creating project flag rule")?; + .context("creating project flag rule")?; Ok(Self { id: ProjectFlagRuleId(row.id), @@ -204,7 +204,7 @@ impl DBProjectFlagRule { ) .fetch_optional(pool) .await - .wrap_err("updating project flag rule")?; + .context("updating project flag rule")?; Ok(row.map(|row| Self { id: ProjectFlagRuleId(row.id), @@ -227,7 +227,7 @@ impl DBProjectFlagRule { ) .execute(pool) .await - .wrap_err("deleting project flag rule")?; + .context("deleting project flag rule")?; Ok(result.rows_affected() > 0) } @@ -286,7 +286,7 @@ impl DBProjectFlag { ) .fetch_all(&**pool) .await - .wrap_err("fetching project flags")?; + .context("fetching project flags")?; if rows.is_empty() { return Ok(None); @@ -349,7 +349,7 @@ impl DBProjectFlagRunResult { ) .fetch_optional(&**pool) .await - .wrap_err("counting project flag run results")?; + .context("counting project flag run results")?; let Some(run) = run else { return Ok(None); }; @@ -370,13 +370,13 @@ impl DBProjectFlagRunResult { ) .fetch_all(&**pool) .await - .wrap_err("fetching project flag run results")?; + .context("fetching project flag run results")?; let mut rule_ids = rows .iter() .flat_map(|row| row.rules.0.keys()) .map(|id| id.parse::()) .collect::, _>>() - .wrap_err("parsing project flag result rule IDs")?; + .context("parsing project flag result rule IDs")?; rule_ids.sort_unstable(); rule_ids.dedup(); let names = sqlx::query!( @@ -385,7 +385,7 @@ impl DBProjectFlagRunResult { ) .fetch_all(&**pool) .await - .wrap_err("fetching project flag rule names")? + .context("fetching project flag rule names")? .into_iter() .map(|row| (row.id.to_string(), row.name)) .collect::>(); @@ -478,7 +478,7 @@ impl DBProjectFlagRunResult { let mut transaction = pool .begin() .await - .wrap_err("starting project flag results transaction")?; + .context("starting project flag results transaction")?; sqlx::query!( r#" SELECT id @@ -491,7 +491,7 @@ impl DBProjectFlagRunResult { ) .fetch_all(&mut transaction) .await - .wrap_err("locking project flag runs")?; + .context("locking project flag runs")?; let surviving_projects = sqlx::query_scalar!( r#" SELECT id FROM mods @@ -503,7 +503,7 @@ impl DBProjectFlagRunResult { ) .fetch_all(&mut transaction) .await - .wrap_err("locking projects for project flag results")?; + .context("locking projects for project flag results")?; let results = results .into_iter() .filter(|payload| { @@ -513,7 +513,7 @@ impl DBProjectFlagRunResult { }) .collect::>(); let results = serde_json::to_value(results) - .wrap_err("serializing project flag run results")?; + .context("serializing project flag run results")?; sqlx::query!( r#" INSERT INTO project_flag_run_results @@ -533,7 +533,7 @@ impl DBProjectFlagRunResult { ) .execute(&mut transaction) .await - .wrap_err("persisting project flag run results")?; + .context("persisting project flag run results")?; let consumed_run_ids = consumed_jobs .iter() .map(|(run_id, _)| run_id.0) @@ -554,7 +554,7 @@ impl DBProjectFlagRunResult { ) .execute(&mut transaction) .await - .wrap_err("acknowledging consumed project flag jobs")?; + .context("acknowledging consumed project flag jobs")?; sqlx::query!( r#" UPDATE project_flag_runs AS runs @@ -571,11 +571,11 @@ impl DBProjectFlagRunResult { ) .execute(&mut transaction) .await - .wrap_err("completing project flag runs")?; + .context("completing project flag runs")?; transaction .commit() .await - .wrap_err("committing project flag run results")?; + .context("committing project flag run results")?; Ok(()) } } @@ -613,21 +613,21 @@ impl DBProjectFlagRun { ) .fetch_one(&**pool) .await - .wrap_err("counting unfinished project flag scans") + .context("counting unfinished project flag scans") } pub async fn delete(id: ProjectFlagRunId, pool: &PgPool) -> Result { let mut transaction = pool .begin() .await - .wrap_err("starting project flag run deletion")?; + .context("starting project flag run deletion")?; let run = sqlx::query_scalar!( r#"SELECT id FROM project_flag_runs WHERE id = $1 FOR UPDATE"#, id.0, ) .fetch_optional(&mut transaction) .await - .wrap_err("locking project flag run for deletion")?; + .context("locking project flag run for deletion")?; if run.is_none() { return Ok(false); } @@ -642,11 +642,11 @@ impl DBProjectFlagRun { ) .fetch_all(&mut transaction) .await - .wrap_err("locking projects for run deletion")?; + .context("locking projects for run deletion")?; sqlx::query!( r#"UPDATE project_flags SET run_id = NULL WHERE run_id = $1 AND active"#, id.0, - ).execute(&mut transaction).await.wrap_err("detaching active project flags")?; + ).execute(&mut transaction).await.context("detaching active project flags")?; let result = sqlx::query!( r#" DELETE FROM project_flag_runs @@ -656,11 +656,11 @@ impl DBProjectFlagRun { ) .execute(&mut transaction) .await - .wrap_err("deleting project flag run")?; + .context("deleting project flag run")?; transaction .commit() .await - .wrap_err("committing project flag run deletion")?; + .context("committing project flag run deletion")?; Ok(result.rows_affected() > 0) } @@ -670,7 +670,7 @@ impl DBProjectFlagRun { ) .fetch_all(pool) .await - .wrap_err("fetching queued project IDs")?; + .context("fetching queued project IDs")?; Ok(ids.into_iter().map(DBProjectId).collect()) } @@ -684,14 +684,14 @@ impl DBProjectFlagRun { project_ids.sort_unstable(); project_ids.dedup(); let total_projects = i64::try_from(project_ids.len()) - .wrap_err("counting project flag run jobs")?; + .context("counting project flag run jobs")?; let username = sqlx::query_scalar!( r#"SELECT username FROM users WHERE id = $1"#, user_id.0, ) .fetch_one(pool) .await - .wrap_err("fetching project flag run starter")?; + .context("fetching project flag run starter")?; let run = Self { id: ProjectFlagRunId(uuid::Uuid::now_v7()), status: ProjectFlagRunStatus::Running, @@ -711,7 +711,7 @@ impl DBProjectFlagRun { let mut transaction = pool .begin() .await - .wrap_err("starting project flag run creation")?; + .context("starting project flag run creation")?; sqlx::query!( r#" INSERT INTO project_flag_runs (id, status, started_by, started_at, total_projects) @@ -724,7 +724,7 @@ impl DBProjectFlagRun { ) .execute(&mut transaction) .await - .wrap_err("creating project flag run")?; + .context("creating project flag run")?; sqlx::query!( r#" INSERT INTO project_flag_run_pending_jobs (run_id, project_id) @@ -735,11 +735,11 @@ impl DBProjectFlagRun { ) .execute(&mut transaction) .await - .wrap_err("creating pending project flag jobs")?; + .context("creating pending project flag jobs")?; transaction .commit() .await - .wrap_err("committing project flag run creation")?; + .context("committing project flag run creation")?; Ok(run) } @@ -763,7 +763,7 @@ impl DBProjectFlagRun { ) .execute(pool) .await - .wrap_err("finishing project flag run")?; + .context("finishing project flag run")?; self.status = status; self.completed_at = Some(completed_at); self.error = error; @@ -796,7 +796,7 @@ impl DBProjectFlagRun { ) .fetch_all(&**pool) .await - .wrap_err("listing project flag runs")?; + .context("listing project flag runs")?; Ok(rows .into_iter() diff --git a/apps/labrinth/src/database/models/project_item.rs b/apps/labrinth/src/database/models/project_item.rs index 8c97e3d744f..1ecfaeb690f 100644 --- a/apps/labrinth/src/database/models/project_item.rs +++ b/apps/labrinth/src/database/models/project_item.rs @@ -9,10 +9,10 @@ use crate::models::link_platform::LinkPlatform; use crate::models::projects::{ MonetizationStatus, ProjectStatus, SideTypesMigrationReviewStatus, }; +use anyhow::{Context, Result}; use ariadne::ids::base62_impl::parse_base62; use chrono::{DateTime, Utc}; use dashmap::{DashMap, DashSet}; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use itertools::Itertools; use minecraft_meta_model::model::MinecraftVersionName; @@ -96,7 +96,7 @@ impl LinkUrl { ) .execute(&mut *transaction) .await - .wrap_err("inserting project links into database")?; + .context("inserting project links into database")?; Ok(()) } @@ -160,7 +160,7 @@ impl DBGalleryItem { ) .execute(&mut *transaction) .await - .wrap_err("inserting project gallery items into database")?; + .context("inserting project gallery items into database")?; Ok(()) } @@ -196,7 +196,7 @@ impl DBModCategory { ) .execute(&mut *transaction) .await - .wrap_err("inserting project categories")?; + .context("inserting project categories")?; Ok(()) } @@ -272,7 +272,7 @@ impl ProjectBuilder { project_struct .insert(&mut *transaction) .await - .wrap_err("inserting project")?; + .context("inserting project")?; let ProjectBuilder { link_urls, @@ -287,7 +287,7 @@ impl ProjectBuilder { version .insert(transaction, redis, file_host, delphi_scan_files) .await - .wrap_err("inserting initial project version")?; + .context("inserting initial project version")?; } LinkUrl::insert_many_projects( @@ -296,7 +296,7 @@ impl ProjectBuilder { &mut *transaction, ) .await - .wrap_err("inserting project links")?; + .context("inserting project links")?; DBGalleryItem::insert_many( gallery_items, @@ -304,7 +304,7 @@ impl ProjectBuilder { &mut *transaction, ) .await - .wrap_err("inserting project gallery items")?; + .context("inserting project gallery items")?; let project_id = self.project_id; let mod_categories = categories @@ -324,7 +324,7 @@ impl ProjectBuilder { .collect_vec(); DBModCategory::insert_many(mod_categories, &mut *transaction) .await - .wrap_err("inserting project categories")?; + .context("inserting project categories")?; Ok(self.project_id) } @@ -406,7 +406,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("inserting project")?; + .context("inserting project")?; Ok(()) } @@ -418,12 +418,12 @@ impl DBProject { ) -> Result> { let project = Self::get_id(id, &mut *transaction, redis) .await - .wrap_err("fetching project by id")?; + .context("fetching project by id")?; if let Some(project) = project { DBProject::clear_cache(id, project.inner.slug, Some(true), redis) .await - .wrap_err("clearing project cache")?; + .context("clearing project cache")?; sqlx::query!( " @@ -434,7 +434,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting project followers")?; + .context("deleting project followers")?; sqlx::query!( " @@ -445,7 +445,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting project gallery items")?; + .context("deleting project gallery items")?; sqlx::query!( " @@ -456,7 +456,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting duplicate project followers")?; + .context("deleting duplicate project followers")?; sqlx::query!( " @@ -468,7 +468,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("clearing report project references")?; + .context("clearing report project references")?; sqlx::query!( " @@ -479,7 +479,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting project categories")?; + .context("deleting project categories")?; sqlx::query!( " @@ -490,12 +490,12 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting project links")?; + .context("deleting project links")?; for version in project.versions { super::DBVersion::remove_full(version, redis, transaction) .await - .wrap_err("removing project version")?; + .context("removing project version")?; } sqlx::query!( @@ -506,7 +506,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting dependency references")?; + .context("deleting dependency references")?; sqlx::query!( " @@ -518,7 +518,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("clearing payout project references")?; + .context("clearing payout project references")?; sqlx::query!( " @@ -529,11 +529,11 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting project row")?; + .context("deleting project row")?; models::DBTeamMember::clear_cache(project.inner.team_id, redis) .await - .wrap_err("clearing team member cache")?; + .context("clearing team member cache")?; let affected_user_ids = sqlx::query!( " @@ -547,11 +547,11 @@ impl DBProject { .map_ok(|x| DBUserId(x.user_id)) .try_collect::>() .await - .wrap_err("deleting team members")?; + .context("deleting team members")?; DBUser::clear_project_cache(&affected_user_ids, redis) .await - .wrap_err("clearing user project cache")?; + .context("clearing user project cache")?; sqlx::query!( " @@ -562,7 +562,7 @@ impl DBProject { ) .execute(&mut *transaction) .await - .wrap_err("deleting team")?; + .context("deleting team")?; Ok(Some(())) } else { @@ -580,7 +580,7 @@ impl DBProject { { DBProject::get_many(&[string], executor, redis) .await - .wrap_err("fetching project") + .context("fetching project") .map(|x| x.into_iter().next()) } @@ -598,7 +598,7 @@ impl DBProject { redis, ) .await - .wrap_err("fetching project by id") + .context("fetching project by id") .map(|x| x.into_iter().next()) } @@ -616,7 +616,7 @@ impl DBProject { .collect::>(); DBProject::get_many(&ids, exec, redis) .await - .wrap_err("fetching projects by id") + .context("fetching projects by id") } pub async fn get_many< @@ -633,7 +633,7 @@ impl DBProject { { Self::get_many_inner(project_strings, exec, redis, true) .await - .wrap_err("fetching projects") + .context("fetching projects") } pub async fn get_many_uncached< @@ -650,7 +650,7 @@ impl DBProject { { Self::get_many_inner(project_strings, exec, redis, false) .await - .wrap_err("fetching uncached projects") + .context("fetching uncached projects") } async fn get_many_inner< @@ -676,7 +676,7 @@ impl DBProject { let mut exec = exec .acquire() .await - .wrap_err("acquiring database connection for project query")?; + .context("acquiring database connection for project query")?; let project_ids_parsed: Vec = ids .iter() .filter_map(|x| parse_base62(&x.to_string()).ok()) @@ -705,7 +705,7 @@ impl DBProject { .collect::>() ) .fetch(&mut exec) - .map_err(eyre::Report::from) + .map_err(anyhow::Error::from) .try_fold( DashMap::new(), |acc: DashMap)>>, m| { @@ -720,13 +720,13 @@ impl DBProject { acc.entry(DBProjectId(m.mod_id)) .or_default() .push((version_id, date_published)); - eyre::Ok(acc) + anyhow::Ok(acc) }; async move { result } }, ) .await - .wrap_err("fetching project versions")?; + .context("fetching project versions")?; let mods_gallery: DashMap> = sqlx::query!( " @@ -755,7 +755,7 @@ impl DBProject { } ) .await - .wrap_err("fetching project gallery items")?; + .context("fetching project gallery items")?; let links: DashMap> = sqlx::query!( " @@ -781,7 +781,7 @@ impl DBProject { } ) .await - .wrap_err("fetching project links")?; + .context("fetching project links")?; #[derive(Default)] struct VersionLoaderData { @@ -821,7 +821,7 @@ impl DBProject { ) .try_collect() .await - .wrap_err("fetching project loader metadata")?; + .context("fetching project loader metadata")?; let project_rows = sqlx::query!( r#" @@ -850,7 +850,7 @@ impl DBProject { ) .fetch_all(&mut exec) .await - .wrap_err("fetching project rows")?; + .context("fetching project rows")?; let project_components = project_rows .iter() @@ -867,7 +867,7 @@ impl DBProject { redis, ) .await - .wrap_err("failed to fetch project query context")?; + .context("failed to fetch project query context")?; let projects = project_rows .into_iter() @@ -894,7 +894,7 @@ impl DBProject { ProjectId::from(project_id), &project_query_context, ) - .wrap_err("failed to populate query components")?; + .context("failed to populate query components")?; let project = ProjectQueryResult { inner: DBProject { @@ -950,15 +950,15 @@ impl DBProject { }; acc.insert(m.id, (m.slug, project)); - eyre::Ok(acc) + anyhow::Ok(acc) }) - .wrap_err("building project query results")?; + .context("building project query results")?; - eyre::Ok(projects) + anyhow::Ok(projects) }, ) .await - .wrap_err("fetching cached projects")?; + .context("fetching cached projects")?; Ok(val) } @@ -984,15 +984,16 @@ impl DBProject { )>; { - let mut redis = redis.connect().await.wrap_err( - "connecting to redis to fetch project dependencies", - )?; + let mut redis = redis + .connect() + .await + .context("connecting to redis to fetch project dependencies")?; let key = redis.key().entity(PROJECTS_DEPENDENCIES_NAMESPACE, id.0); let dependencies = redis .get_deserialized::(&key) .await - .wrap_err("fetching cached project dependencies")?; + .context("fetching cached project dependencies")?; if let Some(dependencies) = dependencies { return Ok(dependencies); } @@ -1022,18 +1023,18 @@ impl DBProject { }) .try_collect::() .await - .wrap_err("fetching project dependencies")?; + .context("fetching project dependencies")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache project dependencies")?; + .context("connecting to redis to cache project dependencies")?; let key = redis.key().entity(PROJECTS_DEPENDENCIES_NAMESPACE, id.0); redis .set_serialized(&key, &dependencies, None) .await - .wrap_err("caching project dependencies")?; + .context("caching project dependencies")?; Ok(dependencies) } @@ -1046,7 +1047,7 @@ impl DBProject { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear project cache")?; + .context("connecting to redis to clear project cache")?; let mut keys = vec![redis.key().entity(PROJECTS_NAMESPACE, id.0)]; if let Some(slug) = slug { keys.push( @@ -1064,7 +1065,7 @@ impl DBProject { redis .delete_many(&keys) .await - .wrap_err("clearing project cache")?; + .context("clearing project cache")?; Ok(()) } } diff --git a/apps/labrinth/src/database/models/report_item.rs b/apps/labrinth/src/database/models/report_item.rs index 2c35a97c214..dcdf4cf895e 100644 --- a/apps/labrinth/src/database/models/report_item.rs +++ b/apps/labrinth/src/database/models/report_item.rs @@ -1,8 +1,8 @@ use crate::database::PgTransaction; use super::ids::*; +use anyhow::Context; use chrono::{DateTime, Utc}; -use eyre::WrapErr; pub struct DBReport { pub id: DBReportId, @@ -127,7 +127,7 @@ impl DBReport { pub async fn remove_full( id: DBReportId, transaction: &mut PgTransaction<'_>, - ) -> eyre::Result> { + ) -> anyhow::Result> { let result = sqlx::query!( " SELECT EXISTS(SELECT 1 FROM reports WHERE id = $1) @@ -136,7 +136,7 @@ impl DBReport { ) .fetch_one(&mut *transaction) .await - .wrap_err("checking whether report exists")?; + .context("checking whether report exists")?; if !result.exists.unwrap_or(false) { return Ok(None); @@ -151,7 +151,7 @@ impl DBReport { ) .fetch_optional(&mut *transaction) .await - .wrap_err("fetching report thread")?; + .context("fetching report thread")?; if let Some(thread_id) = thread_id { crate::database::models::DBThread::remove_full( @@ -159,7 +159,7 @@ impl DBReport { transaction, ) .await - .wrap_err("removing report thread")?; + .context("removing report thread")?; } sqlx::query!( @@ -170,7 +170,7 @@ impl DBReport { ) .execute(&mut *transaction) .await - .wrap_err("removing report")?; + .context("removing report")?; Ok(Some(())) } diff --git a/apps/labrinth/src/database/models/session_item.rs b/apps/labrinth/src/database/models/session_item.rs index 1c8084ae68c..fbec9d64d05 100644 --- a/apps/labrinth/src/database/models/session_item.rs +++ b/apps/labrinth/src/database/models/session_item.rs @@ -1,10 +1,10 @@ use super::ids::*; use crate::database::PgTransaction; use crate::env::ENV; +use anyhow::{Context, Result}; use ariadne::ids::base62_impl::parse_base62; use chrono::{DateTime, Utc}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use futures_util::TryStreamExt; use serde::{Deserialize, Serialize}; use std::fmt::{Debug, Display}; @@ -41,7 +41,7 @@ impl SessionBuilder { ) -> Result { let id = generate_session_id(transaction) .await - .wrap_err("generating session id")?; + .context("generating session id")?; sqlx::query!( " @@ -72,7 +72,7 @@ impl SessionBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting session")?; + .context("inserting session")?; Ok(id) } @@ -114,7 +114,7 @@ impl DBSession { Self::get_many(&[id], exec, redis) .await .map(|x| x.into_iter().next()) - .wrap_err("getting session") + .context("getting session") } pub async fn get_id<'a, 'b, E>( @@ -132,7 +132,7 @@ impl DBSession { ) .await .map(|x| x.into_iter().next()) - .wrap_err("getting session by id") + .context("getting session by id") } pub async fn get_many_ids<'a, E>( @@ -149,7 +149,7 @@ impl DBSession { .collect::>(); DBSession::get_many(&ids, exec, redis) .await - .wrap_err("getting sessions by id") + .context("getting sessions by id") } pub async fn get_many< @@ -217,7 +217,7 @@ impl DBSession { }) .await }).await - .wrap_err("getting sessions from cache or database")?; + .context("getting sessions from cache or database")?; Ok(val) } @@ -234,12 +234,14 @@ impl DBSession { true, &[session], |_| async { - eyre::Ok(DashMap::, DBSession)>::new()) + anyhow::Ok( + DashMap::, DBSession)>::new(), + ) }, ) .await .map(|x| x.into_iter().next()) - .wrap_err("getting cached session") + .context("getting cached session") } pub async fn get_user_sessions<'a, E>( @@ -254,13 +256,13 @@ impl DBSession { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for user sessions")?; + .context("connecting to redis for user sessions")?; let key = redis.key().entity(SESSIONS_USERS_NAMESPACE, user_id.0); let res = redis .get_deserialized::>(&key) .await - .wrap_err("getting cached user sessions")?; + .context("getting cached user sessions")?; if let Some(res) = res { return Ok(res.into_iter().map(DBSessionId).collect()); @@ -281,12 +283,12 @@ impl DBSession { .map_ok(|x| DBSessionId(x.id)) .try_collect::>() .await - .wrap_err("fetching user sessions from database")?; + .context("fetching user sessions from database")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache user sessions")?; + .context("connecting to redis to cache user sessions")?; let key = redis.key().entity(SESSIONS_USERS_NAMESPACE, user_id.0); redis @@ -296,7 +298,7 @@ impl DBSession { Some(ENV.REDIS_SESSION_DEFAULT_EXPIRY), ) .await - .wrap_err("caching user sessions")?; + .context("caching user sessions")?; Ok(db_sessions) } @@ -312,7 +314,7 @@ impl DBSession { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear session caches")?; + .context("connecting to redis to clear session caches")?; if clear_sessions.is_empty() { return Ok(()); @@ -337,7 +339,7 @@ impl DBSession { redis .delete_many(&keys) .await - .wrap_err("clearing session caches")?; + .context("clearing session caches")?; Ok(()) } diff --git a/apps/labrinth/src/database/models/team_item.rs b/apps/labrinth/src/database/models/team_item.rs index 252559dbcab..a2e7188686f 100644 --- a/apps/labrinth/src/database/models/team_item.rs +++ b/apps/labrinth/src/database/models/team_item.rs @@ -3,8 +3,8 @@ use crate::{ database::PgTransaction, models::teams::{OrganizationPermissions, ProjectPermissions}, }; +use anyhow::{Context, Result}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use itertools::Itertools; use rust_decimal::Decimal; @@ -34,7 +34,7 @@ impl TeamBuilder { ) -> Result { let team_id = generate_team_id(transaction) .await - .wrap_err("generating team id")?; + .context("generating team id")?; let team = DBTeam { id: team_id }; @@ -47,14 +47,14 @@ impl TeamBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting team")?; + .context("inserting team")?; let mut team_member_ids = Vec::new(); for _ in &self.members { team_member_ids.push( generate_team_member_id(transaction) .await - .wrap_err("generating team member id")? + .context("generating team member id")? .0, ); } @@ -113,7 +113,7 @@ impl TeamBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting team members")?; + .context("inserting team members")?; Ok(team_id) } @@ -155,7 +155,7 @@ impl DBTeam { ) .fetch_optional(executor) .await - .wrap_err("fetching team association")?; + .context("fetching team association")?; if let Some(t) = result { // Only one of project_id or organization_id will be set @@ -211,7 +211,7 @@ impl DBTeamMember { { Self::get_from_team_full_many(&[id], executor, redis) .await - .wrap_err("fetching full team members") + .context("fetching full team members") } pub async fn get_from_team_full_many<'a, E>( @@ -269,7 +269,7 @@ impl DBTeamMember { }, ) .await - .wrap_err("fetching cached team members")?; + .context("fetching cached team members")?; Ok(val.into_iter().flatten().collect()) } @@ -278,9 +278,9 @@ impl DBTeamMember { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear team cache")?; + .context("connecting to redis to clear team cache")?; let key = redis.key().entity(TEAMS_NAMESPACE, id.0); - redis.delete(&key).await.wrap_err("clearing team cache")?; + redis.delete(&key).await.context("clearing team cache")?; Ok(()) } @@ -295,7 +295,7 @@ impl DBTeamMember { { Self::get_from_user_id_many(&[id], user_id, executor) .await - .wrap_err("fetching team member by user id") + .context("fetching team member by user id") .map(|x| x.into_iter().next()) } @@ -340,7 +340,7 @@ impl DBTeamMember { }) .try_collect::>() .await - .wrap_err("fetching team members by user id")?; + .context("fetching team members by user id")?; Ok(team_members) } @@ -369,7 +369,7 @@ impl DBTeamMember { ) .fetch_optional(executor) .await - .wrap_err("fetching pending team member by user id")?; + .context("fetching pending team member by user id")?; if let Some(m) = result { Ok(Some(DBTeamMember { @@ -439,7 +439,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("deleting team member")?; + .context("deleting team member")?; Ok(()) } @@ -470,7 +470,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("updating team member project permissions")?; + .context("updating team member project permissions")?; } if let Some(organization_permissions) = new_organization_permissions { @@ -486,7 +486,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("updating team member organization permissions")?; + .context("updating team member organization permissions")?; } if let Some(role) = new_role { @@ -502,7 +502,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("updating team member role")?; + .context("updating team member role")?; } if let Some(accepted) = new_accepted @@ -519,7 +519,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("accepting team member")?; + .context("accepting team member")?; } if let Some(payouts_split) = new_payouts_split { @@ -535,7 +535,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("updating team member payout split")?; + .context("updating team member payout split")?; } if let Some(ordering) = new_ordering { @@ -551,7 +551,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("updating team member ordering")?; + .context("updating team member ordering")?; } if let Some(is_owner) = new_is_owner { @@ -567,7 +567,7 @@ impl DBTeamMember { ) .execute(&mut *transaction) .await - .wrap_err("updating team member ownership")?; + .context("updating team member ownership")?; } Ok(()) @@ -601,7 +601,7 @@ impl DBTeamMember { ) .fetch_optional(executor) .await - .wrap_err("fetching project team member by user id")?; + .context("fetching project team member by user id")?; if let Some(m) = result { Ok(Some(DBTeamMember { @@ -654,7 +654,7 @@ impl DBTeamMember { ) .fetch_optional(executor) .await - .wrap_err("fetching organization team member by user id")?; + .context("fetching organization team member by user id")?; if let Some(m) = result { Ok(Some(DBTeamMember { @@ -701,7 +701,7 @@ impl DBTeamMember { ) .fetch_optional(executor) .await - .wrap_err("fetching version team member by user id")?; + .context("fetching version team member by user id")?; if let Some(m) = result { Ok(Some(DBTeamMember { @@ -741,20 +741,20 @@ impl DBTeamMember { let project_team_member = Self::get_from_user_id(project.team_id, user_id, executor) .await - .wrap_err("fetching project team member for permissions")?; + .context("fetching project team member for permissions")?; let organization = DBOrganization::get_associated_organization_project_id( project.id, executor, ) .await - .wrap_err("fetching project organization for permissions")?; + .context("fetching project organization for permissions")?; let organization_team_member = if let Some(organization) = &organization { Self::get_from_user_id(organization.team_id, user_id, executor) .await - .wrap_err("fetching organization team member for permissions")? + .context("fetching organization team member for permissions")? } else { None }; diff --git a/apps/labrinth/src/database/models/thread_issue_item.rs b/apps/labrinth/src/database/models/thread_issue_item.rs index 8016bb0db2b..a0621fdc455 100644 --- a/apps/labrinth/src/database/models/thread_issue_item.rs +++ b/apps/labrinth/src/database/models/thread_issue_item.rs @@ -6,8 +6,8 @@ use crate::database::PgTransaction; use crate::models::thread_issues::{ ThreadIssueContext, ThreadIssueFacet, ThreadIssueTarget, ThreadIssueVerdict, }; +use anyhow::{Context, Result, anyhow}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr, eyre}; use serde::{Deserialize, Serialize}; use sqlx::types::Json; @@ -63,7 +63,7 @@ impl DBThreadIssue { ) .fetch_all(exec) .await - .wrap_err("fetching thread issues")?; + .context("fetching thread issues")?; let mut issues = Vec::::new(); for row in rows { @@ -110,14 +110,16 @@ impl DBThreadIssue { transaction: &mut PgTransaction<'_>, ) -> Result> { if issues.iter().any(|issue| issue.facets.is_empty()) { - return Err(eyre!("thread issues must contain at least one facet")); + return Err(anyhow!( + "thread issues must contain at least one facet" + )); } let mut ids = Vec::with_capacity(issues.len()); for issue in issues { let id = generate_thread_issue_id(&mut *transaction) .await - .wrap_err("generating thread issue ID")?; + .context("generating thread issue ID")?; sqlx::query!( r#" @@ -136,21 +138,21 @@ impl DBThreadIssue { ) .execute(&mut *transaction) .await - .wrap_err("inserting thread issue")?; + .context("inserting thread issue")?; let facet_ids = generate_many_thread_issue_facet_ids( issue.facets.len(), &mut *transaction, ) .await - .wrap_err("generating thread issue facet IDs")?; + .context("generating thread issue facet IDs")?; let facet_ids = facet_ids.iter().map(|id| id.0).collect::>(); let whats = issue .facets .into_iter() .map(serde_json::to_value) .collect::, _>>() - .wrap_err("serializing thread issue facets")?; + .context("serializing thread issue facets")?; let verdicts = facet_ids .iter() .map(|_| ThreadIssueVerdict::Open.as_str().to_string()) @@ -178,7 +180,7 @@ impl DBThreadIssue { ) .execute(&mut *transaction) .await - .wrap_err("inserting thread issue facets")?; + .context("inserting thread issue facets")?; ids.push(id); } @@ -207,7 +209,7 @@ impl DBThreadIssue { ) .execute(&mut *transaction) .await - .wrap_err("updating thread issue facet")?; + .context("updating thread issue facet")?; Ok(result.rows_affected() > 0) } @@ -231,7 +233,7 @@ impl DBThreadIssue { ) .execute(&mut *transaction) .await - .wrap_err("verifying thread issue facets")?; + .context("verifying thread issue facets")?; Ok(()) } @@ -246,7 +248,7 @@ impl DBThreadIssue { ) .execute(&mut *transaction) .await - .wrap_err("deleting thread issue")?; + .context("deleting thread issue")?; Ok(result.rows_affected() > 0) } @@ -279,9 +281,7 @@ impl DBThreadIssue { ) .fetch_all(&mut *transaction) .await - .wrap_err( - "locking project thread issues for verdict synchronization", - )?; + .context("locking project thread issues for verdict synchronization")?; let mut changed_ids = Vec::new(); let mut changed_verdicts = Vec::new(); @@ -350,7 +350,7 @@ impl DBThreadIssue { ) .execute(&mut *transaction) .await - .wrap_err("updating project thread issue facet verdicts")?; + .context("updating project thread issue facet verdicts")?; } for issue in &mut issues { @@ -370,7 +370,7 @@ fn parse_verdict( "open" => Ok(ThreadIssueVerdict::Open), "addressed" => Ok(ThreadIssueVerdict::Addressed), "resolved" => Ok(ThreadIssueVerdict::Resolved), - verdict => Err(eyre!( + verdict => Err(anyhow!( "thread issue `{issue_id}` facet `{facet_id}` has invalid verdict `{verdict}`" )), } diff --git a/apps/labrinth/src/database/models/thread_item.rs b/apps/labrinth/src/database/models/thread_item.rs index 45f4a1e71dc..bab698f73d2 100644 --- a/apps/labrinth/src/database/models/thread_item.rs +++ b/apps/labrinth/src/database/models/thread_item.rs @@ -1,8 +1,8 @@ use super::ids::*; use crate::database::PgTransaction; use crate::models::threads::{MessageBody, ThreadType}; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; pub struct ThreadBuilder { @@ -49,9 +49,9 @@ impl ThreadMessageBuilder { ) -> Result { let thread_message_id = generate_thread_message_id(transaction) .await - .wrap_err("generating thread message id")?; + .context("generating thread message id")?; let body = serde_json::value::to_value(self.body.clone()) - .wrap_err("serializing thread message body")?; + .context("serializing thread message body")?; sqlx::query!( " @@ -70,7 +70,7 @@ impl ThreadMessageBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting thread message")?; + .context("inserting thread message")?; Ok(thread_message_id) } @@ -83,7 +83,7 @@ impl ThreadBuilder { ) -> Result { let thread_id = generate_thread_id(&mut *transaction) .await - .wrap_err("generating thread id")?; + .context("generating thread id")?; sqlx::query!( " INSERT INTO threads ( @@ -100,7 +100,7 @@ impl ThreadBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting thread")?; + .context("inserting thread")?; let (thread_ids, members): (Vec<_>, Vec<_>) = self.members.iter().map(|m| (thread_id.0, m.0)).unzip(); @@ -116,7 +116,7 @@ impl ThreadBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting thread members")?; + .context("inserting thread members")?; Ok(thread_id) } @@ -159,7 +159,7 @@ impl DBThread { ) .fetch_one(&mut *transaction) .await - .wrap_err("checking whether a project team member has replied") + .context("checking whether a project team member has replied") } pub async fn get<'a, E>(id: DBThreadId, exec: E) -> Result> @@ -168,7 +168,7 @@ impl DBThread { { Ok(Self::get_many(&[id], exec) .await - .wrap_err("fetching thread")? + .context("fetching thread")? .into_iter() .next()) } @@ -217,12 +217,12 @@ impl DBThread { }) .try_collect::>() .await - .wrap_err("fetching threads")?; + .context("fetching threads")?; let mut issues = super::DBThreadIssue::get_many_for_threads(thread_ids, exec) .await - .wrap_err("fetching thread issues")? + .context("fetching thread issues")? .into_iter() .fold( std::collections::HashMap::>::new(), @@ -251,7 +251,7 @@ impl DBThread { ) .execute(&mut *transaction) .await - .wrap_err("removing thread messages")?; + .context("removing thread messages")?; sqlx::query!( " DELETE FROM threads_members @@ -261,7 +261,7 @@ impl DBThread { ) .execute(&mut *transaction) .await - .wrap_err("removing thread members")?; + .context("removing thread members")?; sqlx::query!( " DELETE FROM threads @@ -271,7 +271,7 @@ impl DBThread { ) .execute(&mut *transaction) .await - .wrap_err("removing thread")?; + .context("removing thread")?; Ok(Some(())) } @@ -287,7 +287,7 @@ impl DBThreadMessage { { Ok(Self::get_many(&[id], exec) .await - .wrap_err("fetching thread message")? + .context("fetching thread message")? .into_iter() .next()) } @@ -322,7 +322,7 @@ impl DBThreadMessage { }) .try_collect::>() .await - .wrap_err("fetching thread messages")?; + .context("fetching thread messages")?; Ok(messages) } @@ -333,7 +333,7 @@ impl DBThreadMessage { transaction: &mut PgTransaction<'_>, ) -> Result> { let body = serde_json::to_value(MessageBody::Deleted { private }) - .wrap_err("serializing deleted thread message body")?; + .context("serializing deleted thread message body")?; sqlx::query!( " @@ -346,7 +346,7 @@ impl DBThreadMessage { ) .execute(&mut *transaction) .await - .wrap_err("removing thread message")?; + .context("removing thread message")?; Ok(Some(())) } diff --git a/apps/labrinth/src/database/models/user_item.rs b/apps/labrinth/src/database/models/user_item.rs index e274b51882d..42cc5694580 100644 --- a/apps/labrinth/src/database/models/user_item.rs +++ b/apps/labrinth/src/database/models/user_item.rs @@ -12,10 +12,10 @@ use crate::models::pats::Scopes; use crate::models::projects::ProjectStatus; use crate::models::threads::MessageBody; use crate::models::users::Badges; +use anyhow::{Context, Result}; use ariadne::ids::base62_impl::{parse_base62, to_base62}; use chrono::{DateTime, Utc}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; @@ -160,7 +160,7 @@ impl DBUser { DBUser::get_many(&[string], executor, redis) .await .map(|x| x.into_iter().next()) - .wrap_err("getting user") + .context("getting user") } pub async fn get_id<'a, 'b, E>( @@ -174,7 +174,7 @@ impl DBUser { DBUser::get_many(&[ariadne::ids::UserId::from(id)], executor, redis) .await .map(|x| x.into_iter().next()) - .wrap_err("getting user by id") + .context("getting user by id") } pub async fn get_many_ids<'a, E>( @@ -191,7 +191,7 @@ impl DBUser { .collect::>(); DBUser::get_many(&ids, exec, redis) .await - .wrap_err("getting users by id") + .context("getting users by id") } pub async fn get_many< @@ -332,7 +332,7 @@ impl DBUser { }) .await }).await - .wrap_err("getting users from cache or database")?; + .context("getting users from cache or database")?; Ok(val) } @@ -469,13 +469,13 @@ impl DBUser { let mut redis = redis .connect() .await - .wrap_err("connecting to redis for user projects")?; + .context("connecting to redis for user projects")?; let key = redis.key().entity(USERS_PROJECTS_NAMESPACE, user_id.0); let cached_projects = redis .get_deserialized::>(&key) .await - .wrap_err("getting cached user projects")?; + .context("getting cached user projects")?; if let Some(projects) = cached_projects { return Ok(projects); @@ -495,18 +495,18 @@ impl DBUser { .map_ok(|m| DBProjectId(m.id)) .try_collect::>() .await - .wrap_err("fetching user projects from database")?; + .context("fetching user projects from database")?; let mut redis = redis .connect() .await - .wrap_err("connecting to redis to cache user projects")?; + .context("connecting to redis to cache user projects")?; let key = redis.key().entity(USERS_PROJECTS_NAMESPACE, user_id.0); redis .set_serialized(&key, &db_projects, None) .await - .wrap_err("caching user projects")?; + .context("caching user projects")?; Ok(db_projects) } @@ -646,7 +646,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("clearing TOTP secret")?; + .context("clearing TOTP secret")?; sqlx::query!( " @@ -657,7 +657,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("deleting backup codes")?; + .context("deleting backup codes")?; Ok(()) } @@ -669,7 +669,7 @@ impl DBUser { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear user caches")?; + .context("connecting to redis to clear user caches")?; let keys = user_ids .iter() .flat_map(|(id, username)| { @@ -690,7 +690,7 @@ impl DBUser { redis .delete_many(&keys) .await - .wrap_err("clearing user caches")?; + .context("clearing user caches")?; Ok(()) } @@ -701,7 +701,7 @@ impl DBUser { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear user project caches")?; + .context("connecting to redis to clear user project caches")?; let keys = user_ids .iter() .map(|id| redis.key().entity(USERS_PROJECTS_NAMESPACE, id.0)) @@ -710,7 +710,7 @@ impl DBUser { redis .delete_many(&keys) .await - .wrap_err("clearing user project caches")?; + .context("clearing user project caches")?; Ok(()) } @@ -722,13 +722,13 @@ impl DBUser { ) -> Result> { let user = Self::get_id(id, &mut *transaction, redis) .await - .wrap_err("failed to get user by ID")?; + .context("failed to get user by ID")?; if let Some(delete_user) = user { let username = delete_user.username.clone(); DBUser::clear_caches(&[(id, Some(delete_user.username))], redis) .await - .wrap_err("failed to clear caches")?; + .context("failed to clear caches")?; let deleted_user: DBUserId = crate::models::users::DELETED_USER.into(); @@ -753,7 +753,7 @@ impl DBUser { .fetch(&mut *transaction) .try_collect::>() .await - .wrap_err("failed to fetch projects owned by deleted user")?; + .context("failed to fetch projects owned by deleted user")?; for project in &owned_projects { let thread_id = DBThreadId(project.thread_id); @@ -773,7 +773,7 @@ impl DBUser { } .insert(&mut *transaction) .await - .wrap_err( + .context( "failed to insert project transfer thread message", )?; @@ -795,7 +795,7 @@ impl DBUser { } .insert(&mut *transaction) .await - .wrap_err( + .context( "failed to insert automatic rejection thread message", )?; @@ -810,7 +810,7 @@ impl DBUser { } .insert(&mut *transaction) .await - .wrap_err( + .context( "failed to insert automatic rejection status change", )?; @@ -825,7 +825,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err( + .context( "failed to reject processing project owned by deleted user", )?; } @@ -837,7 +837,7 @@ impl DBUser { redis, ) .await - .wrap_err("failed to clear project cache")?; + .context("failed to clear project cache")?; } sqlx::query!( @@ -851,7 +851,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update team_members owner")?; + .context("failed to update team_members owner")?; sqlx::query!( " @@ -864,7 +864,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update versions author_id")?; + .context("failed to update versions author_id")?; let notifications: Vec = sqlx::query!( " @@ -877,7 +877,7 @@ impl DBUser { .map_ok(|m| m.id) .try_collect::>() .await - .wrap_err("failed to fetch notifications")?; + .context("failed to fetch notifications")?; sqlx::query!( " @@ -888,7 +888,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete notifications_actions")?; + .context("failed to delete notifications_actions")?; sqlx::query!( " @@ -899,7 +899,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete notifications_deliveries")?; + .context("failed to delete notifications_deliveries")?; sqlx::query!( " @@ -910,7 +910,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete notifications_deliveries")?; + .context("failed to delete notifications_deliveries")?; sqlx::query!( " @@ -921,7 +921,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete notifications")?; + .context("failed to delete notifications")?; let user_collections = sqlx::query!( " @@ -935,12 +935,12 @@ impl DBUser { .map_ok(|x| DBCollectionId(x.id)) .try_collect::>() .await - .wrap_err("failed to fetch user collections")?; + .context("failed to fetch user collections")?; for collection_id in user_collections { models::DBCollection::remove(collection_id, transaction, redis) .await - .wrap_err("failed to remove collection")?; + .context("failed to remove collection")?; } let report_threads = sqlx::query!( @@ -956,12 +956,12 @@ impl DBUser { .map_ok(|x| DBThreadId(x.id)) .try_collect::>() .await - .wrap_err("failed to fetch report threads")?; + .context("failed to fetch report threads")?; for thread_id in report_threads { models::DBThread::remove_full(thread_id, transaction) .await - .wrap_err("failed to remove thread")?; + .context("failed to remove thread")?; } sqlx::query!( @@ -973,7 +973,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete reports")?; + .context("failed to delete reports")?; sqlx::query!( " @@ -986,7 +986,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update reports user_id")?; + .context("failed to update reports user_id")?; sqlx::query!( " @@ -997,7 +997,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete mod_follows")?; + .context("failed to delete mod_follows")?; sqlx::query!( " @@ -1008,7 +1008,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete team_members")?; + .context("failed to delete team_members")?; sqlx::query!( r#" @@ -1021,7 +1021,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update threads_messages")?; + .context("failed to update threads_messages")?; sqlx::query!( " @@ -1032,7 +1032,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete threads_members")?; + .context("failed to delete threads_members")?; sqlx::query!( " @@ -1045,7 +1045,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update uploaded_images owner_id")?; + .context("failed to update uploaded_images owner_id")?; sqlx::query!( " @@ -1056,7 +1056,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete sessions")?; + .context("failed to delete sessions")?; sqlx::query!( " @@ -1067,7 +1067,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete pats")?; + .context("failed to delete pats")?; sqlx::query!( " @@ -1078,7 +1078,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete friends")?; + .context("failed to delete friends")?; sqlx::query!( " @@ -1090,7 +1090,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update affiliate_codes created_by")?; + .context("failed to update affiliate_codes created_by")?; sqlx::query!( " @@ -1100,7 +1100,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete affiliate_codes")?; + .context("failed to delete affiliate_codes")?; sqlx::query!( " @@ -1112,7 +1112,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update payouts_values user_id")?; + .context("failed to update payouts_values user_id")?; sqlx::query!( " @@ -1124,7 +1124,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update payouts user_id")?; + .context("failed to update payouts user_id")?; sqlx::query!( " @@ -1134,7 +1134,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete payouts_values_notifications")?; + .context("failed to delete payouts_values_notifications")?; sqlx::query!( " @@ -1147,18 +1147,18 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update charges user_id")?; + .context("failed to update charges user_id")?; let open_subscriptions = DBUserSubscription::get_all_user(id, &mut *transaction) .await - .wrap_err("failed to get user subscriptions")?; + .context("failed to get user subscriptions")?; for x in open_subscriptions { let charge = DBCharge::get_open_subscription(x.id, &mut *transaction) .await - .wrap_err("failed to get open subscription charge")?; + .context("failed to get open subscription charge")?; if let Some(mut charge) = charge { charge.status = ChargeStatus::Cancelled; charge.due = Utc::now(); @@ -1167,7 +1167,7 @@ impl DBUser { charge .upsert(transaction) .await - .wrap_err("failed to upsert charge")?; + .context("failed to upsert charge")?; } } @@ -1182,7 +1182,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update users_subscriptions user_id")?; + .context("failed to update users_subscriptions user_id")?; sqlx::query!( " @@ -1193,7 +1193,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete user_backup_codes")?; + .context("failed to delete user_backup_codes")?; sqlx::query!( " @@ -1206,7 +1206,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update oauth_clients created_by")?; + .context("failed to update oauth_clients created_by")?; sqlx::query!( " @@ -1219,7 +1219,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update user_locks locked_by")?; + .context("failed to update user_locks locked_by")?; sqlx::query!( r#" @@ -1232,7 +1232,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update threads_issues created_by")?; + .context("failed to update threads_issues created_by")?; sqlx::query!( " @@ -1245,7 +1245,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to update user_restrictions restricted_by")?; + .context("failed to update user_restrictions restricted_by")?; sqlx::query!( " @@ -1256,7 +1256,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete user")?; + .context("failed to delete user")?; sqlx::query!( " @@ -1267,7 +1267,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete oauth_client_authorizations")?; + .context("failed to delete oauth_client_authorizations")?; sqlx::query!( " @@ -1280,7 +1280,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete users_redeemals")?; + .context("failed to delete users_redeemals")?; sqlx::query!( " @@ -1293,7 +1293,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete users_compliance")?; + .context("failed to delete users_compliance")?; sqlx::query!( " @@ -1304,7 +1304,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete user_limits")?; + .context("failed to delete user_limits")?; sqlx::query!( " @@ -1315,7 +1315,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete users_notifications_preferences")?; + .context("failed to delete users_notifications_preferences")?; sqlx::query!( " @@ -1326,7 +1326,7 @@ impl DBUser { ) .execute(&mut *transaction) .await - .wrap_err("failed to delete moderation_locks")?; + .context("failed to delete moderation_locks")?; Ok(Some(())) } else { diff --git a/apps/labrinth/src/database/models/user_limits.rs b/apps/labrinth/src/database/models/user_limits.rs index dd66488871c..652c5cf1e82 100644 --- a/apps/labrinth/src/database/models/user_limits.rs +++ b/apps/labrinth/src/database/models/user_limits.rs @@ -1,5 +1,5 @@ use crate::database::PgPool; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -19,7 +19,7 @@ pub async fn get_user_requests_per_minute( let mut redis = redis .connect() .await - .wrap_err("connecting to redis for cached user rate limit")?; + .context("connecting to redis for cached user rate limit")?; let key = redis .key() .entity(USER_REQUESTS_PER_MINUTE_NAMESPACE, user_id.0); @@ -27,7 +27,7 @@ pub async fn get_user_requests_per_minute( let cached: Option> = redis .get_deserialized(&key) .await - .wrap_err("fetching cached user rate limit")?; + .context("fetching cached user rate limit")?; if let Some(requests_per_minute) = cached { return Ok(requests_per_minute); } @@ -38,7 +38,7 @@ pub async fn get_user_requests_per_minute( ) .fetch_optional(pool) .await - .wrap_err("fetching user rate limit")? + .context("fetching user rate limit")? .flatten() .map(|requests_per_minute| requests_per_minute as u32); @@ -49,7 +49,7 @@ pub async fn get_user_requests_per_minute( Some(USER_REQUESTS_PER_MINUTE_EXPIRY), ) .await - .wrap_err("caching user rate limit")?; + .context("caching user rate limit")?; Ok(requests_per_minute) } diff --git a/apps/labrinth/src/database/models/user_lock_item.rs b/apps/labrinth/src/database/models/user_lock_item.rs index 4209792676e..df95786f562 100644 --- a/apps/labrinth/src/database/models/user_lock_item.rs +++ b/apps/labrinth/src/database/models/user_lock_item.rs @@ -1,5 +1,5 @@ +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; use crate::database::models::DBUserId; @@ -37,7 +37,7 @@ impl DBUserLock { ) .execute(exec) .await - .wrap_err("upserting user lock")?; + .context("upserting user lock")?; Ok(()) } @@ -52,7 +52,7 @@ impl DBUserLock { ) .fetch_one(exec) .await - .wrap_err("checking user lock")?; + .context("checking user lock")?; Ok(exists) } @@ -68,7 +68,7 @@ impl DBUserLock { ) .execute(exec) .await - .wrap_err("deleting user lock")?; + .context("deleting user lock")?; Ok(result.rows_affected() > 0) } diff --git a/apps/labrinth/src/database/models/user_restriction_item.rs b/apps/labrinth/src/database/models/user_restriction_item.rs index 45171036aec..3cb49ff2f25 100644 --- a/apps/labrinth/src/database/models/user_restriction_item.rs +++ b/apps/labrinth/src/database/models/user_restriction_item.rs @@ -1,5 +1,5 @@ +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::{Deserialize, Serialize}; use crate::database::models::DBUserId; @@ -46,7 +46,7 @@ impl DBUserRestriction { ) .execute(exec) .await - .wrap_err("upserting user restriction")?; + .context("upserting user restriction")?; Ok(()) } @@ -62,7 +62,7 @@ impl DBUserRestriction { ) .execute(exec) .await - .wrap_err("deleting user restriction")?; + .context("deleting user restriction")?; Ok(result.rows_affected() > 0) } diff --git a/apps/labrinth/src/database/models/user_subscription_item.rs b/apps/labrinth/src/database/models/user_subscription_item.rs index addefd14c91..a716740f572 100644 --- a/apps/labrinth/src/database/models/user_subscription_item.rs +++ b/apps/labrinth/src/database/models/user_subscription_item.rs @@ -4,8 +4,8 @@ use crate::database::models::{ use crate::models::billing::{ PriceDuration, ProductMetadata, SubscriptionMetadata, SubscriptionStatus, }; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use itertools::Itertools; use std::convert::{TryFrom, TryInto}; @@ -69,7 +69,7 @@ impl DBUserSubscription { ) -> Result> { Ok(Self::get_many(&[id], exec) .await - .wrap_err("fetching user subscription")? + .context("fetching user subscription")? .into_iter() .next()) } @@ -86,13 +86,13 @@ impl DBUserSubscription { ) .fetch_all(exec) .await - .wrap_err("fetching user subscriptions")?; + .context("fetching user subscriptions")?; results .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing user subscription metadata") + .context("deserializing user subscription metadata") } pub async fn get_all_user( @@ -106,13 +106,13 @@ impl DBUserSubscription { ) .fetch_all(exec) .await - .wrap_err("fetching user subscriptions for user")?; + .context("fetching user subscriptions for user")?; results .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing user subscription metadata") + .context("deserializing user subscription metadata") } pub async fn get_all_servers( @@ -132,13 +132,13 @@ impl DBUserSubscription { ) .fetch_all(exec) .await - .wrap_err("fetching server subscriptions")?; + .context("fetching server subscriptions")?; results .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing user subscription metadata") + .context("deserializing user subscription metadata") } pub async fn upsert( @@ -167,11 +167,11 @@ impl DBUserSubscription { self.created, self.status.as_str(), serde_json::to_value(&self.metadata) - .wrap_err("serializing user subscription metadata")?, + .context("serializing user subscription metadata")?, ) .execute(exec) .await - .wrap_err("upserting user subscription")?; + .context("upserting user subscription")?; Ok(()) } @@ -195,13 +195,13 @@ impl DBUserSubscription { ) .fetch_all(exec) .await - .wrap_err("fetching user subscriptions by server ID")?; + .context("fetching user subscriptions by server ID")?; results .into_iter() .map(TryInto::try_into) .collect::, _>>() - .wrap_err("deserializing user subscription metadata") + .context("deserializing user subscription metadata") } } diff --git a/apps/labrinth/src/database/models/users_notifications_preferences_item.rs b/apps/labrinth/src/database/models/users_notifications_preferences_item.rs index d5b128aa489..d7e7413fae6 100644 --- a/apps/labrinth/src/database/models/users_notifications_preferences_item.rs +++ b/apps/labrinth/src/database/models/users_notifications_preferences_item.rs @@ -1,6 +1,6 @@ use super::ids::*; use crate::models::v3::notifications::{NotificationChannel, NotificationType}; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] @@ -43,7 +43,7 @@ impl UserNotificationPreference { ) -> Result> { Self::get_many_users_or_default(&[user_id], exec) .await - .wrap_err("fetching user notification preferences") + .context("fetching user notification preferences") } pub async fn get_many_users_or_default( @@ -68,7 +68,7 @@ impl UserNotificationPreference { ) .fetch_all(exec) .await - .wrap_err("fetching user notification preferences")?; + .context("fetching user notification preferences")?; let preferences = results .into_iter() @@ -106,7 +106,7 @@ impl UserNotificationPreference { ) .fetch_one(exec) .await - .wrap_err("inserting user notification preference")?; + .context("inserting user notification preference")?; self.id = id; diff --git a/apps/labrinth/src/database/models/version_item.rs b/apps/labrinth/src/database/models/version_item.rs index 106b821f6cd..ac018b535c6 100644 --- a/apps/labrinth/src/database/models/version_item.rs +++ b/apps/labrinth/src/database/models/version_item.rs @@ -7,9 +7,9 @@ use xredis::RedisPool; use crate::models::projects::{FileType, VersionStatus}; use crate::queue::file_scan::scan_file; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use dashmap::{DashMap, DashSet}; -use eyre::{Result, WrapErr}; use futures::TryStreamExt; use itertools::Itertools; use serde::{Deserialize, Serialize}; @@ -41,7 +41,7 @@ pub async fn cleanup_unused_attribution_files_and_groups( ) .execute(&mut *transaction) .await - .wrap_err("deleting unused attribution files")?; + .context("deleting unused attribution files")?; sqlx::query!( " @@ -55,7 +55,7 @@ pub async fn cleanup_unused_attribution_files_and_groups( ) .execute(&mut *transaction) .await - .wrap_err("deleting unused attribution groups")?; + .context("deleting unused attribution groups")?; Ok(()) } @@ -99,7 +99,7 @@ impl DependencyBuilder { dependency .try_get_project_id(transaction) .await - .wrap_err("resolving dependency project")? + .context("resolving dependency project")? .map(|id| id.0), ); } @@ -133,7 +133,7 @@ impl DependencyBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting dependencies")?; + .context("inserting dependencies")?; Ok(()) } @@ -153,7 +153,7 @@ impl DependencyBuilder { ) .fetch_optional(&mut *transaction) .await - .wrap_err("fetching dependency project")? + .context("fetching dependency project")? .map(|x| DBProjectId(x.mod_id)) } else { None @@ -183,7 +183,7 @@ impl VersionFileBuilder { ) -> Result { let file_id = generate_file_id(&mut *transaction) .await - .wrap_err("generating file id")?; + .context("generating file id")?; sqlx::query!( " @@ -200,7 +200,7 @@ impl VersionFileBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting version file")?; + .context("inserting version file")?; for hash in self.hashes { sqlx::query!( @@ -214,7 +214,7 @@ impl VersionFileBuilder { ) .execute(&mut *transaction) .await - .wrap_err("inserting file hash")?; + .context("inserting file hash")?; } let attribution_scan = sqlx::query!( @@ -232,7 +232,7 @@ impl VersionFileBuilder { ) .execute(&mut *transaction) .await - .wrap_err("creating attribution file scan")?; + .context("creating attribution file scan")?; if attribution_scan.rows_affected() > 0 && let Err(err) = scan_file( @@ -288,7 +288,7 @@ impl VersionBuilder { version .insert(transaction) .await - .wrap_err("inserting version")?; + .context("inserting version")?; sqlx::query!( " @@ -300,7 +300,7 @@ impl VersionBuilder { ) .execute(&mut *transaction) .await - .wrap_err("updating project timestamp")?; + .context("updating project timestamp")?; let VersionBuilder { dependencies, @@ -320,7 +320,7 @@ impl VersionBuilder { delphi_scan_files, ) .await - .wrap_err("inserting version file")?; + .context("inserting version file")?; } DependencyBuilder::insert_many( @@ -329,7 +329,7 @@ impl VersionBuilder { transaction, ) .await - .wrap_err("inserting version dependencies")?; + .context("inserting version dependencies")?; let loader_versions = loaders .iter() @@ -340,7 +340,7 @@ impl VersionBuilder { .collect_vec(); DBLoaderVersion::insert_many(loader_versions, transaction) .await - .wrap_err("inserting version loaders")?; + .context("inserting version loaders")?; Ok(self.version_id) } @@ -371,7 +371,7 @@ impl DBLoaderVersion { ) .execute(&mut *transaction) .await - .wrap_err("inserting version loaders")?; + .context("inserting version loaders")?; Ok(()) } @@ -440,7 +440,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("inserting version")?; + .context("inserting version")?; Ok(()) } @@ -452,7 +452,7 @@ impl DBVersion { ) -> Result> { let result = Self::get(id, &mut *transaction, redis) .await - .wrap_err("fetching version")?; + .context("fetching version")?; let Some(result) = result else { return Ok(None); @@ -460,7 +460,7 @@ impl DBVersion { DBVersion::clear_cache(&result, redis) .await - .wrap_err("clearing version cache")?; + .context("clearing version cache")?; sqlx::query!( " @@ -472,7 +472,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("unlinking version reports")?; + .context("unlinking version reports")?; sqlx::query!( " @@ -483,7 +483,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("deleting version loaders")?; + .context("deleting version loaders")?; sqlx::query!( " @@ -498,7 +498,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("deleting version file hashes")?; + .context("deleting version file hashes")?; sqlx::query!( " @@ -509,11 +509,11 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("deleting version files")?; + .context("deleting version files")?; cleanup_unused_attribution_files_and_groups(transaction) .await - .wrap_err("cleaning up unused attribution files and groups")?; + .context("cleaning up unused attribution files and groups")?; // Sync dependencies @@ -525,7 +525,7 @@ impl DBVersion { ) .fetch_one(&mut *transaction) .await - .wrap_err("fetching version project")?; + .context("fetching version project")?; sqlx::query!( " @@ -538,7 +538,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("unlinking version dependencies")?; + .context("unlinking version dependencies")?; sqlx::query!( " @@ -547,7 +547,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("deleting orphaned dependencies")?; + .context("deleting orphaned dependencies")?; sqlx::query!( " @@ -557,7 +557,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("deleting version dependencies")?; + .context("deleting version dependencies")?; // delete version @@ -569,7 +569,7 @@ impl DBVersion { ) .execute(&mut *transaction) .await - .wrap_err("deleting version")?; + .context("deleting version")?; crate::database::models::DBProject::clear_cache( DBProjectId(project_id.mod_id), @@ -578,7 +578,7 @@ impl DBVersion { redis, ) .await - .wrap_err("clearing project cache")?; + .context("clearing project cache")?; Ok(Some(())) } @@ -593,7 +593,7 @@ impl DBVersion { { Self::get_many(&[id], executor, redis) .await - .wrap_err("fetching version") + .context("fetching version") .map(|x| x.into_iter().next()) } @@ -607,7 +607,7 @@ impl DBVersion { { Self::get_many_inner(version_ids, exec, redis, true) .await - .wrap_err("fetching versions") + .context("fetching versions") } pub async fn get_many_uncached<'a, E>( @@ -620,7 +620,7 @@ impl DBVersion { { Self::get_many_inner(version_ids, exec, redis, false) .await - .wrap_err("fetching uncached versions") + .context("fetching uncached versions") } async fn get_many_inner<'a, E>( @@ -640,7 +640,7 @@ impl DBVersion { let mut exec = exec .acquire() .await - .wrap_err("acquiring database connection")?; + .context("acquiring database connection")?; #[derive(Default)] struct VersionLoaderData { @@ -679,7 +679,7 @@ impl DBVersion { ) .try_collect() .await - .wrap_err("fetching version loader data")?; + .context("fetching version loader data")?; #[derive(Deserialize)] struct Hash { @@ -708,7 +708,7 @@ impl DBVersion { ", &version_ids ).fetch(&mut exec) - .map_err(eyre::Report::from) + .map_err(anyhow::Error::from) .try_fold(DashMap::new(), |acc : DashMap>, m| { let file = File { id: DBFileId(m.id), @@ -725,11 +725,11 @@ impl DBVersion { acc.entry(DBVersionId(m.version_id)) .or_default() .push(file); - async move { eyre::Ok(acc) } + async move { anyhow::Ok(acc) } } ) .await - .wrap_err("fetching version files")?; + .context("fetching version files")?; let hashes: DashMap> = sqlx::query!( " @@ -740,7 +740,7 @@ impl DBVersion { &file_ids.iter().map(|x| x.0).collect::>() ) .fetch(&mut exec) - .map_err(eyre::Report::from) + .map_err(anyhow::Error::from) .try_fold(DashMap::new(), |acc: DashMap>, m| { if let Some(found_hash) = m.hash { let hash = Hash { @@ -753,10 +753,10 @@ impl DBVersion { acc.entry(*version_id).or_default().push(hash); } } - async move { eyre::Ok(acc) } + async move { anyhow::Ok(acc) } }) .await - .wrap_err("fetching version file hashes")?; + .context("fetching version file hashes")?; let dependencies : DashMap> = sqlx::query!( " @@ -766,7 +766,7 @@ impl DBVersion { ", &version_ids ).fetch(&mut exec) - .map_err(eyre::Report::from) + .map_err(anyhow::Error::from) .try_fold(DashMap::new(), |acc : DashMap<_,Vec>, m| { let dependency = DependencyQueryResult { id: m.dependency_id, @@ -780,11 +780,11 @@ impl DBVersion { acc.entry(DBVersionId(m.version_id)) .or_default() .push(dependency); - async move { eyre::Ok(acc) } + async move { anyhow::Ok(acc) } } ) .await - .wrap_err("fetching version dependencies")?; + .context("fetching version dependencies")?; let dependency_attributions = crate::queue::file_scan::get_dependency_attributions( @@ -811,7 +811,7 @@ impl DBVersion { ) .fetch_all(&mut exec) .await - .wrap_err("fetching version rows")?; + .context("fetching version rows")?; let version_components = version_rows.iter() .map(|row| (DBVersionId(row.id).into(), &row.components.0)) @@ -822,7 +822,7 @@ impl DBVersion { redis, ) .await - .wrap_err("fetching version query context")?; + .context("fetching version query context")?; let res = version_rows.into_iter() .try_fold(DashMap::new(), |acc, v| { @@ -851,7 +851,7 @@ impl DBVersion { let components_serial = v.components.0; let components = components_serial.clone() .into_query(version_id.into(), &version_query_context) - .wrap_err("failed to populate query components")?; + .context("failed to populate query components")?; let query_version = VersionQueryResult { inner: DBVersion { id: DBVersionId(v.id), @@ -913,15 +913,15 @@ impl DBVersion { }; acc.insert(v.id, query_version); - eyre::Ok(acc) + anyhow::Ok(acc) }) - .wrap_err("populating versions")?; + .context("populating versions")?; - eyre::Ok(res) + anyhow::Ok(res) }, ) .await - .wrap_err("fetching cached versions")?; + .context("fetching cached versions")?; val.sort(); @@ -940,7 +940,7 @@ impl DBVersion { { Self::get_files_from_hash(algo, &[hash], executor, redis) .await - .wrap_err("fetching version file from hash") + .context("fetching version file from hash") .map(|x| { x.into_iter() .find_or_first(|x| Some(x.version_id) == version_id) @@ -975,7 +975,7 @@ impl DBVersion { &file_ids.into_iter().filter_map(|x| x.split('_').last().map(|x| x.as_bytes().to_vec())).collect::>(), ) .fetch(executor) - .map_err(eyre::Report::from) + .map_err(anyhow::Error::from) .try_fold(DashMap::new(), |acc, f| { #[derive(Deserialize)] struct Hash { @@ -1008,16 +1008,16 @@ impl DBVersion { acc.insert(key, file); } - async move { eyre::Ok(acc) } + async move { anyhow::Ok(acc) } }) .await - .wrap_err("fetching version files from hashes")?; + .context("fetching version files from hashes")?; - eyre::Ok(files) + anyhow::Ok(files) } ) .await - .wrap_err("fetching cached version files")?; + .context("fetching cached version files")?; Ok(val) } @@ -1029,7 +1029,7 @@ impl DBVersion { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear version cache")?; + .context("connecting to redis to clear version cache")?; let mut keys = vec![redis.key().entity(VERSIONS_NAMESPACE, version.inner.id.0)]; keys.extend(version.files.iter().flat_map(|file| { @@ -1044,7 +1044,7 @@ impl DBVersion { redis .delete_many(&keys) .await - .wrap_err("clearing version cache")?; + .context("clearing version cache")?; Ok(()) } @@ -1055,7 +1055,7 @@ impl DBVersion { let mut redis = redis .connect() .await - .wrap_err("connecting to redis to clear version caches")?; + .context("connecting to redis to clear version caches")?; let keys = version_ids .iter() .map(|id| redis.key().entity(VERSIONS_NAMESPACE, id.0)) @@ -1064,7 +1064,7 @@ impl DBVersion { redis .delete_many(&keys) .await - .wrap_err("clearing version caches")?; + .context("clearing version caches")?; Ok(()) } } diff --git a/apps/labrinth/src/database/postgres_database.rs b/apps/labrinth/src/database/postgres_database.rs index 9db9dd385ed..a8e8f7b479e 100644 --- a/apps/labrinth/src/database/postgres_database.rs +++ b/apps/labrinth/src/database/postgres_database.rs @@ -1,4 +1,4 @@ -use eyre::Context; +use anyhow::Context; use prometheus::{IntGauge, Registry}; use sqlx::migrate::{MigrateDatabase, Migrator}; use sqlx::postgres::PgPoolOptions; @@ -83,17 +83,17 @@ pub async fn connect_all() -> Result<(PgPool, ReadOnlyPgPool), sqlx::Error> { } } -pub async fn check_for_migrations() -> eyre::Result<()> { +pub async fn check_for_migrations() -> anyhow::Result<()> { let uri = &ENV.DATABASE_URL; let uri = uri.as_str(); if !Postgres::database_exists(uri) .await - .wrap_err("failed to check if database exists")? + .context("failed to check if database exists")? { info!("Creating database..."); Postgres::create_database(uri) .await - .wrap_err("failed to create database")?; + .context("failed to create database")?; } info!("Applying migrations..."); @@ -101,11 +101,11 @@ pub async fn check_for_migrations() -> eyre::Result<()> { let mut conn: sqlx::PgConnection = sqlx::PgConnection::connect(uri) .await - .wrap_err("failed to connect to database")?; + .context("failed to connect to database")?; MIGRATOR .run(&mut conn) .await - .wrap_err("failed to run database migrations")?; + .context("failed to run database migrations")?; Ok(()) } diff --git a/apps/labrinth/src/database/redis/mod.rs b/apps/labrinth/src/database/redis/mod.rs index 5c6ebf1dfb9..a8beed62376 100644 --- a/apps/labrinth/src/database/redis/mod.rs +++ b/apps/labrinth/src/database/redis/mod.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use crate::env::ENV; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; struct RedisConfig { inner: xredis::RedisConfig, @@ -27,7 +27,7 @@ impl RedisConfig { ENV.REDIS_CACHE_LOCKING_STRATEGY, ENV.REDIS_READ_REPLICA_STRATEGY, ) - .wrap_err("loading Redis configuration from environment")?; + .context("loading Redis configuration from environment")?; let cache_settings = xredis::CacheSettings { default_expiry: ENV.REDIS_DEFAULT_EXPIRY, actual_expiry: ENV.REDIS_ACTUAL_EXPIRY, diff --git a/apps/labrinth/src/env.rs b/apps/labrinth/src/env.rs index f9ad395ad0d..d2cb85b48ca 100644 --- a/apps/labrinth/src/env.rs +++ b/apps/labrinth/src/env.rs @@ -3,8 +3,8 @@ use std::{ sync::LazyLock, }; +use anyhow::{Context, anyhow}; use derive_more::{Deref, DerefMut}; -use eyre::{Context, eyre}; use serde::de::DeserializeOwned; use url::Url; @@ -33,8 +33,8 @@ macro_rules! vars { } impl EnvVars { - pub fn from_env() -> eyre::Result { - let mut err = eyre!("failed to read environment variables"); + pub fn from_env() -> anyhow::Result { + let mut err = anyhow!("failed to read environment variables"); $( #[expect( @@ -53,7 +53,7 @@ macro_rules! vars { match parse_value::<$ty>(stringify!($field), default) { Ok(value) => Some(value), Err(source) => { - err = err.wrap_err(eyre!("{source:#}")); + err = err.context(anyhow!("{source:#}")); None } } @@ -77,21 +77,21 @@ pub static ENV: LazyLock = LazyLock::new(|| { EnvVars::from_env().unwrap_or_else(|err| panic!("{err:?}")) }); -fn parse_value(key: &str, default: Option) -> eyre::Result +fn parse_value(key: &str, default: Option) -> anyhow::Result where T: FromStr, T::Err: std::error::Error + Send + Sync + 'static, { match (dotenvy::var(key), default) { - (Ok(value), _) => value.parse::().wrap_err_with(|| { - eyre!("`{key}` is not a valid `{}`", type_name::()) + (Ok(value), _) => value.parse::().with_context(|| { + anyhow!("`{key}` is not a valid `{}`", type_name::()) }), (Err(_), Some(default)) => Ok(default), - (Err(_), None) => Err(eyre!("`{key}` missing")), + (Err(_), None) => Err(anyhow!("`{key}` missing")), } } -pub fn init() -> eyre::Result<()> { +pub fn init() -> anyhow::Result<()> { dotenvy::dotenv().ok(); EnvVars::from_env()?; LazyLock::force(&ENV); diff --git a/apps/labrinth/src/file_hosting/kafka_host.rs b/apps/labrinth/src/file_hosting/kafka_host.rs index 8661bf2c3f7..6011092cf42 100644 --- a/apps/labrinth/src/file_hosting/kafka_host.rs +++ b/apps/labrinth/src/file_hosting/kafka_host.rs @@ -1,9 +1,9 @@ use std::sync::Arc; use actix_web::web; +use anyhow::{Context, Result, anyhow}; use async_trait::async_trait; use bytes::Bytes; -use eyre::{Result, WrapErr, eyre}; use rdkafka::{producer::FutureRecord, util::Timeout}; use serde::Serialize; @@ -57,7 +57,7 @@ impl KafkaFileHost { }, ); let payload = serde_json::to_vec(&event) - .wrap_err("serializing file uploaded event")?; + .context("serializing file uploaded event")?; let record = FutureRecord::to(FILE_UPLOADED_TOPIC) .key(&data.file_name) .payload(&payload) @@ -67,8 +67,8 @@ impl KafkaFileHost { .client .send(record, Timeout::After(KAFKA_OPERATION_INTERVAL)) .await - .map_err(|(err, _)| eyre!(err)) - .wrap_err("publishing file uploaded event")?; + .map_err(|(err, _)| anyhow!(err)) + .context("publishing file uploaded event")?; Ok(()) } diff --git a/apps/labrinth/src/lib.rs b/apps/labrinth/src/lib.rs index 37d42ca5999..0f386f4785d 100644 --- a/apps/labrinth/src/lib.rs +++ b/apps/labrinth/src/lib.rs @@ -1,5 +1,6 @@ #![recursion_limit = "256"] +use anyhow::anyhow; use std::sync::Arc; use std::time::Duration; @@ -295,16 +296,16 @@ pub fn app_data_config( labrinth_config: LabrinthConfig, ) { cfg.app_data(web::FormConfig::default().error_handler(|err, _req| { - routes::ApiError::Request(eyre::eyre!("{err}")).into() + routes::ApiError::Request(anyhow!("{err}")).into() })) .app_data(web::PathConfig::default().error_handler(|err, _req| { - routes::ApiError::Request(eyre::eyre!("{err}")).into() + routes::ApiError::Request(anyhow!("{err}")).into() })) .app_data(web::QueryConfig::default().error_handler(|err, _req| { - routes::ApiError::Request(eyre::eyre!("{err}")).into() + routes::ApiError::Request(anyhow!("{err}")).into() })) .app_data(web::JsonConfig::default().error_handler(|err, _req| { - routes::ApiError::Request(eyre::eyre!("{err}")).into() + routes::ApiError::Request(anyhow!("{err}")).into() })) .app_data(web::Data::new(labrinth_config.redis_pool.clone())) .app_data(web::Data::new(labrinth_config.pool.clone())) diff --git a/apps/labrinth/src/main.rs b/apps/labrinth/src/main.rs index b34f4ab782f..9f1a74f51a5 100644 --- a/apps/labrinth/src/main.rs +++ b/apps/labrinth/src/main.rs @@ -65,7 +65,6 @@ struct Args { } fn main() -> std::io::Result<()> { - color_eyre::install().expect("failed to install `color-eyre`"); modrinth_util::log::init().expect("failed to initialize logging"); env::init().expect("failed to initialize environment variables"); diff --git a/apps/labrinth/src/models/exp/component.rs b/apps/labrinth/src/models/exp/component.rs index 1fcd3b3e4dc..7c373750fdd 100644 --- a/apps/labrinth/src/models/exp/component.rs +++ b/apps/labrinth/src/models/exp/component.rs @@ -101,10 +101,10 @@ macro_rules! define { } pub mod unwrap_edit { - use eyre::{Result, eyre}; + use anyhow::{Result, anyhow}; pub fn required(field: Option, field_name: &str) -> Result { - field.ok_or_else(|| eyre!("missing field `{field_name}`")) + field.ok_or_else(|| anyhow!("missing field `{field_name}`")) } pub fn optional( @@ -117,7 +117,7 @@ pub mod unwrap_edit { // value is omitted from json -> no value None => Ok(None), // value is in json but is null -> empty - Some(None) => Err(eyre!("missing field `{field_name}`")), + Some(None) => Err(anyhow!("missing field `{field_name}`")), } } @@ -140,8 +140,8 @@ macro_rules! relations { }; } +use anyhow::Result; pub(crate) use define; -use eyre::Result; pub(crate) use relations; use serde::{Deserialize, Serialize, de::DeserializeOwned}; diff --git a/apps/labrinth/src/models/exp/minecraft.rs b/apps/labrinth/src/models/exp/minecraft.rs index 23d390b3270..a38323fa1dc 100644 --- a/apps/labrinth/src/models/exp/minecraft.rs +++ b/apps/labrinth/src/models/exp/minecraft.rs @@ -1,7 +1,8 @@ +use anyhow::anyhow; use std::time::Duration; +use anyhow::Result; use chrono::{DateTime, Utc}; -use eyre::Result; use minecraft_meta_model::model::MinecraftVersionName; use serde::{Deserialize, Serialize}; use serde_binhum::serde_binhum; @@ -129,7 +130,7 @@ pub enum Language { #[serde(rename_all = "snake_case")] #[strum( serialize_all = "snake_case", - parse_err_ty = eyre::Report, + parse_err_ty = anyhow::Error, parse_err_fn = invalid_minecraft_metadata_value )] pub enum Environment { @@ -164,7 +165,7 @@ pub enum Environment { #[serde(rename_all = "lowercase")] #[strum( serialize_all = "lowercase", - parse_err_ty = eyre::Report, + parse_err_ty = anyhow::Error, parse_err_fn = invalid_minecraft_metadata_value )] pub enum MrpackLoader { @@ -216,8 +217,8 @@ impl MrpackLoader { } } -fn invalid_minecraft_metadata_value(value: &str) -> eyre::Report { - eyre::eyre!("invalid Minecraft metadata value `{value}`") +fn invalid_minecraft_metadata_value(value: &str) -> anyhow::Error { + anyhow!("invalid Minecraft metadata value `{value}`") } component::define! { @@ -455,7 +456,7 @@ impl ComponentEdit for JavaServerProjectEdit { fn create(self) -> Result { Ok(JavaServerProject { - address: self.address.wrap_err("missing `address`")?, + address: self.address.context("missing `address`")?, content: self.content.unwrap_or_default(), }) } diff --git a/apps/labrinth/src/models/exp/project.rs b/apps/labrinth/src/models/exp/project.rs index 4dcc06fcabb..0b60a9d27ca 100644 --- a/apps/labrinth/src/models/exp/project.rs +++ b/apps/labrinth/src/models/exp/project.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use validator::Validate; @@ -102,7 +102,7 @@ macro_rules! define_project_components { context, ) .map(Some) - .wrap_err(concat!("failed to populate `", stringify!($ty), "`"))? + .context(concat!("failed to populate `", stringify!($ty), "`"))? } None => None, }, @@ -231,7 +231,7 @@ pub async fn fetch_query_context( ) .fetch_all(db) .await - .wrap_err("failed to fetch partial versions")? + .context("failed to fetch partial versions")? .into_iter() .map(|row| { ( diff --git a/apps/labrinth/src/models/exp/version.rs b/apps/labrinth/src/models/exp/version.rs index dac8e0d5b31..3217f1c6525 100644 --- a/apps/labrinth/src/models/exp/version.rs +++ b/apps/labrinth/src/models/exp/version.rs @@ -6,7 +6,7 @@ use crate::models::exp::{ use crate::models::exp::component::ComponentQuery; use crate::models::ids::VersionId; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use validator::Validate; @@ -90,7 +90,7 @@ macro_rules! define_version_components { context, ) .map(Some) - .wrap_err(concat!("failed to populate `", stringify!($ty), "`"))?, + .context(concat!("failed to populate `", stringify!($ty), "`"))?, None => None, }, )* diff --git a/apps/labrinth/src/models/minecraft.rs b/apps/labrinth/src/models/minecraft.rs index f7c8cd7daeb..0e51097239d 100644 --- a/apps/labrinth/src/models/minecraft.rs +++ b/apps/labrinth/src/models/minecraft.rs @@ -5,8 +5,8 @@ use crate::util::minecraft_meta::MinecraftVersionEntry; use std::collections::HashMap; use std::sync::LazyLock; +use anyhow::{Result, anyhow}; use chrono::{DateTime, Utc}; -use eyre::{Result, eyre}; use minecraft_meta_model::{ model::MinecraftVersionName, upstream::mojang::VersionType, }; @@ -58,7 +58,7 @@ pub fn parse_minecraft_fields( value .as_str() .ok_or_else(|| { - eyre!("`environment` must be a string") + anyhow!("`environment` must be a string") })? .parse::()?, ) @@ -72,7 +72,7 @@ pub fn parse_minecraft_fields( .collect::>>()?, ); } - _ => return Err(eyre!("unknown Minecraft field `{name}`")), + _ => return Err(anyhow!("unknown Minecraft field `{name}`")), } } Ok(edit) @@ -81,12 +81,12 @@ pub fn parse_minecraft_fields( fn string_array<'a>(value: &'a Value, field: &str) -> Result> { value .as_array() - .ok_or_else(|| eyre!("`{field}` must be an array"))? + .ok_or_else(|| anyhow!("`{field}` must be an array"))? .iter() .map(|value| { value .as_str() - .ok_or_else(|| eyre!("`{field}` must contain only strings")) + .ok_or_else(|| anyhow!("`{field}` must contain only strings")) }) .collect() } diff --git a/apps/labrinth/src/models/v2/projects.rs b/apps/labrinth/src/models/v2/projects.rs index ac11246a769..29d83f89d44 100644 --- a/apps/labrinth/src/models/v2/projects.rs +++ b/apps/labrinth/src/models/v2/projects.rs @@ -11,9 +11,9 @@ use crate::models::projects::{ Project, ProjectStatus, Version, VersionFile, VersionStatus, VersionType, }; use crate::routes::v2_reroute::{self, capitalize_first}; +use anyhow::{Context, Result, anyhow}; use ariadne::ids::UserId; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use validator::Validate; @@ -251,14 +251,14 @@ impl LegacyProject { let example_versions = version_item::DBVersion::get_many(&version_ids, pool, redis) .await - .wrap_err("fetching example versions for legacy projects")?; + .context("fetching example versions for legacy projects")?; let archived_disclosure_ids = DBProjectDisclosure::projects_with_type( ProjectDisclosureType::Archived, &project_ids, pool, ) .await - .wrap_err("fetching archived disclosures for legacy projects")?; + .context("fetching archived disclosures for legacy projects")?; let mut legacy_projects = Vec::new(); for project in data { @@ -473,12 +473,12 @@ pub fn validate_donation_platforms( .parse::() .is_ok_and(LinkPlatform::is_donation) { - return Err(crate::routes::ApiError::Request(eyre::eyre!( + return Err(crate::routes::ApiError::Request(anyhow!( "each donation link must specify a donation platform" ))); } if !platforms.insert(&link.id) { - return Err(crate::routes::ApiError::Request(eyre::eyre!( + return Err(crate::routes::ApiError::Request(anyhow!( "donation platforms must not be repeated" ))); } diff --git a/apps/labrinth/src/models/v3/moderation_notes.rs b/apps/labrinth/src/models/v3/moderation_notes.rs index 5488ec0ddff..883eac69b50 100644 --- a/apps/labrinth/src/models/v3/moderation_notes.rs +++ b/apps/labrinth/src/models/v3/moderation_notes.rs @@ -1,4 +1,5 @@ use actix_web::{HttpRequest, http::header::IF_MATCH}; +use anyhow::anyhow; use ariadne::ids::UserId; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; @@ -38,7 +39,7 @@ pub struct PatchModerationNote { impl PatchModerationNote { pub fn validate_not_empty(&self) -> Result<(), ApiError> { if self.notes.is_none() && self.user_rating.is_none() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "must specify `notes` or `user_rating`", ))); } @@ -54,14 +55,12 @@ pub fn parse_if_match_header( return Ok(None); }; - let value = value.to_str().wrap_request_err( + let value = value.to_str().request_context( "`if-match` header must be a valid integer".to_string(), )?; Some(value.parse::().map_err(|_| { - ApiError::Request(eyre::eyre!( - "`if-match` header must be a valid integer", - )) + ApiError::Request(anyhow!("`if-match` header must be a valid integer",)) })) .transpose() } diff --git a/apps/labrinth/src/models/v3/notifications.rs b/apps/labrinth/src/models/v3/notifications.rs index 9675825d1be..12a00412ea8 100644 --- a/apps/labrinth/src/models/v3/notifications.rs +++ b/apps/labrinth/src/models/v3/notifications.rs @@ -9,6 +9,7 @@ use crate::models::ids::{ }; use crate::models::projects::ProjectStatus; use crate::routes::ApiError; +use anyhow::anyhow; use ariadne::ids::UserId; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; @@ -794,8 +795,8 @@ impl NotificationDeliveryStatus { NotificationDeliveryStatus::Delivered => Ok(()), NotificationDeliveryStatus::SkippedPreferences | NotificationDeliveryStatus::SkippedDefault | - NotificationDeliveryStatus::Pending => Err(ApiError::Request(eyre::eyre!("An error occurred while sending an email to your email address. Please try again later.".to_owned()))), - NotificationDeliveryStatus::PermanentlyFailed => Err(ApiError::Request(eyre::eyre!("This email address doesn't exist! Please try another one.".to_owned()))), + NotificationDeliveryStatus::Pending => Err(ApiError::Request(anyhow!("An error occurred while sending an email to your email address. Please try again later.".to_owned()))), + NotificationDeliveryStatus::PermanentlyFailed => Err(ApiError::Request(anyhow!("This email address doesn't exist! Please try another one.".to_owned()))), } } diff --git a/apps/labrinth/src/queue/analytics/cache.rs b/apps/labrinth/src/queue/analytics/cache.rs index 76715a3bed6..aac6c0960b4 100644 --- a/apps/labrinth/src/queue/analytics/cache.rs +++ b/apps/labrinth/src/queue/analytics/cache.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; use xredis::RedisPool; +use anyhow::{Result, anyhow}; use const_format::formatcp; -use eyre::{Result, eyre}; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use tracing::{debug, info}; @@ -75,7 +75,7 @@ pub async fn cache_analytics( )) .fetch_all::() .await - .wrap_err("failed to create cursor for total server plays")?; + .context("failed to create cursor for total server plays")?; info!( "Caching Minecraft server analytics for {} projects", @@ -94,7 +94,7 @@ pub async fn cache_analytics( ) .fetch_all(db) .await - .wrap_internal_err("failed to get slugs for projects to cache analytics")? + .internal_context("failed to get slugs for projects to cache analytics")? .into_iter() .filter_map(|row| { row.slug @@ -105,7 +105,7 @@ pub async fn cache_analytics( let mut redis = redis_pool .connect() .await - .wrap_err("failed to connect to redis")?; + .context("failed to connect to redis")?; for row in rows { let project_id = ProjectId(row.project_id); @@ -119,8 +119,8 @@ pub async fn cache_analytics( redis .set_serialized(&key, analytics, None) .await - .wrap_err_with(|| { - eyre!("failed to set analytics for project '{project_id}'") + .with_context(|| { + anyhow!("failed to set analytics for project '{project_id}'") })?; DBProject::clear_cache( @@ -130,8 +130,8 @@ pub async fn cache_analytics( redis_pool, ) .await - .wrap_err_with(|| { - eyre!("failed to clear cache for project '{project_id}'") + .with_context(|| { + anyhow!("failed to clear cache for project '{project_id}'") })?; } diff --git a/apps/labrinth/src/queue/billing.rs b/apps/labrinth/src/queue/billing.rs index 95fc13871f2..509d3778221 100644 --- a/apps/labrinth/src/queue/billing.rs +++ b/apps/labrinth/src/queue/billing.rs @@ -26,6 +26,7 @@ use crate::util::archon::{CreateServerRequest, Specs}; use crate::util::error::ApiContext as _; use crate::util::error::Context; use crate::util::stripe::StripeContext as _; +use anyhow::anyhow; use ariadne::ids::base62_impl::to_base62; use chrono::Utc; use futures::FutureExt; @@ -53,11 +54,11 @@ async fn update_tax_amounts( let mut txn = pg .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let charges = DBCharge::get_updateable_lock(&mut txn, 5) .await - .wrap_internal_err("fetching charges from database")?; + .internal_context("fetching charges from database")?; if charges.is_empty() { info!("No more charges to process"); @@ -87,10 +88,10 @@ async fn update_tax_amounts( let op_fut = async move { let product = DBProduct::get_price(charge.price_id, &pg) .await - .wrap_internal_err( + .internal_context( "fetching product price from database", )? - .wrap_internal_err( + .internal_context( "finding product price in database", )?; @@ -132,7 +133,7 @@ async fn update_tax_amounts( // for this. let subscription_id = - charge.subscription_id.wrap_request_err_with( + charge.subscription_id.request_context_with( || "charge has no subscription ID".to_owned(), )?; @@ -153,7 +154,7 @@ async fn update_tax_amounts( } .insert(charge.user_id, &mut txn, redis) .await - .wrap_internal_err("inserting database records for `update_tax_amounts`")?; + .internal_context("inserting database records for `update_tax_amounts`")?; charge.tax_amount = new_tax_amount; } @@ -170,12 +171,12 @@ async fn update_tax_amounts( charge .upsert(&mut txn) .await - .wrap_internal_err("updating subscription id in database")?; + .internal_context("updating subscription id in database")?; } txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; if processed_charges >= limit { break Ok(()); @@ -211,7 +212,7 @@ async fn update_anrok_transactions( .payment_platform_id .as_ref() .and_then(|x| x.parse().ok()) - .wrap_request_err_with(|| { + .request_context_with(|| { "refund charge has no or an invalid refund ID" .to_owned() })?; @@ -220,12 +221,12 @@ async fn update_anrok_transactions( .expand(["payment_intent.payment_method".to_owned()]) .send(stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; let pi = refund .payment_intent .and_then(|x| x.into_object()) - .wrap_request_err_with(|| { + .request_context_with(|| { "refund charge has no payment intent".to_owned() })?; @@ -235,7 +236,7 @@ async fn update_anrok_transactions( .payment_platform_id .as_ref() .and_then(|x| x.parse().ok()) - .wrap_request_err_with(|| { + .request_context_with(|| { "charge has no payment platform ID".to_owned() })?; @@ -245,7 +246,7 @@ async fn update_anrok_transactions( .expand(["payment_method".to_owned()]) .send(stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; let anrok_id = anrok::transaction_id_stripe_pi(&stripe_id); @@ -259,15 +260,15 @@ async fn update_anrok_transactions( let stripe_customer = DBUser::get_id(c.user_id, &mut *txn, redis) .await - .wrap_internal_err("fetching Stripe customer from database")? - .wrap_internal_err("finding Stripe customer in database")?; + .internal_context("fetching Stripe customer from database")? + .internal_context("finding Stripe customer in database")?; let stripe_customer_id = stripe_customer .stripe_customer_id - .wrap_request_err("finding Stripe customer ID on user")?; + .request_context("finding Stripe customer ID on user")?; let customer_id: CustomerId = stripe_customer_id .parse() - .wrap_request_err("parsing request value")?; + .request_context("parsing request value")?; match pi_stripe_address { Some(address) => { @@ -295,7 +296,7 @@ async fn update_anrok_transactions( c.tax_platform_id = Some("unresolved".to_owned()); c.upsert(txn) .await - .wrap_internal_err("updating customer in database")?; + .internal_context("updating customer in database")?; return Ok(()); }; @@ -305,8 +306,8 @@ async fn update_anrok_transactions( let tax_id = DBProductsTaxIdentifier::get_price(c.price_id, &mut *txn) .await - .wrap_api_err("fetching price")? - .wrap_internal_err("finding product tax identifier for price")?; + .api_context("fetching price")? + .internal_context("finding product tax identifier for price")?; // Note: if the tax amount that was charged to the customer is *different* than // what it *should* be NOW, we will take on a loss here. @@ -335,7 +336,7 @@ async fn update_anrok_transactions( match result { Ok(response) => { - let version = response.version.wrap_request_err_with(|| { + let version = response.version.request_context_with(|| { "anrok response is missing tax transaction version" .to_owned() })?; @@ -346,7 +347,7 @@ async fn update_anrok_transactions( c.tax_platform_accounting_time = Some(c.due); c.upsert(txn) .await - .wrap_internal_err("updating version in database")?; + .internal_context("updating version in database")?; Ok(()) } @@ -359,11 +360,11 @@ async fn update_anrok_transactions( c.tax_platform_id = Some("unresolved".to_owned()); c.upsert(txn) .await - .wrap_internal_err("updating version in database")?; + .internal_context("updating version in database")?; Ok(()) } else { - Err(ApiError::Internal(eyre::eyre!( + Err(ApiError::Internal(anyhow!( "calculating tax with Anrok: {error}" ))) } @@ -379,12 +380,12 @@ async fn update_anrok_transactions( let mut txn = pg .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut charges = DBCharge::get_missing_tax_identifier_lock(&mut txn, offset, 1) .await - .wrap_internal_err("fetching charges from database")?; + .internal_context("fetching charges from database")?; let Some(c) = charges.pop() else { info!("No more charges to process"); @@ -410,7 +411,7 @@ async fn update_anrok_transactions( txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; if processed_charges >= limit { break Ok(()); @@ -433,7 +434,7 @@ pub async fn try_process_user_redeemal( let updated = user_redeemal .update_status_if_pending(pool) .await - .wrap_internal_err("updating updated in database")?; + .internal_context("updating updated in database")?; if !updated { return Ok(()); @@ -448,7 +449,7 @@ pub async fn try_process_user_redeemal( pool, "medal", ) .await - .wrap_internal_err("fetching query product with prices from Redis")?; + .internal_context("fetching query product with prices from Redis")?; let Some(product_item::QueryProductWithPrices { id: _product_id, @@ -458,7 +459,7 @@ pub async fn try_process_user_redeemal( name: _, }) = medal_products.pop() else { - return Err(ApiError::Conflict(eyre::eyre!( + return Err(ApiError::Conflict(anyhow!( "Missing Medal subscription product".to_owned(), ))); }; @@ -471,20 +472,20 @@ pub async fn try_process_user_redeemal( region, } = metadata else { - return Err(ApiError::Conflict(eyre::eyre!( + return Err(ApiError::Conflict(anyhow!( "Missing or incorrect metadata for Medal subscription".to_owned(), ))); }; let Some(medal_price) = prices.pop() else { - return Err(ApiError::Conflict(eyre::eyre!( + return Err(ApiError::Conflict(anyhow!( "Missing price for Medal subscription".to_owned(), ))); }; let (price_duration, price_amount) = match medal_price.prices { Price::OneTime { price: _ } => { - return Err(ApiError::Conflict(eyre::eyre!( + return Err(ApiError::Conflict(anyhow!( "Unexpected metadata for Medal subscription price".to_owned(), ))); } @@ -493,7 +494,7 @@ pub async fn try_process_user_redeemal( let Some((price_duration, price_amount)) = intervals.into_iter().next() else { - return Err(ApiError::Conflict(eyre::eyre!( + return Err(ApiError::Conflict(anyhow!( "Missing price interval for Medal subscription".to_owned(), ))); }; @@ -508,14 +509,14 @@ pub async fn try_process_user_redeemal( let user = DBUser::get_id(user_id, pool, redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching user from database")? + .not_found_context("resource not found")?; // Send the provision request to Archon. On failure, the redeemal will be "stuck" processing, // and moved back to pending by `index_subscriptions`. let archon_client = ArchonClient::from_env() - .wrap_api_err("executing `ArchonClient::from_env`")?; + .api_context("executing `ArchonClient::from_env`")?; let server_id = archon_client .create_server(&CreateServerRequest { user_id: to_base62(user_id.0 as u64), @@ -531,20 +532,20 @@ pub async fn try_process_user_redeemal( tags: vec!["medal".to_owned()], }) .await - .wrap_internal_err( + .internal_context( "inserting database records for `try_process_user_redeemal`", )?; let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; // Build a subscription using this price ID. let subscription = DBUserSubscription { id: generate_user_subscription_id(&mut txn) .await - .wrap_internal_err("generating user subscription ID")?, + .internal_context("generating user subscription ID")?, user_id, price_id, interval: PriceDuration::FiveDays, @@ -558,14 +559,14 @@ pub async fn try_process_user_redeemal( subscription .upsert(&mut txn) .await - .wrap_internal_err("generating user subscription ID")?; + .internal_context("generating user subscription ID")?; // Insert an expiring charge, `index_subscriptions` will unprovision the // subscription when expired. DBCharge { id: generate_charge_id(&mut txn) .await - .wrap_internal_err("generating redeemal charge ID")?, + .internal_context("generating redeemal charge ID")?, user_id, price_id, amount: price_amount.into(), @@ -589,17 +590,17 @@ pub async fn try_process_user_redeemal( } .upsert(&mut txn) .await - .wrap_internal_err("upserting redeemal charge")?; + .internal_context("upserting redeemal charge")?; // Update `users_redeemal`, mark subscription as redeemed. user_redeemal.status = users_redeemals::Status::Processed; - user_redeemal.update(&mut txn).await.wrap_internal_err( + user_redeemal.update(&mut txn).await.internal_context( "updating database records for `try_process_user_redeemal`", )?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(()) } @@ -607,7 +608,7 @@ pub async fn try_process_user_redeemal( pub async fn cancel_failing_charges(pool: &PgPool) -> Result<(), ApiError> { let charges_to_cancel = DBCharge::get_cancellable(pool) .await - .wrap_internal_err("fetching charge from database")?; + .internal_context("fetching charge from database")?; for mut charge in charges_to_cancel { charge.status = ChargeStatus::Cancelled; @@ -615,15 +616,15 @@ pub async fn cancel_failing_charges(pool: &PgPool) -> Result<(), ApiError> { let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; charge .upsert(&mut transaction) .await - .wrap_internal_err("updating transaction in database")?; + .internal_context("updating transaction in database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } Ok(()) @@ -637,7 +638,7 @@ pub async fn process_chargeable_charges( ) -> Result<(), ApiError> { let charges_to_do = DBCharge::get_chargeable(pool) .await - .wrap_internal_err("fetching charge from database")?; + .internal_context("fetching charge from database")?; let prices = product_item::DBProductPrice::get_many( &charges_to_do @@ -649,7 +650,7 @@ pub async fn process_chargeable_charges( pool, ) .await - .wrap_internal_err("fetching product prices from database")?; + .internal_context("fetching product prices from database")?; let users = crate::database::models::DBUser::get_many_ids( &charges_to_do @@ -662,7 +663,7 @@ pub async fn process_chargeable_charges( redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; for mut charge in charges_to_do { let Some(product_price) = @@ -748,15 +749,15 @@ pub async fn process_chargeable_charges( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; charge .upsert(&mut transaction) .await - .wrap_internal_err("updating transaction in database")?; + .internal_context("updating transaction in database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } Ok(()) @@ -771,7 +772,7 @@ async fn unprovision_subscriptions( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut clear_cache_users = Vec::new(); // If an active subscription has: @@ -781,7 +782,7 @@ async fn unprovision_subscriptions( // It should be unprovisioned let all_charges = DBCharge::get_unprovision(pool) .await - .wrap_internal_err("fetching charges from database")?; + .internal_context("fetching charges from database")?; let mut all_subscriptions = user_subscription_item::DBUserSubscription::get_many( @@ -794,7 +795,7 @@ async fn unprovision_subscriptions( pool, ) .await - .wrap_internal_err("fetching user subscriptions from database")?; + .internal_context("fetching user subscriptions from database")?; let subscription_prices = product_item::DBProductPrice::get_many( &all_subscriptions .iter() @@ -805,7 +806,7 @@ async fn unprovision_subscriptions( pool, ) .await - .wrap_internal_err("fetching product prices from database")?; + .internal_context("fetching product prices from database")?; let subscription_products = product_item::DBProduct::get_many( &subscription_prices .iter() @@ -816,7 +817,7 @@ async fn unprovision_subscriptions( pool, ) .await - .wrap_internal_err("fetching products from database")?; + .internal_context("fetching products from database")?; let users = DBUser::get_many_ids( &all_subscriptions .iter() @@ -828,7 +829,7 @@ async fn unprovision_subscriptions( redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; for charge in all_charges { debug!("Unprovisioning charge '{}'", to_base62(charge.id.0 as u64)); @@ -878,7 +879,7 @@ async fn unprovision_subscriptions( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `unprovision_subscriptions`", )?; @@ -924,7 +925,7 @@ async fn unprovision_subscriptions( subscription .upsert(&mut transaction) .await - .wrap_internal_err("updating err in database")?; + .internal_context("updating err in database")?; } clear_cache_users.push(user.id); @@ -938,11 +939,11 @@ async fn unprovision_subscriptions( redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(()) } @@ -954,7 +955,7 @@ async fn process_redeemals( // If an offer redeemal has been processing for over 5 minutes, it should be set pending. UserRedeemal::update_stuck_5_minutes(pool) .await - .wrap_internal_err( + .internal_context( "updating database records for `process_redeemals`", )?; @@ -962,7 +963,7 @@ async fn process_redeemals( // Try processing it. let pending_redeemals = UserRedeemal::get_pending(pool, 100) .await - .wrap_internal_err("fetching user redeemal from Redis")?; + .internal_context("fetching user redeemal from Redis")?; for redeemal in pending_redeemals { if let Err(error) = try_process_user_redeemal(pool, redis, redeemal).await diff --git a/apps/labrinth/src/queue/delphi_scan.rs b/apps/labrinth/src/queue/delphi_scan.rs index ec928aec7b0..ff044ab01f4 100644 --- a/apps/labrinth/src/queue/delphi_scan.rs +++ b/apps/labrinth/src/queue/delphi_scan.rs @@ -1,4 +1,4 @@ -use eyre::{Result, WrapErr, eyre}; +use anyhow::{Context, Result, anyhow}; use rdkafka::{producer::FutureRecord, util::Timeout}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -72,7 +72,7 @@ pub async fn publish_file_scan( ); let key = event.data.file_id.to_string(); let payload = serde_json::to_vec(&event) - .wrap_err("serializing Delphi file scan event")?; + .context("serializing Delphi file scan event")?; let record = FutureRecord::to(DELPHI_FILE_SCAN_TOPIC) .key(&key) .payload(&payload) @@ -85,9 +85,9 @@ pub async fn publish_file_scan( .send(record, Timeout::After(KAFKA_OPERATION_INTERVAL)), ) .await - .wrap_err("timing out Delphi file scan event publication")? - .map_err(|(err, _)| eyre!(err)) - .wrap_err("publishing Delphi file scan event")?; + .context("timing out Delphi file scan event publication")? + .map_err(|(err, _)| anyhow!(err)) + .context("publishing Delphi file scan event")?; Ok(()) } @@ -118,7 +118,7 @@ pub async fn record_succeeded_scan( ) .execute(&mut *transaction) .await - .wrap_err("recording successful Delphi file scan")?; + .context("recording successful Delphi file scan")?; Ok(()) } @@ -129,14 +129,14 @@ pub(crate) async fn fetch_delphi_version() -> Result { .send() .await .and_then(|response| response.error_for_status()) - .wrap_err("fetching Delphi version")?; + .context("fetching Delphi version")?; let version = response .text() .await - .wrap_err("reading Delphi version response body")?; + .context("reading Delphi version response body")?; - version.trim().parse().wrap_err_with(|| { - eyre!("invalid Delphi version response body: {version}") + version.trim().parse().with_context(|| { + anyhow!("invalid Delphi version response body: {version}") }) } @@ -154,5 +154,5 @@ pub(crate) async fn scan_outcome<'e>( ) .fetch_optional(exec) .await - .wrap_err("checking whether Delphi scan is terminal") + .context("checking whether Delphi scan is terminal") } diff --git a/apps/labrinth/src/queue/email.rs b/apps/labrinth/src/queue/email.rs index e3c914548aa..95410824cc7 100644 --- a/apps/labrinth/src/queue/email.rs +++ b/apps/labrinth/src/queue/email.rs @@ -158,7 +158,7 @@ impl EmailQueue { .await .to_transport() .await - .wrap_internal_err("creating email transport")?; + .internal_context("creating email transport")?; let begin = std::time::Instant::now(); @@ -168,7 +168,7 @@ impl EmailQueue { &self.pg, ) .await - .wrap_internal_err("creating email transport")?; + .internal_context("creating email transport")?; if deliveries.is_empty() { return Ok(false); @@ -180,7 +180,7 @@ impl EmailQueue { // ballooning the error rate. for d in deliveries.iter_mut().filter(|d| d.attempt_count >= 3) { d.status = NotificationDeliveryStatus::PermanentlyFailed; - d.update(&self.pg).await.wrap_internal_err( + d.update(&self.pg).await.internal_context( "marking exhausted email delivery as failed", )?; } @@ -196,7 +196,7 @@ impl EmailQueue { let notifications = DBNotification::get_many(¬ification_ids, &self.pg) .await - .wrap_internal_err("fetching notifications from database")?; + .internal_context("fetching notifications from database")?; // For all notifications we collected, fill out the template // and send it via SMTP in parallel. @@ -218,12 +218,12 @@ impl EmailQueue { .pg .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let maybe_user = DBUser::get_id(notification.user_id, &mut txn, &this.redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; let Some(user) = maybe_user else { return Ok(( @@ -298,7 +298,7 @@ impl EmailQueue { }; delivery.attempt_count += 1; - delivery.update(&self.pg).await.wrap_internal_err( + delivery.update(&self.pg).await.internal_context( "updating processed email delivery", )?; } @@ -318,7 +318,7 @@ impl EmailQueue { delivery .update(&self.pg) .await - .wrap_internal_err("scheduling email delivery retry")?; + .internal_context("scheduling email delivery retry")?; } info!( @@ -343,7 +343,7 @@ impl EmailQueue { .await .to_transport() .await - .wrap_internal_err("creating email transport")?; + .internal_context("creating email transport")?; self.send_one_with_transport( txn, transport, @@ -371,7 +371,7 @@ impl EmailQueue { &self.redis, ) .await - .wrap_internal_err("creating email transport")? + .internal_context("creating email transport")? .into_iter() .find(|t| t.notification_type == notification.notification_type()) else { return Ok(NotificationDeliveryStatus::SkippedDefault); @@ -388,7 +388,7 @@ impl EmailQueue { address, ) .await - .wrap_api_err("executing `templates::build_email`")?; + .api_context("executing `templates::build_email`")?; let send_result = transport.send(message).await; diff --git a/apps/labrinth/src/queue/email/templates.rs b/apps/labrinth/src/queue/email/templates.rs index 33df0b86723..7f8ff811d67 100644 --- a/apps/labrinth/src/queue/email/templates.rs +++ b/apps/labrinth/src/queue/email/templates.rs @@ -12,6 +12,7 @@ use crate::routes::ApiError; use crate::util::error::ApiContext as _; use crate::util::error::Context; use crate::util::http::HTTP_CLIENT; +use anyhow::anyhow; use ariadne::ids::base62_impl::to_base62; use futures::TryFutureExt; use lettre::Message; @@ -137,7 +138,7 @@ pub async fn build_email( match template .get_cached_html_data(redis) .await - .wrap_internal_err("fetching email template HTML from Redis")? + .internal_context("fetching email template HTML from Redis")? { Some(html_body) => Ok(Ok(html_body)), None => { @@ -153,7 +154,7 @@ pub async fn build_email( template .set_cached_html_data(body.clone(), redis) .await - .wrap_internal_err( + .internal_context( "updating database records for `build_email`", )?; } @@ -174,8 +175,8 @@ pub async fn build_email( let db_user = DBUser::get_id(user_id, &mut *exec, redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_internal_err("finding email recipient in database")?; + .internal_context("fetching user from database")? + .internal_context("finding email recipient in database")?; let map = [ (USER_NAME, db_user.username), @@ -188,14 +189,14 @@ pub async fn build_email( get_html_body, collect_template_variables(exec, redis, user_id, body, map) ) - .wrap_api_err("executing `collect_template_variables`")?; + .api_context("executing `collect_template_variables`")?; let mut message_builder = Message::builder().from(Mailbox::new( Some(from_name), from_address .parse() .map_err(MailError::from) - .wrap_internal_err("reading HTTP response body")?, + .internal_context("reading HTTP response body")?, )); if let Some((name, address)) = reply_name.zip(reply_address) { @@ -204,7 +205,7 @@ pub async fn build_email( address .parse() .map_err(MailError::from) - .wrap_internal_err("reading HTTP response body")?, + .internal_context("reading HTTP response body")?, )); } @@ -259,7 +260,7 @@ pub async fn build_email( } => message_builder .multipart(MultiPart::alternative_plain_html(plaintext, html)) .map_err(MailError::from) - .wrap_internal_err( + .internal_context( "executing `MultiPart::alternative_plain_html`", )?, @@ -269,7 +270,7 @@ pub async fn build_email( } => message_builder .singlepart(SinglePart::plain(plaintext)) .map_err(MailError::from) - .wrap_internal_err("executing `SinglePart::plain`")?, + .internal_context("executing `SinglePart::plain`")?, Body { plaintext: None, @@ -277,13 +278,13 @@ pub async fn build_email( } => message_builder .singlepart(SinglePart::html(html)) .map_err(MailError::from) - .wrap_internal_err("executing `SinglePart::html`")?, + .internal_context("executing `SinglePart::html`")?, Body { plaintext: None, html: None, } => { - return Err(ApiError::Internal(eyre::eyre!( + return Err(ApiError::Internal(anyhow!( "Neither HTML or plaintext could be generated" ))); } @@ -350,7 +351,7 @@ async fn resolve_report_title( let Some(report) = DBReport::get(report_id, &mut *exec) .await - .wrap_internal_err("fetching report from database")? + .internal_context("fetching report from database")? else { return Ok(title); }; @@ -421,8 +422,8 @@ async fn collect_template_variables( redis, ) .await - .wrap_internal_err("fetching email project")? - .wrap_internal_err("finding email project in database")? + .internal_context("fetching email project")? + .internal_context("finding email project in database")? .inner; map.insert(PROJECT_ID, to_base62(project_id.0)); @@ -446,7 +447,7 @@ async fn collect_template_variables( report_id.0 as i64 ) .fetch_one(&mut *exec) - .await.wrap_internal_err("querying database for `collect_template_variables`")?; + .await.internal_context("querying database for `collect_template_variables`")?; map.insert(REPORT_ID, to_base62(report_id.0)); map.insert( @@ -457,7 +458,7 @@ async fn collect_template_variables( result.title, ) .await - .wrap_api_err("executing `resolve_report_title`")?, + .api_context("executing `resolve_report_title`")?, ); map.insert(REPORT_DATE, date_human_readable(result.created)); Ok(EmailTemplate::Static(map)) @@ -477,7 +478,7 @@ async fn collect_template_variables( report_id.0 as i64 ) .fetch_one(&mut *exec) - .await.wrap_internal_err("querying database for `collect_template_variables`")?; + .await.internal_context("querying database for `collect_template_variables`")?; map.insert( REPORT_TITLE, @@ -487,7 +488,7 @@ async fn collect_template_variables( result.title, ) .await - .wrap_api_err("executing `resolve_report_title`")?, + .api_context("executing `resolve_report_title`")?, ); map.insert(NEWREPORT_ID, to_base62(report_id.0)); Ok(EmailTemplate::Static(map)) @@ -502,7 +503,7 @@ async fn collect_template_variables( ) .fetch_one(&mut *exec) .await - .wrap_internal_err( + .internal_context( "querying database for `collect_template_variables`", )?; @@ -523,8 +524,8 @@ async fn collect_template_variables( redis, ) .await - .wrap_internal_err("fetching email project")? - .wrap_internal_err("finding email project in database")? + .internal_context("fetching email project")? + .internal_context("finding email project in database")? .inner; map.insert(PROJECT_ID, to_base62(project_id.0)); @@ -546,8 +547,8 @@ async fn collect_template_variables( redis, ) .await - .wrap_internal_err("fetching email project")? - .wrap_internal_err("finding email project in database")? + .internal_context("fetching email project")? + .internal_context("finding email project in database")? .inner; map.insert(PROJECT_ID, to_base62(project_id.0)); @@ -561,8 +562,8 @@ async fn collect_template_variables( redis, ) .await - .wrap_internal_err("fetching user from database")? - .wrap_internal_err("finding new owner user in database")?; + .internal_context("fetching user from database")? + .internal_context("finding new owner user in database")?; map.insert(NEWOWNER_TYPE, "user".to_string()); map.insert(NEWOWNER_TYPE_CAPITALIZED, "User".to_string()); @@ -576,8 +577,8 @@ async fn collect_template_variables( redis, ) .await - .wrap_internal_err("fetching organization from database")? - .wrap_internal_err( + .internal_context("fetching organization from database")? + .internal_context( "finding new owner organization in database", )?; @@ -615,7 +616,7 @@ async fn collect_template_variables( ) .fetch_one(&mut *exec) .await - .wrap_internal_err( + .internal_context( "querying database for `collect_template_variables`", )?; @@ -650,7 +651,7 @@ async fn collect_template_variables( ) .fetch_one(&mut *exec) .await - .wrap_internal_err( + .internal_context( "querying database for `collect_template_variables`", )?; @@ -681,7 +682,7 @@ async fn collect_template_variables( ) .fetch_one(&mut *exec) .await - .wrap_internal_err( + .internal_context( "querying database for `collect_template_variables`", )?; @@ -870,7 +871,7 @@ async fn collect_template_variables( variables: map, body: dynamic_email_body(redis, title, body_md, key) .await - .wrap_api_err("executing `dynamic_email_body`")?, + .api_context("executing `dynamic_email_body`")?, title: title.to_string(), }), @@ -886,8 +887,8 @@ async fn collect_template_variables( redis, ) .await - .wrap_internal_err("fetching user from database")? - .wrap_internal_err("finding server invite sender in database")?; + .internal_context("fetching user from database")? + .internal_context("finding server invite sender in database")?; map.insert(SERVERINVITE_INVITER_NAME, inviter.username); map.insert(SERVERINVITE_SERVER_NAME, server_name.clone()); @@ -927,13 +928,13 @@ async fn dynamic_email_body( .send() .await .and_then(|res| res.error_for_status()) - .wrap_internal_err("deserializing HTTP response")? + .internal_context("deserializing HTTP response")? .bytes() .await - .wrap_internal_err("deserializing HTTP response")? + .internal_context("deserializing HTTP response")? .as_ref(), ) - .wrap_internal_err("email body is not valid UTF-8") + .internal_context("email body is not valid UTF-8") .map(ToOwned::to_owned) }) .await diff --git a/apps/labrinth/src/queue/file_scan.rs b/apps/labrinth/src/queue/file_scan.rs index 3a58d491d64..12f63117707 100644 --- a/apps/labrinth/src/queue/file_scan.rs +++ b/apps/labrinth/src/queue/file_scan.rs @@ -3,8 +3,8 @@ use std::io::{Cursor, Read}; use std::sync::Arc; use xredis::RedisPool; +use anyhow::{Result, anyhow}; use chrono::Utc; -use eyre::{Result, eyre}; use hex::ToHex; use serde::Serialize; use sha1::Digest; @@ -82,7 +82,7 @@ pub async fn scan_all_pending_files( ) .fetch_one(db) .await - .wrap_err("fetching number of files to scan")?; + .context("fetching number of files to scan")?; info!( "Found {total_to_scan} total pending files to scan, running in batches of {PENDING_FILE_SCAN_BATCH_SIZE} with concurrency {scan_concurrency}" @@ -129,7 +129,7 @@ async fn scan_pending_files_batch( ) .fetch_all(db) .await - .wrap_err("fetching files to scan")?; + .context("fetching files to scan")?; let fetched_count = files_to_scan.len(); @@ -161,7 +161,7 @@ async fn scan_pending_files_batch( let mut scanned_count = 0; let mut errors = Vec::new(); for task in tasks { - match task.await.wrap_err("joining file scan task")? { + match task.await.context("joining file scan task")? { Ok(count) => scanned_count += count, Err(err) => { errors.push(err); @@ -178,13 +178,13 @@ async fn scan_pending_files_batch( .collect::>() .join("\n\n"); - return Err(eyre!( + return Err(anyhow!( "failed to scan {error_count} pending file chunks:\n\n{error_messages}" )); } if fetched_count > 0 && scanned_count == 0 { - return Err(eyre!( + return Err(anyhow!( "file scan batch made no progress after fetching {fetched_count} files" )); } @@ -215,8 +215,8 @@ async fn scan_pending_files_chunk( file_host, file_id, &row.url, ) .await - .wrap_err_with(|| { - eyre!("extracting overrides for file {file_id:?}") + .with_context(|| { + anyhow!("extracting overrides for file {file_id:?}") })?; if overrides.is_empty() { @@ -230,13 +230,12 @@ async fn scan_pending_files_chunk( let mut txn = db .begin() .await - .wrap_err("beginning file scan transaction")?; + .context("beginning file scan transaction")?; - let resolved = resolve_overrides(&overrides, &mut txn) - .await - .wrap_err_with(|| { - eyre!("resolving overrides for file {file_id:?}") - })?; + let resolved = + resolve_overrides(&overrides, &mut txn).await.with_context( + || anyhow!("resolving overrides for file {file_id:?}"), + )?; info!("Resolved: {resolved:#?}"); persist_attribution_results( @@ -248,16 +247,16 @@ async fn scan_pending_files_chunk( &mut txn, ) .await - .wrap_err_with(|| { - eyre!("persisting attribution results for file {file_id:?}") + .with_context(|| { + anyhow!("persisting attribution results for file {file_id:?}") })?; txn.commit() .await - .wrap_err("committing file scan transaction")?; + .context("committing file scan transaction")?; log_marked_override_projects(&resolved); - eyre::Ok(()) + anyhow::Ok(()) } .instrument(span) .await; @@ -274,7 +273,7 @@ async fn scan_pending_files_chunk( update_file_scan_result(db, file_id, scan_result) .await - .wrap_err("marking file as scanned")?; + .context("marking file as scanned")?; scanned_count += 1; } @@ -296,7 +295,7 @@ pub async fn scan_file( upsert_file_scan_result(txn, file_id, file_scan_result(&result)) .await - .wrap_err("marking file as scanned")?; + .context("marking file as scanned")?; result } @@ -312,8 +311,8 @@ async fn scan_file_inner( let overrides = extract_override_files_from_storage(file_host, file_id, file_url) .await - .wrap_err_with(|| { - eyre!("extracting overrides for file {file_id:?}") + .with_context(|| { + anyhow!("extracting overrides for file {file_id:?}") })?; let scanned_file_names = @@ -327,16 +326,16 @@ async fn scan_file_inner( let before = count_project_attributions(project_id, txn).await?; let resolved = - resolve_overrides(&overrides, txn).await.wrap_err_with(|| { - eyre!("resolving overrides for file {file_id:?}") + resolve_overrides(&overrides, txn).await.with_context(|| { + anyhow!("resolving overrides for file {file_id:?}") })?; persist_attribution_results( project_id, file_id, &overrides, &resolved, redis, txn, ) .await - .wrap_err_with(|| { - eyre!("persisting attribution results for file {file_id:?}") + .with_context(|| { + anyhow!("persisting attribution results for file {file_id:?}") })?; let after = count_project_attributions(project_id, txn).await?; @@ -379,7 +378,7 @@ async fn count_project_attributions( ) .fetch_one(&mut *txn) .await - .wrap_err("counting project attributions")?; + .context("counting project attributions")?; Ok(ProjectAttributionCounts { groups: row.groups as u64, @@ -419,7 +418,7 @@ async fn update_file_scan_result( ) .execute(db) .await - .wrap_err("updating file scan result")?; + .context("updating file scan result")?; Ok(()) } @@ -446,7 +445,7 @@ async fn upsert_file_scan_result( ) .execute(&mut *txn) .await - .wrap_err("upserting file scan result")?; + .context("upserting file scan result")?; Ok(()) } @@ -458,7 +457,7 @@ pub async fn scan_override_files( ) -> Result> { extract_override_files_from_storage(file_host, file_id, file_url) .await - .wrap_err_with(|| eyre!("extracting overrides for file {file_id:?}")) + .with_context(|| anyhow!("extracting overrides for file {file_id:?}")) } async fn extract_override_files_from_storage( @@ -470,19 +469,19 @@ async fn extract_override_files_from_storage( .strip_prefix(&ENV.CDN_URL) .unwrap_or(file_url) .trim_start_matches('/'); - let key = urlencoding::decode(key).wrap_err("decoding file URL path")?; + let key = urlencoding::decode(key).context("decoding file URL path")?; let file_data = file_host .read_file(&key, FileHostPublicity::Public) .await - .wrap_err_with(|| { - eyre!("reading file {file_id:?} from storage at {key}") + .with_context(|| { + anyhow!("reading file {file_id:?} from storage at {key}") })?; spawn_blocking(move || extract_override_files(&file_data)) .await - .wrap_err("extracting override files")? - .wrap_err("extracting override files") + .context("extracting override files")? + .context("extracting override files") } #[derive(Debug)] @@ -583,17 +582,17 @@ fn should_scan(name: &str) -> bool { fn extract_override_files(data: &[u8]) -> Result> { let reader = Cursor::new(data); let mut zip = - ZipArchive::new(reader).wrap_err("creating zip archive reader")?; + ZipArchive::new(reader).context("creating zip archive reader")?; let mut files = Vec::new(); for i in 0..zip.len() { let mut file = zip .by_index(i) - .wrap_err_with(|| eyre!("reading file {i}"))?; + .with_context(|| anyhow!("reading file {i}"))?; let name = file .name() - .wrap_err_with(|| eyre!("decoding filename for file {i}"))? + .with_context(|| anyhow!("decoding filename for file {i}"))? .into_owned(); if file.is_dir() { @@ -648,7 +647,7 @@ async fn persist_attribution_results( ) .fetch_all(&mut *txn) .await - .wrap_err("checking existing attribution files")?; + .context("checking existing attribution files")?; let mut flame_groups: HashMap< u32, @@ -709,7 +708,7 @@ async fn persist_attribution_results( ) .fetch_all(&mut *txn) .await - .wrap_err("fetching existing flame attribution groups")?; + .context("fetching existing flame attribution groups")?; let mut existing_flame_group_ids = HashMap::new(); for group in existing_flame_groups { @@ -742,7 +741,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting external license attribution file into existing flame group")?; + .context("inserting external license attribution file into existing flame group")?; continue; } @@ -763,7 +762,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting external license attribution group")?; + .context("inserting external license attribution group")?; sqlx::query!( r#" @@ -779,7 +778,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting external license attribution file")?; + .context("inserting external license attribution file")?; } for (flame_project_id, (files, resolution)) in &flame_groups { @@ -810,7 +809,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting attribution group")?; + .context("inserting attribution group")?; existing_flame_group_ids.insert(*flame_project_id, id); id }; @@ -831,7 +830,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting attribution files")?; + .context("inserting attribution files")?; } for file in &unknown_files { @@ -846,7 +845,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting unknown attribution group")?; + .context("inserting unknown attribution group")?; sqlx::query!( r#" @@ -860,7 +859,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting unknown attribution file")?; + .context("inserting unknown attribution file")?; } if !all_sha1s.is_empty() { @@ -880,7 +879,7 @@ async fn persist_attribution_results( ) .execute(&mut *txn) .await - .wrap_err("inserting override file sources")?; + .context("inserting override file sources")?; } let version_id = sqlx::query_scalar!( @@ -893,11 +892,11 @@ async fn persist_attribution_results( ) .fetch_one(&mut *txn) .await - .wrap_err("fetching scanned file version")?; + .context("fetching scanned file version")?; DBVersion::clear_cache_ids(&[version_id], redis) .await - .wrap_err("clearing version cache after attribution scan")?; + .context("clearing version cache after attribution scan")?; Ok(()) } @@ -965,7 +964,7 @@ async fn resolve_overrides( ) .fetch_all(&mut *txn) .await - .wrap_err("fetching external file licenses")?; + .context("fetching external file licenses")?; let mut direct_external_licenses = HashMap::new(); for row in rows { @@ -1000,7 +999,7 @@ async fn resolve_overrides( let body = res .text() .await - .wrap_err("reading Flame fingerprint response")?; + .context("reading Flame fingerprint response")?; let flame_files: Vec<_> = serde_json::from_str::>(&body) @@ -1036,7 +1035,7 @@ async fn resolve_overrides( ) .fetch_all(&mut *txn) .await - .wrap_err("fetching Flame project licenses")?; + .context("fetching Flame project licenses")?; let mut project_external_licenses = HashMap::new(); for row in project_license_rows { @@ -1161,7 +1160,7 @@ async fn resolve_overrides( DBUserId(0), ) .await - .wrap_err("inserting external license files")?; + .context("inserting external license files")?; } } @@ -1276,7 +1275,7 @@ where ) .fetch_all(exec) .await - .wrap_err("fetching files missing attribution")?; + .context("fetching files missing attribution")?; let mut result = std::collections::HashMap::new(); for row in rows { @@ -1337,7 +1336,7 @@ where ) .fetch_all(exec) .await - .wrap_err("fetching dependency attributions")?; + .context("fetching dependency attributions")?; let mut result = HashMap::new(); for row in rows { diff --git a/apps/labrinth/src/queue/moderation/project_flag.rs b/apps/labrinth/src/queue/moderation/project_flag.rs index 96684baa2d1..ff8a085356c 100644 --- a/apps/labrinth/src/queue/moderation/project_flag.rs +++ b/apps/labrinth/src/queue/moderation/project_flag.rs @@ -5,7 +5,7 @@ use std::{ time::Duration, }; -use eyre::{Result, eyre}; +use anyhow::{Result, anyhow}; use regex::Regex; use xredis::RedisPool; @@ -244,7 +244,7 @@ impl ProjectFlagEngine { let ast = self .rhai .compile(¶ms.expression) - .wrap_err("compiling script")?; + .context("compiling script")?; Ok(ProjectRuleCall { ast, scan_files_for: params.scan_files_for.clone(), @@ -261,19 +261,19 @@ impl ProjectFlagEngine { let projects = DBProject::get_many_ids(project_ids, &*self.ro_pool, &self.redis) .await - .wrap_err("fetching projects for flag evaluation")?; + .context("fetching projects for flag evaluation")?; let ids = project_ids.iter().map(|id| id.0).collect::>(); let version_ids = sqlx::query_scalar!( r#"SELECT id FROM versions WHERE mod_id = ANY($1) ORDER BY date_published DESC, id DESC"#, &ids, ).fetch_all(&*self.ro_pool).await - .wrap_err("fetching version IDs for flag evaluation")? + .context("fetching version IDs for flag evaluation")? .into_iter().map(DBVersionId).collect::>(); let mut versions = HashMap::<_, Vec>::new(); for version in DBVersion::get_many(&version_ids, &*self.ro_pool, &self.redis) .await - .wrap_err("fetching versions for flag evaluation")? + .context("fetching versions for flag evaluation")? { versions .entry(version.inner.project_id) @@ -294,7 +294,7 @@ impl ProjectFlagEngine { &*self.ro_pool, ) .await - .wrap_err("fetching disclosures for flag evaluation")? + .context("fetching disclosures for flag evaluation")? { disclosures .entry(disclosure.project_id) @@ -309,7 +309,7 @@ impl ProjectFlagEngine { .collect::>(); let mut threads = DBThread::get_many(&thread_ids, &*self.ro_pool) .await - .wrap_err("fetching moderation threads for flag evaluation")? + .context("fetching moderation threads for flag evaluation")? .into_iter() .map(|thread| (thread.id, thread)) .collect::>(); @@ -325,7 +325,7 @@ impl ProjectFlagEngine { &self.redis, ) .await - .wrap_err("fetching organizations for flag evaluation")? + .context("fetching organizations for flag evaluation")? .into_iter() .map(|organization| (organization.id, organization)) .collect::>(); @@ -342,7 +342,7 @@ impl ProjectFlagEngine { &self.redis, ) .await - .wrap_err("fetching team members for flag evaluation")?; + .context("fetching team members for flag evaluation")?; let mut user_ids = members.iter().map(|m| m.user_id).collect::>(); user_ids.sort_unstable_by_key(|id| id.0); @@ -350,7 +350,7 @@ impl ProjectFlagEngine { let users = DBUser::get_many_ids(&user_ids, &*self.ro_pool, &self.redis) .await - .wrap_err("fetching team users for flag evaluation")? + .context("fetching team users for flag evaluation")? .into_iter() .map(|user| (user.id, User::from(user))) .collect::>(); @@ -359,7 +359,7 @@ impl ProjectFlagEngine { let user = users .get(&member.user_id) .cloned() - .ok_or_else(|| eyre!("team member user not found"))?; + .ok_or_else(|| anyhow!("team member user not found"))?; teams .entry(member.team_id) .or_default() @@ -376,18 +376,19 @@ impl ProjectFlagEngine { .map(|id| { let organization = organizations.get(&id).cloned().ok_or_else(|| { - eyre!("project organization not found") + anyhow!("project organization not found") })?; let members = teams .get(&organization.team_id) .cloned() .unwrap_or_default(); - eyre::Ok(Organization::from(organization, members)) + anyhow::Ok(Organization::from(organization, members)) }) .transpose()?; - let thread = threads - .remove(&project.thread_id) - .ok_or_else(|| eyre!("project moderation thread not found"))?; + let thread = + threads.remove(&project.thread_id).ok_or_else(|| { + anyhow!("project moderation thread not found") + })?; let moderation_thread = FlagModerationThread { id: thread.id.into(), messages: thread @@ -478,12 +479,14 @@ impl ProjectFlagEngine { if let Some(error) = scan_error && !call.scan_files_for.is_empty() { - return Err(eyre!("project file scan failed: {error}")); + return Err(anyhow!("project file scan failed: {error}")); } let context = rhai::serde::to_dynamic(context) - .wrap_err("serializing flag context for script")? + .context("serializing flag context for script")? .try_cast::() - .ok_or_else(|| eyre!("flag context must serialize to a map"))?; + .ok_or_else(|| { + anyhow!("flag context must serialize to a map") + })?; let mut scope = rhai::Scope::new(); for (name, value) in context { if scan_error.is_some() && name == "scanned_files" { @@ -494,9 +497,9 @@ impl ProjectFlagEngine { let output = self .rhai .eval_ast_with_scope::(&mut scope, &call.ast) - .wrap_err("running script"); + .context("running script"); let output = match scan_error { - Some(error) => output.wrap_err_with(|| { + Some(error) => output.with_context(|| { format!("file scan unavailable for script: {error}") }), None => output, @@ -506,9 +509,9 @@ impl ProjectFlagEngine { .map(|value| { let value = rhai::serde::from_dynamic::(&value) - .wrap_err("converting project flag to json")?; + .context("converting project flag to json")?; serde_json::from_value::(value) - .wrap_err("decoding project flag") + .context("decoding project flag") }) .collect::>>() })(); @@ -527,7 +530,7 @@ impl ProjectFlagEngine { .load_contexts(&[project_id]) .await? .remove(&project_id) - .ok_or_else(|| eyre!("project not found"))?; + .ok_or_else(|| anyhow!("project not found"))?; let files = self .load_files(&[project_id]) .await? @@ -555,11 +558,11 @@ impl ProjectFlagEngine { Ok(ProjectFlagEvaluation { flags: flags?, log }) }) .await - .wrap_err("joining project flag evaluation")? + .context("joining project flag evaluation")? }, ) .await - .wrap_err("project flag rule evaluation timed out")? + .context("project flag rule evaluation timed out")? } pub async fn scan_flags( diff --git a/apps/labrinth/src/queue/moderation/project_flag_attribution.rs b/apps/labrinth/src/queue/moderation/project_flag_attribution.rs index 1fe2aeebda1..71246b2bd53 100644 --- a/apps/labrinth/src/queue/moderation/project_flag_attribution.rs +++ b/apps/labrinth/src/queue/moderation/project_flag_attribution.rs @@ -1,8 +1,8 @@ use std::collections::{HashMap, HashSet}; +use anyhow::{Context, Result}; use ariadne::ids::UserId; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use serde::Serialize; use utoipa::ToSchema; @@ -93,7 +93,7 @@ pub(super) async fn load_attributions( ) .fetch_all(&**pool) .await - .wrap_err("fetching attribution groups for flag evaluation")?; + .context("fetching attribution groups for flag evaluation")?; if groups.is_empty() { return Ok(result); } @@ -118,7 +118,7 @@ pub(super) async fn load_attributions( ) .fetch_all(&**pool) .await - .wrap_err("fetching attribution files for flag evaluation")?; + .context("fetching attribution files for flag evaluation")?; let mut license_ids: Vec<_> = files .iter() @@ -139,7 +139,7 @@ pub(super) async fn load_attributions( ) .fetch_all(&**pool) .await - .wrap_err( + .context( "fetching attribution external licenses for flag evaluation", )?; for row in rows { @@ -182,7 +182,7 @@ pub(super) async fn load_attributions( ) .fetch_all(&**pool) .await - .wrap_err("fetching attribution versions for flag evaluation")?; + .context("fetching attribution versions for flag evaluation")?; versions.extend(rows.into_iter().map(|row| FlagAttributionVersion { id: VersionId(row.id as u64), name: row.name, @@ -239,7 +239,7 @@ pub(super) async fn load_attributions( ) .fetch_all(&**pool) .await - .wrap_err("fetching attribution override files on platform for flag evaluation")?; + .context("fetching attribution override files on platform for flag evaluation")?; let mut platform_files_by_project: HashMap<_, Vec<_>> = HashMap::new(); for row in platform_files { platform_files_by_project @@ -273,14 +273,14 @@ pub(super) async fn load_attributions( .attribution .map(serde_json::from_value::) .transpose() - .wrap_err( + .context( "deserializing attribution resolution for flag evaluation", )?; let flame_project = group .flame_project .map(serde_json::from_value::) .transpose() - .wrap_err("deserializing attribution source for flag evaluation")?; + .context("deserializing attribution source for flag evaluation")?; result .entry(DBProjectId(group.project_id)) .or_default() diff --git a/apps/labrinth/src/queue/moderation/project_flag_files.rs b/apps/labrinth/src/queue/moderation/project_flag_files.rs index e342510576b..efaeeaebbe6 100644 --- a/apps/labrinth/src/queue/moderation/project_flag_files.rs +++ b/apps/labrinth/src/queue/moderation/project_flag_files.rs @@ -2,7 +2,7 @@ use std::collections::{BTreeMap, HashMap}; use std::io::{Cursor, Read}; use std::sync::Arc; -use eyre::{Context, Result, ensure, eyre}; +use anyhow::{Context, Result, anyhow, ensure}; use regex::Regex; use sha2::{Digest, Sha256}; @@ -29,7 +29,7 @@ struct Budget { impl Budget { fn consume(&mut self, bytes: u64) -> Result<()> { - (bytes <= ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - self.bytes).then_some(()).ok_or_else(|| eyre!("project file scan exceeds total byte budget")).wrap_err_with(|| eyre!("requested {bytes} bytes, remaining {} bytes, maximum {} bytes", ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - self.bytes, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES))?; + (bytes <= ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - self.bytes).then_some(()).ok_or_else(|| anyhow!("project file scan exceeds total byte budget")).with_context(|| anyhow!("requested {bytes} bytes, remaining {} bytes, maximum {} bytes", ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - self.bytes, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES))?; self.bytes += bytes; Ok(()) } @@ -68,7 +68,7 @@ pub(super) async fn load_project_files( ) .fetch_all(&**ro_pool) .await - .wrap_err("fetching project files for content scanning")?; + .context("fetching project files for content scanning")?; for row in rows { files.entry(DBProjectId(row.project_id)).or_default().push( @@ -98,27 +98,27 @@ pub(super) async fn scan_project_files( && file.size as u64 <= ENV.PROJECT_FLAG_SCAN_MAX_ARTIFACT_BYTES) .then_some(()) .ok_or_else(|| { - eyre!( + anyhow!( "file {} exceeds declared artifact size budget", file.file_id.0 ) }) - .wrap_err_with(|| { - eyre!( + .with_context(|| { + anyhow!( "declared size {} bytes, maximum {} bytes", file.size, ENV.PROJECT_FLAG_SCAN_MAX_ARTIFACT_BYTES ) })?; (file.size as u64 - <= ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes).then_some(()).ok_or_else(|| eyre!("file {} exceeds remaining declared byte budget", - file.file_id.0)).wrap_err_with(|| eyre!("declared size {} bytes, remaining {} bytes, maximum {} bytes", file.size, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES))?; + <= ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes).then_some(()).ok_or_else(|| anyhow!("file {} exceeds remaining declared byte budget", + file.file_id.0)).with_context(|| anyhow!("declared size {} bytes, remaining {} bytes, maximum {} bytes", file.size, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES))?; let cdn_prefix = format!("{}/", ENV.CDN_URL.trim_end_matches('/')); let key = file.url.strip_prefix(&cdn_prefix).ok_or_else(|| { - eyre::eyre!("project file url is outside the configured cdn") + anyhow!("project file url is outside the configured cdn") })?; let key = urlencoding::decode(key) - .wrap_err("decoding project file storage key")?; + .context("decoding project file storage key")?; ensure!( !key.is_empty() && !key.contains('\\') @@ -128,19 +128,19 @@ pub(super) async fn scan_project_files( let permit = Arc::clone(downloads) .acquire_owned() .await - .wrap_err("acquiring project file download permit")?; + .context("acquiring project file download permit")?; let data = file_host .read_file(&key, FileHostPublicity::Public) .await - .wrap_err_with(|| { + .with_context(|| { format!("reading project file {} from storage", file.file_id.0) })?; (data.len() as u64 <= ENV.PROJECT_FLAG_SCAN_MAX_ARTIFACT_BYTES) .then_some(()) - .ok_or_else(|| eyre!("project file exceeds artifact size budget")) - .wrap_err_with(|| { - eyre!( + .ok_or_else(|| anyhow!("project file exceeds artifact size budget")) + .with_context(|| { + anyhow!( "actual size {} bytes, maximum {} bytes", data.len(), ENV.PROJECT_FLAG_SCAN_MAX_ARTIFACT_BYTES @@ -161,10 +161,10 @@ pub(super) async fn scan_project_files( &mut budget, &mut leaves, )?; - eyre::Ok((leaves, budget)) + anyhow::Ok((leaves, budget)) }) .await - .wrap_err("joining project file content scan")??; + .context("joining project file content scan")??; budget = next_budget; scanned_files.extend(artifact_leaves.into_iter().map( |(file_path, sha256, found_patterns)| ScannedFile { @@ -217,26 +217,26 @@ fn scan_contents( (depth < ENV.PROJECT_FLAG_SCAN_MAX_DEPTH) .then_some(()) .ok_or_else(|| { - eyre!("archive nesting depth budget exceeded at {path}") + anyhow!("archive nesting depth budget exceeded at {path}") }) - .wrap_err_with(|| { - eyre!( + .with_context(|| { + anyhow!( "attempted archive layer {}, maximum {} layers", depth + 1, ENV.PROJECT_FLAG_SCAN_MAX_DEPTH ) })?; let mut archive = ZipArchive::new(Cursor::new(data)) - .wrap_err_with(|| format!("opening archive {path}"))?; - (archive.len() <= ENV.PROJECT_FLAG_SCAN_MAX_ENTRIES - budget.entries).then_some(()).ok_or_else(|| eyre!("archive entry budget exceeded at {path}")).wrap_err_with(|| eyre!("archive contains {} entries, remaining {} entries, maximum {} entries", archive.len(), ENV.PROJECT_FLAG_SCAN_MAX_ENTRIES - budget.entries, ENV.PROJECT_FLAG_SCAN_MAX_ENTRIES))?; + .with_context(|| format!("opening archive {path}"))?; + (archive.len() <= ENV.PROJECT_FLAG_SCAN_MAX_ENTRIES - budget.entries).then_some(()).ok_or_else(|| anyhow!("archive entry budget exceeded at {path}")).with_context(|| anyhow!("archive contains {} entries, remaining {} entries, maximum {} entries", archive.len(), ENV.PROJECT_FLAG_SCAN_MAX_ENTRIES - budget.entries, ENV.PROJECT_FLAG_SCAN_MAX_ENTRIES))?; budget.entries += archive.len(); for index in 0..archive.len() { let mut entry = archive .by_index(index) - .wrap_err_with(|| format!("opening entry {index} in {path}"))?; + .with_context(|| format!("opening entry {index} in {path}"))?; let entry_path = format!( "{path}!/{}", - entry.name().wrap_err("decoding archive entry name")? + entry.name().context("decoding archive entry name")? ); if entry.is_dir() { continue; @@ -247,7 +247,7 @@ fn scan_contents( let remaining = PREFIX_BYTES - contents.len(); let count = entry .read(&mut prefix[..remaining]) - .wrap_err("reading archive entry prefix")?; + .context("reading archive entry prefix")?; if count == 0 { break; } @@ -266,24 +266,26 @@ fn scan_contents( (entry.size() <= limit) .then_some(()) .ok_or_else(|| { - eyre!("archive entry size budget exceeded at {entry_path}") + anyhow!( + "archive entry size budget exceeded at {entry_path}" + ) }) - .wrap_err_with(|| { - eyre!( + .with_context(|| { + anyhow!( "declared size {} bytes, maximum {limit} bytes", entry.size() ) })?; (entry.size().saturating_sub(contents.len() as u64) - <= ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes).then_some(()).ok_or_else(|| eyre!("remaining byte budget exceeded at {entry_path}")).wrap_err_with(|| eyre!("requested {} bytes, remaining {} bytes, maximum {} bytes", entry.size().saturating_sub(contents.len() as u64), ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES))?; + <= ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes).then_some(()).ok_or_else(|| anyhow!("remaining byte budget exceeded at {entry_path}")).with_context(|| anyhow!("requested {} bytes, remaining {} bytes, maximum {} bytes", entry.size().saturating_sub(contents.len() as u64), ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES - budget.bytes, ENV.PROJECT_FLAG_SCAN_MAX_TOTAL_BYTES))?; loop { let count = entry .read(&mut prefix) - .wrap_err("reading archive entry contents")?; + .context("reading archive entry contents")?; if count == 0 { break; } - (contents.len() as u64 + count as u64 <= limit).then_some(()).ok_or_else(|| eyre!("archive entry size budget exceeded at {entry_path}")).wrap_err_with(|| eyre!("actual size at least {} bytes, maximum {limit} bytes", contents.len() as u64 + count as u64))?; + (contents.len() as u64 + count as u64 <= limit).then_some(()).ok_or_else(|| anyhow!("archive entry size budget exceeded at {entry_path}")).with_context(|| anyhow!("actual size at least {} bytes, maximum {limit} bytes", contents.len() as u64 + count as u64))?; budget.consume(count as u64)?; contents.extend_from_slice(&prefix[..count]); } @@ -299,9 +301,9 @@ fn scan_contents( } else if is_text_prefix(&data[..data.len().min(PREFIX_BYTES)]) { (data.len() as u64 <= ENV.PROJECT_FLAG_SCAN_MAX_TEXT_BYTES) .then_some(()) - .ok_or_else(|| eyre!("text size budget exceeded at {path}")) - .wrap_err_with(|| { - eyre!( + .ok_or_else(|| anyhow!("text size budget exceeded at {path}")) + .with_context(|| { + anyhow!( "actual size {} bytes, maximum {} bytes", data.len(), ENV.PROJECT_FLAG_SCAN_MAX_TEXT_BYTES diff --git a/apps/labrinth/src/queue/moderation/project_flag_run.rs b/apps/labrinth/src/queue/moderation/project_flag_run.rs index 1b16d67fa03..d18fac8854d 100644 --- a/apps/labrinth/src/queue/moderation/project_flag_run.rs +++ b/apps/labrinth/src/queue/moderation/project_flag_run.rs @@ -5,7 +5,7 @@ use std::{ }; use super::project_flag::{ProjectFlagEngine, ProjectRuleCall}; -use eyre::{Result, WrapErr, eyre}; +use anyhow::{Context, Result, anyhow}; use futures::{StreamExt, TryStreamExt, stream}; use rdkafka::{ Message, Offset, TopicPartitionList, @@ -54,11 +54,11 @@ pub async fn consume_project_flag_runs( .set("isolation.level", "read_committed") .set("enable.auto.offset.store", "false") .create() - .wrap_err("creating project flag run Kafka consumer")?; + .context("creating project flag run Kafka consumer")?; let consumer = Arc::new(consumer); consumer .subscribe(&[PROJECT_FLAG_RUN_TOPIC]) - .wrap_err("subscribing to project flag run Kafka topic")?; + .context("subscribing to project flag run Kafka topic")?; tracing::warn!( topic = PROJECT_FLAG_RUN_TOPIC, @@ -71,13 +71,15 @@ pub async fn consume_project_flag_runs( loop { messages.clear(); let result = async { - messages.push(consumer.recv().await.wrap_err( - "receiving initial project flag run Kafka message", - )?); + messages.push( + consumer.recv().await.context( + "receiving initial project flag run Kafka message", + )?, + ); let deadline = tokio::time::Instant::now() + SCAN_BATCH_DELAY; while messages.len() < batch_size { match tokio::time::timeout_at(deadline, consumer.recv()).await { - Ok(message) => messages.push(message.wrap_err( + Ok(message) => messages.push(message.context( "receiving project flag run Kafka batch message", )?), Err(_) => break, @@ -88,10 +90,10 @@ pub async fn consume_project_flag_runs( .iter() .map(|message| { let payload = message.payload().ok_or_else(|| { - eyre!("project flag run Kafka message has no payload") + anyhow!("project flag run Kafka message has no payload") })?; serde_json::from_slice::(payload) - .wrap_err("decoding project flag run Kafka message") + .context("decoding project flag run Kafka message") }) .collect::>>()?; @@ -113,16 +115,16 @@ pub async fn consume_project_flag_runs( partition, Offset::Offset(offset), ) - .wrap_err("building project flag run consumer offsets")?; + .context("building project flag run consumer offsets")?; } let consumer = consumer.clone(); tokio::task::spawn_blocking(move || { consumer.commit(&positions, CommitMode::Sync) }) .await - .wrap_err("joining project flag run offset commit")? - .wrap_err("committing project flag run consumer offsets")?; - eyre::Ok(()) + .context("joining project flag run offset commit")? + .context("committing project flag run consumer offsets")?; + anyhow::Ok(()) } .await; if let Err(error) = result { @@ -154,7 +156,7 @@ async fn scan_batch( let mut connection = redis .connect() .await - .wrap_err("connecting to Redis for project flag rule snapshots")?; + .context("connecting to Redis for project flag rule snapshots")?; for run_id in events.iter().map(|event| event.run_id) { if snapshots.contains_key(&run_id) { continue; @@ -162,7 +164,7 @@ async fn scan_batch( let Some(id) = run_id else { let rules = DBProjectFlagRule::all(pool) .await - .wrap_err("loading rules for standalone project scans")?; + .context("loading rules for standalone project scans")?; snapshots.insert(None, Ok(rules)); continue; }; @@ -171,7 +173,7 @@ async fn scan_batch( .arg(key) .query_async(&mut connection) .await - .wrap_err("fetching project flag rule snapshot")?; + .context("fetching project flag rule snapshot")?; let rules = snapshot .ok_or_else(|| format!("rule snapshot missing for run {}", id.0)) .and_then(|snapshot| { @@ -198,7 +200,7 @@ async fn scan_batch( Ok(rules) => rules, Err(error) => { prepared.error = Some(error); - return eyre::Ok((run_id, prepared)); + return anyhow::Ok((run_id, prepared)); } }; for rule in rules { @@ -220,12 +222,12 @@ async fn scan_batch( pattern_names, }); } - eyre::Ok((run_id, prepared)) + anyhow::Ok((run_id, prepared)) }) .collect::>>() }) .await - .wrap_err("joining project flag rule compilation")??; + .context("joining project flag rule compilation")??; let runs = Arc::new(runs); let project_ids = events .iter() @@ -261,7 +263,7 @@ async fn scan_batch( let context = contexts .get(&project_id) .ok_or_else(|| { - eyre!( + anyhow!( "project context missing for {}", event.project_id ) @@ -269,9 +271,9 @@ async fn scan_batch( .clone(); let run = runs .get(&event.run_id) - .ok_or_else(|| eyre!("project scan rules not found"))?; + .ok_or_else(|| anyhow!("project scan rules not found"))?; if let Some(error) = &run.error { - return Err(eyre!(error.clone())); + return Err(anyhow!(error.clone())); } let files = files .get(&project_id) @@ -280,7 +282,7 @@ async fn scan_batch( let scanned_context = engine .prepare_context(context.clone(), files, &run.patterns) .await - .wrap_err_with(|| { + .with_context(|| { format!( "preparing project {} for flag scanning", event.project_id @@ -290,7 +292,7 @@ async fn scan_batch( Ok(context) => (context, None), Err(error) => (context, Some(format!("{error:#}"))), }; - eyre::Ok((context, scan_error)) + anyhow::Ok((context, scan_error)) } .await; (event, prepared) @@ -338,7 +340,7 @@ async fn scan_batch( &context, scan_error.as_deref(), ), - Err(error) => (Err(eyre!(error.clone())), Vec::new()), + Err(error) => (Err(anyhow!(error.clone())), Vec::new()), }; let (flags, error) = match evaluation { Ok(flags) => (flags, None), @@ -360,7 +362,7 @@ async fn scan_batch( .collect::>(); let mut results = Vec::new(); for result in futures::future::join_all(tasks).await { - results.push(result.wrap_err("joining project flag batch evaluation")?); + results.push(result.context("joining project flag batch evaluation")?); } let result_count = results.len(); DBProjectFlagRunResult::upsert_many(results, &consumed_jobs, pool).await?; @@ -392,12 +394,12 @@ pub async fn dispatch_project_flag_run( kafka: &KafkaClientState, ) -> Result<()> { let snapshot = serde_json::to_vec(&rules) - .wrap_err("serializing project flag run rules")?; + .context("serializing project flag run rules")?; tokio::time::timeout(KAFKA_DELIVERY_TIMEOUT, async { let mut connection = redis .connect() .await - .wrap_err("connecting to Redis for project flag run")?; + .context("connecting to Redis for project flag run")?; let key = connection .key() .entity("project_flag_run_rules:v1", run_id.0); @@ -407,12 +409,12 @@ pub async fn dispatch_project_flag_run( .arg("NX") .query_async::>(&mut connection) .await - .wrap_err("storing project flag run rules")? - .ok_or_else(|| eyre!("project flag run rules already exist"))?; - eyre::Ok(()) + .context("storing project flag run rules")? + .ok_or_else(|| anyhow!("project flag run rules already exist"))?; + anyhow::Ok(()) }) .await - .wrap_err("timed out storing project flag run rules")??; + .context("timed out storing project flag run rules")??; if project_ids.is_empty() { return Ok(()); @@ -431,7 +433,7 @@ pub async fn dispatch_project_flag_run( let result = (|| { producer .begin_transaction() - .wrap_err("beginning project flag run Kafka transaction")?; + .context("beginning project flag run Kafka transaction")?; runtime.block_on(async { tokio::time::timeout(KAFKA_DELIVERY_TIMEOUT, async { let producer = &producer; @@ -444,7 +446,7 @@ pub async fn dispatch_project_flag_run( ProjectFlagRunEvent { project_id, run_id: Some(run_id) }, ); let payload = serde_json::to_vec(&event) - .wrap_err("serializing project flag run event")?; + .context("serializing project flag run event")?; let project_key = project_id.to_string(); producer .send( @@ -455,16 +457,16 @@ pub async fn dispatch_project_flag_run( KAFKA_OPERATION_INTERVAL, ) .await - .map_err(|(error, _)| eyre!(error)) - .wrap_err("publishing project flag run event")?; - eyre::Ok(()) + .map_err(|(error, _)| anyhow!(error)) + .context("publishing project flag run event")?; + anyhow::Ok(()) }) .buffer_unordered(100) .try_collect::<()>() .await }) .await - .wrap_err("timed out publishing project flag run events")? + .context("timed out publishing project flag run events")? })?; commit_uncertain = true; for attempt in 0..3 { @@ -477,8 +479,8 @@ pub async fn dispatch_project_flag_run( if error.txn_requires_abort() => { commit_uncertain = false; - return Err(eyre!(error)) - .wrap_err("committing project flag run Kafka transaction"); + return Err(anyhow!(error)) + .context("committing project flag run Kafka transaction"); } Err(KafkaError::Transaction(error)) if error.is_retriable() && attempt < 2 => @@ -486,22 +488,22 @@ pub async fn dispatch_project_flag_run( tracing::warn!(%error, "Retrying project flag run Kafka commit"); } Err(error) => { - return Err(eyre!(error)) - .wrap_err("committing project flag run Kafka transaction"); + return Err(anyhow!(error)) + .context("committing project flag run Kafka transaction"); } } } - eyre::Ok(()) + anyhow::Ok(()) })(); if let Err(error) = result { if commit_uncertain { - return Err(error.wrap_err(ProjectFlagDispatchUncertain)); + return Err(error.context(ProjectFlagDispatchUncertain)); } if let Err(abort_error) = producer.abort_transaction(KAFKA_DELIVERY_TIMEOUT) { - return Err(error.wrap_err(format!( + return Err(error.context(format!( "aborting project flag run Kafka transaction failed: {abort_error}" ))); } @@ -511,6 +513,6 @@ pub async fn dispatch_project_flag_run( Ok(()) }) .await - .wrap_err("joining project flag run dispatch") - .wrap_err(ProjectFlagDispatchUncertain)? + .context("joining project flag run dispatch") + .context(ProjectFlagDispatchUncertain)? } diff --git a/apps/labrinth/src/queue/payouts/flow/mod.rs b/apps/labrinth/src/queue/payouts/flow/mod.rs index 240b525acf6..88a8c3ab9c2 100644 --- a/apps/labrinth/src/queue/payouts/flow/mod.rs +++ b/apps/labrinth/src/queue/payouts/flow/mod.rs @@ -2,7 +2,7 @@ //! maximum withdraw amounts, and execution logic. use crate::util::error::ApiContext as _; -use eyre::eyre; +use anyhow::anyhow; use modrinth_util::decimal::Decimal2dp; use rust_decimal::Decimal; use thiserror::Error; @@ -38,10 +38,10 @@ impl PayoutsQueue { let method = self .get_payout_methods() .await - .wrap_internal_err("failed to fetch payout methods")? + .internal_context("failed to fetch payout methods")? .into_iter() .find(|method| method.id == withdrawal.method_id) - .wrap_request_err("invalid payout method ID")?; + .request_context("invalid payout method ID")?; Ok::<_, ApiError>(method) }; @@ -62,7 +62,7 @@ impl PayoutsQueue { method_details, &get_method .await - .wrap_api_err("executing `tremendous::create`")?, + .api_context("executing `tremendous::create`")?, ) .await } @@ -166,11 +166,12 @@ impl ReadyPayoutFlow { } fn get_verified_email(user: &DBUser) -> Result<&str, ApiError> { - let email = user.email.as_ref().wrap_request_err( - "you must add an email to your account to withdraw", - )?; + let email = user + .email + .as_ref() + .request_context("you must add an email to your account to withdraw")?; if !user.email_verified { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "you must verify your email to withdraw" ))); } diff --git a/apps/labrinth/src/queue/payouts/flow/mural.rs b/apps/labrinth/src/queue/payouts/flow/mural.rs index ac55d132a82..44529fbc490 100644 --- a/apps/labrinth/src/queue/payouts/flow/mural.rs +++ b/apps/labrinth/src/queue/payouts/flow/mural.rs @@ -1,6 +1,6 @@ +use anyhow::anyhow; use ariadne::ids::UserId; use chrono::Utc; -use eyre::eyre; use modrinth_util::decimal::Decimal2dp; use muralpay::FiatAndRailCode; use rust_decimal::{Decimal, RoundingStrategy, dec}; @@ -76,13 +76,13 @@ pub(super) async fn create( details: MuralPayDetails, ) -> Result { if is_blocked_region(details.recipient_info.physical_address()) { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "withdrawals are not supported for this region" ))); } let gross_usd = - Decimal2dp::new(amount).wrap_request_err("invalid amount")?; + Decimal2dp::new(amount).request_context("invalid amount")?; let platform_fee_usd = Decimal2dp::rounded( PLATFORM_FEE.compute_fee(gross_usd), RoundingStrategy::AwayFromZero, @@ -91,7 +91,7 @@ pub(super) async fn create( let mural = queue.muralpay.load(); let mural = mural .as_ref() - .wrap_internal_err("required Mural client is not available")?; + .internal_context("required Mural client is not available")?; let method_fee_usd; let forex_usd_to_currency; @@ -119,11 +119,11 @@ pub(super) async fn create( fiat_and_rail_code, }]) .await - .wrap_internal_err("failed to request fees")?; + .internal_context("failed to request fees")?; let fee = fees .into_iter() .next() - .wrap_internal_err("no fees returned")?; + .internal_context("no fees returned")?; match fee { muralpay::TokenPayoutFee::Success { @@ -139,7 +139,7 @@ pub(super) async fn create( min_amount_usd = min_usd_fiat(fiat_and_rail_code); } muralpay::TokenPayoutFee::Error { message, .. } => { - return Err(ApiError::Internal(eyre!( + return Err(ApiError::Internal(anyhow!( "failed to compute fee: {message}" ))); } @@ -182,15 +182,15 @@ pub(super) async fn execute( recipient_info, }: MuralFlow, ) -> Result<(), ApiError> { - let user_email = get_verified_email(user) - .wrap_api_err("fetching verified user email")?; + let user_email = + get_verified_email(user).api_context("fetching verified user email")?; let sent_to_method_usd = net_usd + method_fee_usd; let total_fee_usd = method_fee_usd + platform_fee_usd; let mural = queue.muralpay.load(); let mural = mural .as_ref() - .wrap_internal_err("required Mural client is not available")?; + .internal_context("required Mural client is not available")?; let payment_statement_doc = queue .create_mural_payment_statement_doc( @@ -201,7 +201,7 @@ pub(super) async fn execute( gotenberg, ) .await - .wrap_api_err("creating Mural payment statement document")?; + .api_context("creating Mural payment statement document")?; let user_id = UserId::from(user.id); let method_id = match &payout_details { @@ -265,11 +265,11 @@ pub(super) async fn execute( let payout_request = match payout_request { Ok(payout_request) => payout_request, Err(muralpay::MuralError::Api(err)) => { - return Err(ApiError::Request(eyre::eyre!(Box::new(err)))); + return Err(ApiError::Request(anyhow!(Box::new(err)))); } Err(err) => { return Err(ApiError::Internal( - eyre!(err).wrap_err("failed to create payout request"), + anyhow!(err).context("failed to create payout request"), )); } }; @@ -307,7 +307,7 @@ pub(super) async fn execute( .client .execute_payout_request(payout_request.id) .await - .wrap_internal_err("failed to execute payout request")?; + .internal_context("failed to execute payout request")?; Ok::<_, ApiError>(()) }) .await; @@ -334,12 +334,12 @@ pub(super) async fn execute( payout .insert(&mut transaction) .await - .wrap_internal_err("failed to insert payout")?; + .internal_context("failed to insert payout")?; transaction .commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; Ok(()) } diff --git a/apps/labrinth/src/queue/payouts/flow/paypal.rs b/apps/labrinth/src/queue/payouts/flow/paypal.rs index de4b158f347..3200f6fb0ea 100644 --- a/apps/labrinth/src/queue/payouts/flow/paypal.rs +++ b/apps/labrinth/src/queue/payouts/flow/paypal.rs @@ -1,3 +1,4 @@ +use anyhow::anyhow; use chrono::Utc; use modrinth_util::decimal::Decimal2dp; use reqwest::Method; @@ -39,7 +40,7 @@ pub(super) async fn create( is_venmo: bool, ) -> Result { let gross_usd = - Decimal2dp::new(amount).wrap_request_err("invalid amount")?; + Decimal2dp::new(amount).request_context("invalid amount")?; let fee_usd = Decimal2dp::rounded( FEE.compute_fee(amount), RoundingStrategy::AwayFromZero, @@ -102,18 +103,18 @@ pub(super) async fn execute( if let Some(venmo) = &user.venmo_handle { ("Venmo", "user_handle", venmo.clone(), venmo) } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Venmo address has not been set for account!", ))); } } else if let Some(paypal_id) = &user.paypal_id { if let Some(paypal_country) = &user.paypal_country { if paypal_country == "US" && method_id != "paypal_us" { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Please use the US PayPal transfer option!", ))); } else if paypal_country != "US" && method_id == "paypal_us" { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Please use the International PayPal transfer option!", ))); } @@ -125,12 +126,12 @@ pub(super) async fn execute( user.paypal_email.as_ref().unwrap_or(paypal_id), ) } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Please re-link your PayPal account!", ))); } } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You have not linked a PayPal account!", ))); }; @@ -163,7 +164,7 @@ pub(super) async fn execute( None, ) .await - .wrap_internal_err("failed to make payout request")?; + .internal_context("failed to make payout request")?; // by this point, we've made a monetary payout request to this user; // no matter what we do, we *must* track this payout in the DB, @@ -191,7 +192,7 @@ pub(super) async fn execute( let link = res .links .first() - .wrap_request_err("no PayPal links available")?; + .request_context("no PayPal links available")?; let res = queue .make_paypal_request::<(), PayoutData>( @@ -202,8 +203,8 @@ pub(super) async fn execute( Some(true), ) .await - .wrap_internal_err("failed to make PayPal link request")?; - let data = res.items.first().wrap_internal_err( + .internal_context("failed to make PayPal link request")?; + let data = res.items.first().internal_context( "no payout items returned from PayPal link request", )?; @@ -221,12 +222,12 @@ pub(super) async fn execute( payout .insert(&mut transaction) .await - .wrap_internal_err("failed to insert payout")?; + .internal_context("failed to insert payout")?; transaction .commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; Ok(()) } diff --git a/apps/labrinth/src/queue/payouts/flow/tremendous.rs b/apps/labrinth/src/queue/payouts/flow/tremendous.rs index 19b00bba959..b524ffd520e 100644 --- a/apps/labrinth/src/queue/payouts/flow/tremendous.rs +++ b/apps/labrinth/src/queue/payouts/flow/tremendous.rs @@ -1,6 +1,6 @@ use crate::util::error::ApiContext as _; +use anyhow::anyhow; use chrono::Utc; -use eyre::eyre; use modrinth_util::decimal::Decimal2dp; use reqwest::Method; use rust_decimal::{Decimal, RoundingStrategy, dec}; @@ -43,19 +43,19 @@ pub(super) async fn create( let forex: TremendousForexResponse = queue .make_tremendous_request(Method::GET, "forex", None::<()>) .await - .wrap_internal_err("failed to fetch Tremendous forex data")?; + .internal_context("failed to fetch Tremendous forex data")?; let usd_to_currency_for = |currency_code: &str| { forex .forex .get(currency_code) .copied() - .wrap_internal_err_with(|| { - eyre!("no Tremendous forex rate for '{currency_code}'") + .internal_context_with(|| { + anyhow!("no Tremendous forex rate for '{currency_code}'") }) }; - let category = method.category.as_ref().wrap_internal_err_with(|| { - eyre!("method '{}' should have a category", method.id) + let category = method.category.as_ref().internal_context_with(|| { + anyhow!("method '{}' should have a category", method.id) })?; let delivery_email = details.delivery_email; @@ -66,7 +66,7 @@ pub(super) async fn create( let currency = details.currency.unwrap_or(TremendousCurrency::Usd); let currency_code = currency.to_string(); let usd_to_currency = usd_to_currency_for(¤cy_code) - .wrap_api_err("executing `usd_to_currency_for`")?; + .api_context("executing `usd_to_currency_for`")?; let fee = PayoutMethodFee { // If a user withdraws $10: @@ -85,7 +85,7 @@ pub(super) async fn create( }; let gross_usd = - Decimal2dp::new(amount).wrap_request_err("invalid amount")?; + Decimal2dp::new(amount).request_context("invalid amount")?; let total_fee_usd = Decimal2dp::rounded( fee.compute_fee(amount), @@ -130,7 +130,7 @@ pub(super) async fn create( TremendousCurrency::Usd.to_string() }; let usd_to_currency = usd_to_currency_for(¤cy_code) - .wrap_api_err("executing `usd_to_currency_for`")?; + .api_context("executing `usd_to_currency_for`")?; let currency_to_usd = dec!(1) / usd_to_currency; // no fees @@ -193,8 +193,8 @@ pub(super) async fn execute( pub order: Order, } - let user_email = get_verified_email(user) - .wrap_api_err("fetching verified user email")?; + let user_email = + get_verified_email(user).api_context("fetching verified user email")?; let order_req = json!({ "payment": { @@ -222,7 +222,7 @@ pub(super) async fn execute( let order_res: TremendousResponse = queue .make_tremendous_request(Method::POST, "orders", Some(order_req)) .await - .wrap_internal_err("failed to make Tremendous order request")?; + .internal_context("failed to make Tremendous order request")?; let platform_id = order_res .order @@ -244,12 +244,12 @@ pub(super) async fn execute( } .insert(&mut transaction) .await - .wrap_internal_err("failed to insert payout")?; + .internal_context("failed to insert payout")?; transaction .commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; Ok(()) } diff --git a/apps/labrinth/src/queue/payouts/mod.rs b/apps/labrinth/src/queue/payouts/mod.rs index 166851caa67..828cde23120 100644 --- a/apps/labrinth/src/queue/payouts/mod.rs +++ b/apps/labrinth/src/queue/payouts/mod.rs @@ -6,10 +6,11 @@ use crate::models::payouts::{ use crate::routes::ApiError; use crate::util::error::ApiContext as _; use crate::util::error::Context; +use anyhow::Result; +use anyhow::anyhow; use arc_swap::ArcSwapOption; use base64::Engine; use chrono::{DateTime, Duration, Utc}; -use eyre::Result; use modrinth_util::decimal::Decimal2dp; use muralpay::FiatAndRailCode; use reqwest::Method; @@ -187,14 +188,14 @@ impl PayoutsQueue { .form(&form) .send() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "error while authenticating with PayPal".to_string(), )? .json() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "error while authenticating with PayPal (deser error)" .to_string(), )?; @@ -224,8 +225,8 @@ impl PayoutsQueue { drop(read); self.refresh_token() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "error while authenticating with PayPal".to_string(), )? } else { @@ -235,8 +236,8 @@ impl PayoutsQueue { drop(read); self.refresh_token() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "error while authenticating with PayPal".to_string(), )? }; @@ -270,8 +271,8 @@ impl PayoutsQueue { let resp = request .send() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "could not communicate with PayPal".to_string(), )?; @@ -280,8 +281,8 @@ impl PayoutsQueue { let value = resp .json::() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "could not retrieve PayPal response body".to_string(), )?; @@ -304,7 +305,7 @@ impl PayoutsQueue { if error.name == "INSUFFICIENT_FUNDS" { error.message = "We're currently transferring funds to our PayPal account. Please try again in a couple days.".to_string(); } - return Err(ApiError::FailedDependency(eyre::eyre!(format!( + return Err(ApiError::FailedDependency(anyhow!(format!( "error name: {}, message: {}", error.name, error.message )))); @@ -313,19 +314,18 @@ impl PayoutsQueue { if let Ok(error) = serde_json::from_value::(value) { - return Err(ApiError::FailedDependency(eyre::eyre!(format!( + return Err(ApiError::FailedDependency(anyhow!(format!( "error name: {}, message: {}", error.error, error.error_description )))); } - return Err(ApiError::FailedDependency(eyre::eyre!( + return Err(ApiError::FailedDependency(anyhow!( "could not retrieve PayPal error body", ))); } - serde_json::from_value(value) - .wrap_request_err("deserializing JSON data") + serde_json::from_value(value).request_context("deserializing JSON data") } pub async fn make_tremendous_request( @@ -349,8 +349,8 @@ impl PayoutsQueue { let resp = request .send() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "could not communicate with Tremendous".to_string(), )?; @@ -359,8 +359,8 @@ impl PayoutsQueue { let value = resp .json::() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "could not retrieve Tremendous response body".to_string(), )?; @@ -376,25 +376,24 @@ impl PayoutsQueue { let err = serde_json::from_value::(array.clone()) - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "could not retrieve Tremendous error json body" .to_string(), )?; - return Err(ApiError::FailedDependency(eyre::eyre!(format!( + return Err(ApiError::FailedDependency(anyhow!(format!( "Tremendous error: {} ({:?})", err.message, err.payload )))); } - return Err(ApiError::FailedDependency(eyre::eyre!( + return Err(ApiError::FailedDependency(anyhow!( "could not retrieve Tremendous error body", ))); } - serde_json::from_value(value) - .wrap_request_err("deserializing JSON data") + serde_json::from_value(value).request_context("deserializing JSON data") } pub async fn get_payout_methods( @@ -462,7 +461,7 @@ impl PayoutsQueue { drop(read); refresh_payout_methods(self) .await - .wrap_api_err("executing `refresh_payout_methods`")? + .api_context("executing `refresh_payout_methods`")? } else { options.clone() } @@ -470,7 +469,7 @@ impl PayoutsQueue { drop(read); refresh_payout_methods(self) .await - .wrap_api_err("executing `refresh_payout_methods`")? + .api_context("executing `refresh_payout_methods`")? }; Ok(options.options) @@ -550,7 +549,7 @@ async fn get_tremendous_payout_methods( let forex: TremendousForexResponse = queue .make_tremendous_request(Method::GET, "forex", None::<()>) .await - .wrap_err("failed to fetch Tremendous forex data")?; + .context("failed to fetch Tremendous forex data")?; let response = queue .make_tremendous_request::<(), TremendousResponse>( @@ -559,7 +558,7 @@ async fn get_tremendous_payout_methods( None, ) .await - .wrap_err("failed to fetch Tremendous products data")?; + .context("failed to fetch Tremendous products data")?; let mut methods = Vec::new(); diff --git a/apps/labrinth/src/queue/payouts/mural.rs b/apps/labrinth/src/queue/payouts/mural.rs index a877df8d998..fb6f21c35af 100644 --- a/apps/labrinth/src/queue/payouts/mural.rs +++ b/apps/labrinth/src/queue/payouts/mural.rs @@ -1,5 +1,5 @@ +use anyhow::{Result, anyhow}; use chrono::Utc; -use eyre::{Result, eyre}; use modrinth_util::decimal::Decimal2dp; use rust_decimal::{Decimal, prelude::ToPrimitive}; use serde::{Deserialize, Serialize}; @@ -59,19 +59,19 @@ impl PayoutsQueue { payment_date: Utc::now(), gross_amount_cents: gross_cents .to_i64() - .wrap_internal_err_with(|| eyre!("gross amount of cents `{gross_cents}` cannot be expressed as an `i64`"))?, + .internal_context_with(|| anyhow!("gross amount of cents `{gross_cents}` cannot be expressed as an `i64`"))?, net_amount_cents: net_cents .to_i64() - .wrap_internal_err_with(|| eyre!("net amount of cents `{net_cents}` cannot be expressed as an `i64`"))?, + .internal_context_with(|| anyhow!("net amount of cents `{net_cents}` cannot be expressed as an `i64`"))?, fees_cents: fees_cents .to_i64() - .wrap_internal_err_with(|| eyre!("fees amount of cents `{fees_cents}` cannot be expressed as an `i64`"))?, + .internal_context_with(|| anyhow!("fees amount of cents `{fees_cents}` cannot be expressed as an `i64`"))?, currency_code: "USD".into(), }; let payment_statement_doc = gotenberg .wait_for_payment_statement(&payment_statement) .await - .wrap_internal_err("failed to generate payment statement")?; + .internal_context("failed to generate payment statement")?; // TODO // std::fs::write( @@ -94,7 +94,7 @@ impl PayoutsQueue { let muralpay = self.muralpay.load(); let muralpay = muralpay .as_ref() - .wrap_err("Mural Pay client not available")?; + .context("Mural Pay client not available")?; muralpay.client.cancel_payout_request(id).await?; Ok(()) diff --git a/apps/labrinth/src/queue/server_ping.rs b/apps/labrinth/src/queue/server_ping.rs index 3e59b537cef..461a3b63503 100644 --- a/apps/labrinth/src/queue/server_ping.rs +++ b/apps/labrinth/src/queue/server_ping.rs @@ -46,7 +46,7 @@ impl ServerPingQueue { } } - pub async fn ping_minecraft_java_servers(&self) -> eyre::Result<()> { + pub async fn ping_minecraft_java_servers(&self) -> anyhow::Result<()> { let server_projects = self.find_servers_to_ping().await?; info!("Found {} servers to ping", server_projects.len()); @@ -101,13 +101,13 @@ impl ServerPingQueue { .clickhouse .insert::(CLICKHOUSE_TABLE) .await - .wrap_err("failed to begin inserting ping records")?; + .context("failed to begin inserting ping records")?; let mut redis = self .redis .connect() .await - .wrap_err("failed to connect to redis")?; + .context("failed to connect to redis")?; for (project_id, ping) in &pings { let data = ping.data.as_ref(); @@ -133,7 +133,7 @@ impl ServerPingQueue { ch.write(&row) .await - .wrap_err("failed to write ping record")?; + .context("failed to write ping record")?; let mut updated_project = false; if data.is_some() { @@ -142,13 +142,13 @@ impl ServerPingQueue { redis .set_serialized(&ping_key, ping, None) .await - .wrap_err("failed to set redis key")?; + .context("failed to set redis key")?; updated_project = true; redis .delete(&failure_key) .await - .wrap_err("failed to delete failure count")?; + .context("failed to delete failure count")?; } else { // ping failed; if it's failed too many times, mark it as offline in redis // otherwise, just add to the fail counter @@ -156,7 +156,7 @@ impl ServerPingQueue { let failure_count = redis .incr(&failure_key) .await - .wrap_err("failed to increment failure count")?; + .context("failed to increment failure count")?; if let Some(count) = failure_count && count >= ENV.SERVER_PING_MAX_FAIL_COUNT @@ -164,7 +164,7 @@ impl ServerPingQueue { redis .set_serialized(&ping_key, ping, None) .await - .wrap_err( + .context( "failed to set failed ping record in redis", )?; updated_project = true; @@ -194,7 +194,7 @@ impl ServerPingQueue { ch.end() .await - .wrap_err("failed to end inserting ping records")?; + .context("failed to end inserting ping records")?; } let num_success = @@ -210,7 +210,8 @@ impl ServerPingQueue { async fn find_servers_to_ping( &self, - ) -> eyre::Result> { + ) -> anyhow::Result> + { // first select all java servers let all_server_projects = sqlx::query!( r#" @@ -227,7 +228,7 @@ impl ServerPingQueue { ) .fetch_all(&self.db) .await - .wrap_err("failed to fetch servers to ping")?; + .context("failed to fetch servers to ping")?; if all_server_projects.is_empty() { // we must early-exit, otherwise we'll run `redis.get_many()`, @@ -240,7 +241,7 @@ impl ServerPingQueue { .redis .connect() .await - .wrap_err("failed to connect to redis")?; + .context("failed to connect to redis")?; // get the last ping info for all of them // querying redis here, which is a cache, not the source of truth (clickhouse), @@ -260,7 +261,7 @@ impl ServerPingQueue { let all_server_last_pings = redis .get_many_deserialized::(&ping_keys) .await - .wrap_err("failed to fetch server project last pings")?; + .context("failed to fetch server project last pings")?; let now = Utc::now(); let projects_to_ping = all_server_projects @@ -303,7 +304,7 @@ impl ServerPingQueue { pub async fn ping_server( address: &str, timeout: Option, -) -> eyre::Result { +) -> anyhow::Result { let start = Instant::now(); let default_duration = Duration::from_millis(ENV.SERVER_PING_TIMEOUT_MS); let timeout = timeout @@ -312,7 +313,7 @@ pub async fn ping_server( let (address, port) = match address.rsplit_once(':') { Some((addr, port)) => { - let port = port.parse::().wrap_err("invalid port number")?; + let port = port.parse::().context("invalid port number")?; (addr, port) } None => (address, 25565), @@ -324,15 +325,15 @@ pub async fn ping_server( .with_srv_lookup() .connect() .await - .wrap_err("failed to connect to server")?; + .context("failed to connect to server")?; let status = conn .status() .await - .wrap_err("failed to get server status")? + .context("failed to get server status")? .status; - eyre::Ok(exp::minecraft::JavaServerPingData { + anyhow::Ok(exp::minecraft::JavaServerPingData { latency: start.elapsed(), version_name: status.version.name, version_protocol: status.version.protocol, @@ -347,7 +348,7 @@ pub async fn ping_server( tokio::time::timeout(timeout, task) .await - .map_err(eyre::Error::new) + .map_err(anyhow::Error::new) .flatten() } diff --git a/apps/labrinth/src/queue/session.rs b/apps/labrinth/src/queue/session.rs index adb2f2fe2e5..83242d390d1 100644 --- a/apps/labrinth/src/queue/session.rs +++ b/apps/labrinth/src/queue/session.rs @@ -6,8 +6,8 @@ use crate::database::models::{ }; use crate::database::{PgPool, PgTransaction}; use crate::routes::internal::session::SessionMetadata; +use anyhow::{Context as _, Result}; use chrono::Utc; -use eyre::{Result, WrapErr as _}; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use tokio::sync::Mutex; @@ -89,15 +89,15 @@ impl AuthQueue { let mut transaction = pool .begin() .await - .wrap_err("starting database transaction")?; + .context("starting database transaction")?; sqlx::query!("SET LOCAL lock_timeout = '60s'") .execute(&mut transaction) .await - .wrap_err("setting auth queue flush lock timeout")?; + .context("setting auth queue flush lock timeout")?; AdvisoryLock::AuthQueueFlush .acquire(&mut transaction) .await - .wrap_err("acquiring auth queue flush lock")?; + .context("acquiring auth queue flush lock")?; let mut clear_cache_sessions = Vec::new(); for (id, metadata) in session_queue { @@ -120,7 +120,7 @@ impl AuthQueue { ) .execute(&mut transaction) .await - .wrap_err("updating session last login in database")?; + .context("updating session last login in database")?; } use futures::TryStreamExt; @@ -135,7 +135,7 @@ impl AuthQueue { .map_ok(|x| (DBSessionId(x.id), x.session, DBUserId(x.user_id))) .try_collect::>() .await - .wrap_err("fetching expired sessions from database")?; + .context("fetching expired sessions from database")?; for (id, session, user_id) in expired_ids { clear_cache_sessions.push(( @@ -145,12 +145,12 @@ impl AuthQueue { )); DBSession::remove(id, &mut transaction) .await - .wrap_err("removing expired session from database")?; + .context("removing expired session from database")?; } DBSession::clear_cache(clear_cache_sessions, redis) .await - .wrap_err("clearing expired session cache")?; + .context("clearing expired session cache")?; let ids = pat_queue.iter().map(|id| id.0).collect_vec(); let clear_cache_pats = pat_queue @@ -169,22 +169,22 @@ impl AuthQueue { ) .execute(&mut transaction) .await - .wrap_err("updating personal access token last used in database")?; + .context("updating personal access token last used in database")?; update_oauth_access_token_last_used( oauth_access_token_queue, &mut transaction, ) .await - .wrap_err("updating oauth access token last used in database")?; + .context("updating oauth access token last used in database")?; transaction .commit() .await - .wrap_err("committing database transaction")?; + .context("committing database transaction")?; DBPersonalAccessToken::clear_cache(clear_cache_pats, redis) .await - .wrap_err("clearing personal access token cache")?; + .context("clearing personal access token cache")?; } Ok(flushed_counts) @@ -208,6 +208,6 @@ async fn update_oauth_access_token_last_used( ) .execute(&mut *transaction) .await - .wrap_err("updating oauth access token last used in database")?; + .context("updating oauth access token last used in database")?; Ok(()) } diff --git a/apps/labrinth/src/routes/debug/mod.rs b/apps/labrinth/src/routes/debug/mod.rs index f405b7b8fe0..4320c63bc02 100644 --- a/apps/labrinth/src/routes/debug/mod.rs +++ b/apps/labrinth/src/routes/debug/mod.rs @@ -1,8 +1,8 @@ use std::time::Duration; use actix_web::web; -use eyre::Context; -use eyre::eyre; +use anyhow::Context; +use anyhow::anyhow; use prometheus::IntGauge; #[cfg(target_os = "linux")] @@ -45,16 +45,16 @@ pub fn config(cfg: &mut actix_web::web::ServiceConfig) { pub fn register_and_set_metrics( registry: &prometheus::Registry, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { #[cfg(target_os = "linux")] { pprof::register_and_set_metrics(registry) - .wrap_err("failed to register jemalloc metrics")?; + .context("failed to register jemalloc metrics")?; } let make_gauge = |key: &str, name: &str| { IntGauge::new(key, name) - .wrap_err_with(|| eyre!("failed to create gauge for '{key}'")) + .with_context(|| anyhow!("failed to create gauge for '{key}'")) }; let num_workers = make_gauge( @@ -73,7 +73,7 @@ pub fn register_and_set_metrics( for gauge in [&num_workers, &num_alive_tasks, &global_queue_depth] { registry .register(Box::new(gauge.clone())) - .wrap_err("failed to register gauge")?; + .context("failed to register gauge")?; } tokio::spawn(async move { diff --git a/apps/labrinth/src/routes/debug/pprof.rs b/apps/labrinth/src/routes/debug/pprof.rs index 89845bb77cc..34439861b1c 100644 --- a/apps/labrinth/src/routes/debug/pprof.rs +++ b/apps/labrinth/src/routes/debug/pprof.rs @@ -3,7 +3,7 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context as _; use crate::util::guards::admin_key_guard; use actix_web::{HttpResponse, get}; -use eyre::eyre; +use anyhow::anyhow; use prometheus::{IntGauge, Registry}; use std::time::Duration; @@ -24,11 +24,11 @@ pub fn config(cfg: &mut actix_web::web::ServiceConfig) { pub async fn heap() -> Result { let mut prof_ctl = jemalloc_pprof::PROF_CTL.as_ref().unwrap().lock().await; require_profiling_activated(&prof_ctl) - .wrap_api_err("executing `require_profiling_activated`")?; + .api_context("executing `require_profiling_activated`")?; let pprof = prof_ctl .dump_pprof() - .map_err(|err| eyre::Report::msg(err.to_string())) - .wrap_request_err("processing request")?; + .map_err(|err| anyhow::Error::msg(err.to_string())) + .request_context("processing request")?; Ok(HttpResponse::Ok() .content_type("application/octet-stream") @@ -44,11 +44,11 @@ pub async fn heap() -> Result { pub async fn flame_graph() -> Result { let mut prof_ctl = jemalloc_pprof::PROF_CTL.as_ref().unwrap().lock().await; require_profiling_activated(&prof_ctl) - .wrap_api_err("executing `require_profiling_activated`")?; + .api_context("executing `require_profiling_activated`")?; let svg = prof_ctl .dump_flamegraph() - .map_err(|err| eyre::Report::msg(err.to_string())) - .wrap_request_err("processing request")?; + .map_err(|err| anyhow::Error::msg(err.to_string())) + .request_context("processing request")?; Ok(HttpResponse::Ok().content_type("image/svg+xml").body(svg)) } @@ -59,16 +59,14 @@ fn require_profiling_activated( if prof_ctl.activated() { Ok(()) } else { - Err(ApiError::Request( - eyre::eyre!("Profiling is not activated",), - )) + Err(ApiError::Request(anyhow!("Profiling is not activated",))) } } -pub fn register_and_set_metrics(registry: &Registry) -> eyre::Result<()> { +pub fn register_and_set_metrics(registry: &Registry) -> anyhow::Result<()> { let make_gauge = |key: &str, name: &str| { IntGauge::new(key, name) - .wrap_err_with(|| eyre!("failed to create gauge for '{key}'")) + .with_context(|| anyhow!("failed to create gauge for '{key}'")) }; let active_mem = @@ -91,7 +89,7 @@ pub fn register_and_set_metrics(registry: &Registry) -> eyre::Result<()> { ] { registry .register(Box::new(gauge.clone())) - .wrap_err("failed to register gauge")?; + .context("failed to register gauge")?; } tokio::spawn(async move { diff --git a/apps/labrinth/src/routes/internal/admin.rs b/apps/labrinth/src/routes/internal/admin.rs index c3229bb7681..d86fe4f5bc7 100644 --- a/apps/labrinth/src/routes/internal/admin.rs +++ b/apps/labrinth/src/routes/internal/admin.rs @@ -7,7 +7,7 @@ use crate::search::incremental::consume::reindex_project_document; use crate::util::error::Context; use crate::util::guards::admin_key_guard; use actix_web::{HttpResponse, post, web}; -use eyre::eyre; +use anyhow::anyhow; use serde::Deserialize; use xredis::RedisPool; @@ -60,7 +60,7 @@ pub async fn force_reindex( search_backend .rebuild_index(pool.as_ref().clone(), redis.clone()) .await - .wrap_internal_err("failed to index projects")?; + .internal_context("failed to index projects")?; Ok(HttpResponse::NoContent().finish()) } @@ -90,8 +90,8 @@ pub async fn force_reindex_project( project_id, ) .await - .wrap_internal_err_with(|| { - eyre!("failed to reindex project `{project_id}`") + .internal_context_with(|| { + anyhow!("failed to reindex project `{project_id}`") })?; Ok(HttpResponse::NoContent().finish()) diff --git a/apps/labrinth/src/routes/internal/admin/user_credentials.rs b/apps/labrinth/src/routes/internal/admin/user_credentials.rs index f0f0298c96d..8a7a6b6e022 100644 --- a/apps/labrinth/src/routes/internal/admin/user_credentials.rs +++ b/apps/labrinth/src/routes/internal/admin/user_credentials.rs @@ -1,6 +1,6 @@ use actix_web::{HttpRequest, delete, post, web}; +use anyhow::anyhow; use chrono::Duration; -use eyre::eyre; use lettre::message::Mailbox; use serde::Deserialize; use xredis::RedisPool; @@ -55,24 +55,24 @@ pub async fn force_password_reset( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you must be an admin to reset a user's password" ))); } let target = DBUser::get(&path.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("user not found")?; + .internal_context("fetching user from database")? + .not_found_context("user not found")?; if matches!( Role::from_string(&target.role), Role::Moderator | Role::Admin ) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "cannot reset password of a staff account" ))); } @@ -83,19 +83,19 @@ pub async fn force_password_reset( .map(|email| email.trim().to_owned()) .filter(|email| !email.is_empty()) .or(target.email) - .wrap_request_err("user has no email address, one must be specified")?; + .request_context("user has no email address, one must be specified")?; let mailbox: Mailbox = - address.parse().wrap_request_err("invalid email address")?; + address.parse().request_context("invalid email address")?; let email_taken = DBUser::get_by_case_insensitive_email(&address, &**pool) .await - .wrap_internal_err("checking for existing email address")? + .internal_context("checking for existing email address")? .into_iter() .any(|id| id != target.id); if email_taken { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "email address is already registered to another account" ))); } @@ -103,7 +103,7 @@ pub async fn force_password_reset( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( r#" @@ -119,11 +119,11 @@ pub async fn force_password_reset( ) .execute(&mut txn) .await - .wrap_internal_err("clearing user password and setting email")?; + .internal_context("clearing user password and setting email")?; let sessions = DBSession::remove_all_for_user(target.id, &mut txn) .await - .wrap_internal_err("revoking user sessions")?; + .internal_context("revoking user sessions")?; let flow = DBFlow::ForcedPasswordReset { user_id: target.id, @@ -131,7 +131,7 @@ pub async fn force_password_reset( } .insert(Duration::hours(24), &redis) .await - .wrap_internal_err("inserting password reset flow")?; + .internal_context("inserting password reset flow")?; email_queue .send_one( @@ -141,21 +141,21 @@ pub async fn force_password_reset( mailbox, ) .await - .wrap_api_err("sending password reset email")? + .api_context("sending password reset email")? .as_user_error() - .wrap_api_err("validating email delivery status")?; + .api_context("validating email delivery status")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBUser::clear_caches(&[(target.id, Some(target.username))], &redis) .await - .wrap_internal_err("clearing user cache")?; + .internal_context("clearing user cache")?; DBSession::clear_user_sessions_cache(target.id, sessions, &redis) .await - .wrap_internal_err("clearing session cache")?; + .internal_context("clearing session cache")?; Ok(()) } @@ -182,55 +182,57 @@ pub async fn reset_2fa( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you must be an admin to reset a user's 2FA" ))); } let target = DBUser::get(&path.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("user not found")?; + .internal_context("fetching user from database")? + .not_found_context("user not found")?; if matches!( Role::from_string(&target.role), Role::Moderator | Role::Admin ) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "cannot reset 2FA of a staff account" ))); } if target.totp_secret.is_none() { - return Err(ApiError::Request(eyre!("user does not have 2FA enabled"))); + return Err(ApiError::Request(anyhow!( + "user does not have 2FA enabled" + ))); } let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; DBUser::remove_2fa(target.id, &mut txn) .await - .wrap_internal_err("removing 2FA")?; + .internal_context("removing 2FA")?; NotificationBuilder { body: NotificationBody::TwoFactorRemoved, } .insert(target.id, &mut txn, &redis) .await - .wrap_internal_err("inserting 2FA removal notification")?; + .internal_context("inserting 2FA removal notification")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBUser::clear_caches(&[(target.id, Some(target.username))], &redis) .await - .wrap_internal_err("clearing user cache")?; + .internal_context("clearing user cache")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/admin/user_lock.rs b/apps/labrinth/src/routes/internal/admin/user_lock.rs index cac9d5553d3..d0329230e0b 100644 --- a/apps/labrinth/src/routes/internal/admin/user_lock.rs +++ b/apps/labrinth/src/routes/internal/admin/user_lock.rs @@ -1,5 +1,5 @@ use actix_web::{HttpRequest, delete, put, web}; -use eyre::eyre; +use anyhow::anyhow; use serde::Deserialize; use xredis::RedisPool; @@ -50,53 +50,55 @@ pub async fn lock_user( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!("only admins can lock users"))); + return Err(ApiError::Auth(anyhow!("only admins can lock users"))); } let reason = body.reason.trim(); if reason.is_empty() { - return Err(ApiError::Request(eyre!("lock reason must not be empty"))); + return Err(ApiError::Request(anyhow!( + "lock reason must not be empty" + ))); } let target = DBUser::get(&path.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("user not found")?; + .internal_context("fetching user from database")? + .not_found_context("user not found")?; if matches!( Role::from_string(&target.role), Role::Moderator | Role::Admin ) { - return Err(ApiError::Auth(eyre!("cannot lock a staff account"))); + return Err(ApiError::Auth(anyhow!("cannot lock a staff account"))); } let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; DBUserLock::upsert(target.id, user.user.id.into(), reason, &mut txn) .await - .wrap_internal_err("locking user")?; + .internal_context("locking user")?; let sessions = DBSession::remove_all_for_user(target.id, &mut txn) .await - .wrap_internal_err("revoking user sessions")?; + .internal_context("revoking user sessions")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBUser::clear_caches(&[(target.id, Some(target.username))], &redis) .await - .wrap_internal_err("clearing user cache")?; + .internal_context("clearing user cache")?; DBSession::clear_user_sessions_cache(target.id, sessions, &redis) .await - .wrap_internal_err("clearing session cache")?; + .internal_context("clearing session cache")?; Ok(()) } @@ -123,27 +125,27 @@ pub async fn unlock_user( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!("only admins can unlock users"))); + return Err(ApiError::Auth(anyhow!("only admins can unlock users"))); } let target = DBUser::get(&path.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("user not found")?; + .internal_context("fetching user from database")? + .not_found_context("user not found")?; if !DBUserLock::delete(target.id, &**pool) .await - .wrap_internal_err("unlocking user")? + .internal_context("unlocking user")? { - return Err(ApiError::NotFound(eyre!("user is not locked"))); + return Err(ApiError::NotFound(anyhow!("user is not locked"))); } DBUser::clear_caches(&[(target.id, Some(target.username))], &redis) .await - .wrap_internal_err("clearing user cache")?; + .internal_context("clearing user cache")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/admin/user_sessions.rs b/apps/labrinth/src/routes/internal/admin/user_sessions.rs index 9e1b273d0cb..526c3a7677b 100644 --- a/apps/labrinth/src/routes/internal/admin/user_sessions.rs +++ b/apps/labrinth/src/routes/internal/admin/user_sessions.rs @@ -1,5 +1,5 @@ use actix_web::{HttpRequest, delete, web}; -use eyre::eyre; +use anyhow::anyhow; use xredis::RedisPool; use crate::auth::get_user_from_headers; @@ -38,45 +38,45 @@ pub async fn revoke_user_sessions( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "only admins can revoke user sessions" ))); } let target = DBUser::get(&path.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("user not found")?; + .internal_context("fetching user from database")? + .not_found_context("user not found")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let sessions = DBSession::remove_all_for_user(target.id, &mut transaction) .await - .wrap_internal_err("revoking user sessions")?; + .internal_context("revoking user sessions")?; let pats = DBPersonalAccessToken::remove_all_for_user(target.id, &mut transaction) .await - .wrap_internal_err("revoking user personal access tokens")?; + .internal_context("revoking user personal access tokens")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBSession::clear_user_sessions_cache(target.id, sessions, &redis) .await - .wrap_internal_err("clearing session cache")?; + .internal_context("clearing session cache")?; DBPersonalAccessToken::clear_user_pats_cache(target.id, pats, &redis) .await - .wrap_internal_err("clearing personal access token cache")?; + .internal_context("clearing personal access token cache")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/analytics_event.rs b/apps/labrinth/src/routes/internal/analytics_event.rs index bb4787f4586..9b280d2b354 100644 --- a/apps/labrinth/src/routes/internal/analytics_event.rs +++ b/apps/labrinth/src/routes/internal/analytics_event.rs @@ -1,6 +1,6 @@ use actix_web::{HttpRequest, delete, patch, post, web}; +use anyhow::anyhow; use chrono::{DateTime, Utc}; -use eyre::eyre; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -57,10 +57,10 @@ pub async fn analytics_event_create( Scopes::empty(), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to manage analytics events" ))); } @@ -68,10 +68,10 @@ pub async fn analytics_event_create( let mut transaction = pool .begin() .await - .wrap_internal_err("failed to begin transaction")?; + .internal_context("failed to begin transaction")?; let id = generate_analytics_event_id(&mut transaction) .await - .wrap_internal_err("failed to generate analytics event ID")?; + .internal_context("failed to generate analytics event ID")?; let event = DBAnalyticsEvent { id, @@ -82,15 +82,15 @@ pub async fn analytics_event_create( event .insert(&mut transaction) .await - .wrap_internal_err("failed to insert analytics event")?; + .internal_context("failed to insert analytics event")?; transaction .commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; DBAnalyticsEvent::clear_cache(&redis) .await - .wrap_internal_err("failed to clear analytics event cache")?; + .internal_context("failed to clear analytics event cache")?; Ok(web::Json(event.into())) } @@ -117,10 +117,10 @@ pub async fn analytics_event_edit( Scopes::empty(), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to manage analytics events" ))); } @@ -135,13 +135,13 @@ pub async fn analytics_event_edit( let updated = event .update(&**pool) .await - .wrap_internal_err("failed to update analytics event")?; + .internal_context("failed to update analytics event")?; if !updated { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } DBAnalyticsEvent::clear_cache(&redis) .await - .wrap_internal_err("failed to clear analytics event cache")?; + .internal_context("failed to clear analytics event cache")?; Ok(web::Json(event.into())) } @@ -167,10 +167,10 @@ pub async fn analytics_event_delete( Scopes::empty(), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to manage analytics events" ))); } @@ -180,13 +180,13 @@ pub async fn analytics_event_delete( &**pool, ) .await - .wrap_internal_err("failed to delete analytics event")?; + .internal_context("failed to delete analytics event")?; if !deleted { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } DBAnalyticsEvent::clear_cache(&redis) .await - .wrap_internal_err("failed to clear analytics event cache")?; + .internal_context("failed to clear analytics event cache")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/attribution.rs b/apps/labrinth/src/routes/internal/attribution.rs index 2ad386822e2..a952ba0f71d 100644 --- a/apps/labrinth/src/routes/internal/attribution.rs +++ b/apps/labrinth/src/routes/internal/attribution.rs @@ -1,7 +1,7 @@ use crate::util::error::ApiContext as _; use actix_web::{HttpRequest, delete, get, patch, post, web}; +use anyhow::anyhow; use chrono::{DateTime, Utc}; -use eyre::eyre; use serde::{Deserialize, Serialize}; use crate::auth::{UserWithScopes, get_user_from_headers}; @@ -126,7 +126,7 @@ pub async fn scan( Scopes::VERSION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let mut version_ids: Vec = body .version_ids @@ -152,10 +152,10 @@ pub async fn scan( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err("failed to fetch versions for attribution scan")?; + .internal_context("failed to fetch versions for attribution scan")?; if versions.len() != version_ids.len() { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let mut project_ids: Vec = @@ -171,14 +171,14 @@ pub async fn scan( "you do not have permission to upload versions to this project", ) .await - .wrap_api_err("validating can upload versions to project")?; + .api_context("validating can upload versions to project")?; } let project_ids = project_ids.iter().map(|id| id.0).collect::>(); let mut transaction = pool .begin() .await - .wrap_internal_err("failed to begin attribution scan transaction")?; + .internal_context("failed to begin attribution scan transaction")?; sqlx::query!( r#" @@ -190,7 +190,7 @@ pub async fn scan( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to remove attribution scan exemptions")?; + .internal_context("failed to remove attribution scan exemptions")?; let result = sqlx::query!( r#" @@ -204,18 +204,18 @@ pub async fn scan( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to queue version files for attribution scan")?; + .internal_context("failed to queue version files for attribution scan")?; transaction .commit() .await - .wrap_internal_err("failed to commit attribution scan transaction")?; + .internal_context("failed to commit attribution scan transaction")?; let version_ids = version_ids.into_iter().map(DBVersionId).collect::>(); DBVersion::clear_cache_ids(&version_ids, redis.as_ref()) .await - .wrap_internal_err("failed to clear version cache")?; + .internal_context("failed to clear version cache")?; Ok(web::Json(ScanResponse { queued_files: result.rows_affected(), @@ -240,7 +240,7 @@ async fn force_scan_file( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let file_id: DBFileId = path.into_inner().into(); let file = sqlx::query!( @@ -257,10 +257,10 @@ async fn force_scan_file( ) .fetch_optional(pool.as_ref()) .await - .wrap_internal_err("failed to fetch attribution scan file")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch attribution scan file")? + .not_found_context("resource not found")?; - let mut transaction = pool.begin().await.wrap_internal_err( + let mut transaction = pool.begin().await.internal_context( "failed to begin attribution file scan transaction", )?; @@ -273,7 +273,7 @@ async fn force_scan_file( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to remove attribution scan exemption")?; + .internal_context("failed to remove attribution scan exemption")?; let scan_summary = scan_file( &mut transaction, @@ -284,15 +284,15 @@ async fn force_scan_file( &file.url, ) .await - .wrap_internal_err("failed to scan file for attributions")?; + .internal_context("failed to scan file for attributions")?; - transaction.commit().await.wrap_internal_err( + transaction.commit().await.internal_context( "failed to commit attribution file scan transaction", )?; DBVersion::clear_cache_ids(&[file.version_id], redis.as_ref()) .await - .wrap_internal_err("failed to clear version cache")?; + .internal_context("failed to clear version cache")?; Ok(web::Json(scan_summary)) } @@ -323,13 +323,13 @@ pub async fn list( Scopes::VERSION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let requester_is_mod = scopes.contains(Scopes::MODERATION_READ); let project = DBProject::get_id(project_id, pool.as_ref(), redis.as_ref()) .await - .wrap_internal_err("fetching attribution project")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching attribution project")? + .not_found_context("resource not found")?; let (team_member, organization_team_member) = DBTeamMember::get_for_project_permissions( &project.inner, @@ -337,7 +337,7 @@ pub async fn list( pool.as_ref(), ) .await - .wrap_internal_err("failed to fetch project permissions")?; + .internal_context("failed to fetch project permissions")?; if !requester_is_mod && ProjectPermissions::get_permissions_by_scopes( scopes, @@ -346,7 +346,7 @@ pub async fn list( ) .is_none() { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to read versions for this project" ))); } @@ -366,7 +366,7 @@ pub async fn list( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err("failed to fetch attribution groups")?; + .internal_context("failed to fetch attribution groups")?; let group_ids: Vec = groups.iter().map(|g| g.id.0).collect(); @@ -394,7 +394,7 @@ pub async fn list( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err("failed to fetch attribution group files")? + .internal_context("failed to fetch attribution group files")? }; let override_files_on_platform = if requester_is_mod { @@ -423,9 +423,7 @@ pub async fn list( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err( - "failed to fetch override files already on platform", - )? + .internal_context("failed to fetch override files already on platform")? .into_iter() .map(|row| OverrideFileOnPlatformResponse { file_path: row.file_path, @@ -471,7 +469,7 @@ pub async fn list( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err("failed to fetch moderation external licenses")? + .internal_context("failed to fetch moderation external licenses")? .into_iter() .map(|row| { ( @@ -519,7 +517,7 @@ pub async fn list( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err("failed to fetch attribution group versions")?; + .internal_context("failed to fetch attribution group versions")?; rows.into_iter() .map(|v| VersionInfo { id: VersionId(v.id as u64), @@ -656,13 +654,13 @@ pub async fn update_group( Scopes::VERSION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !can_edit_attribution_group(pool.as_ref(), group_id, &user) .await - .wrap_api_err("checking edit attribution group")? + .api_context("checking edit attribution group")? { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "This attribution group cannot be edited", ))); } @@ -672,7 +670,7 @@ pub async fn update_group( AttributionResolutionKind::GloballyAllowed { .. } ) && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "Only moderators can set globally allowed attributions", ))); } @@ -680,7 +678,7 @@ pub async fn update_group( if body.attribution.moderation_status.is_some() && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "Only moderators can set attribution moderation status", ))); } @@ -705,15 +703,15 @@ pub async fn update_group( ) .execute(pool.as_ref()) .await - .wrap_internal_err("failed to update attribution group")?; + .internal_context("failed to update attribution group")?; if result.rows_affected() == 0 { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } clear_group_version_cache(pool.as_ref(), redis.as_ref(), &[group_id]) .await - .wrap_api_err("executing `clear_group_version_cache`")?; + .api_context("executing `clear_group_version_cache`")?; Ok(()) } @@ -746,7 +744,7 @@ pub async fn delete_groups( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("deleting database records for `delete_groups`")?; + .auth_context("deleting database records for `delete_groups`")?; let group_ids = body .groups @@ -785,7 +783,7 @@ pub async fn delete_all_groups( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("deleting database records for `delete_all_groups`")?; + .auth_context("deleting database records for `delete_all_groups`")?; let project_id = DBProjectId::from(body.project_id).0; let group_ids = sqlx::query_scalar!( @@ -798,7 +796,7 @@ pub async fn delete_all_groups( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err("failed to fetch project attribution groups")? + .internal_context("failed to fetch project attribution groups")? .into_iter() .map(|id| id.0) .collect::>(); @@ -818,7 +816,7 @@ async fn delete_attribution_groups( return Ok(()); } - let mut txn = pool.begin().await.wrap_internal_err( + let mut txn = pool.begin().await.internal_context( "failed to begin attribution group deletion transaction", )?; @@ -837,7 +835,7 @@ async fn delete_attribution_groups( ) .fetch_all(&mut txn) .await - .wrap_internal_err("failed to fetch attribution group versions")?; + .internal_context("failed to fetch attribution group versions")?; sqlx::query!( " @@ -848,7 +846,7 @@ async fn delete_attribution_groups( ) .execute(&mut txn) .await - .wrap_internal_err("failed to delete attribution group files")?; + .internal_context("failed to delete attribution group files")?; let result = sqlx::query!( " @@ -859,19 +857,19 @@ async fn delete_attribution_groups( ) .execute(&mut txn) .await - .wrap_internal_err("failed to delete attribution groups")?; + .internal_context("failed to delete attribution groups")?; if result.rows_affected() != group_ids.len() as u64 { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } - txn.commit().await.wrap_internal_err( + txn.commit().await.internal_context( "failed to commit attribution group deletion transaction", )?; DBVersion::clear_cache_ids(&version_ids, redis) .await - .wrap_internal_err("failed to clear version attribution cache")?; + .internal_context("failed to clear version attribution cache")?; Ok(()) } @@ -905,11 +903,11 @@ pub async fn assign( Scopes::VERSION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let sha1 = body.sha1.trim().to_lowercase(); if hex_to_bytes(&sha1).is_none() { - return Err(ApiError::Request(eyre::eyre!("invalid sha1 hex string",))); + return Err(ApiError::Request(anyhow!("invalid sha1 hex string",))); } let sha1_bytes = sha1.as_bytes().to_vec(); let project_id: DBProjectId = body.project_id.into(); @@ -926,8 +924,8 @@ pub async fn assign( ) .fetch_optional(pool.as_ref()) .await - .wrap_internal_err("failed to fetch source attribution group")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch source attribution group")? + .not_found_context("resource not found")?; let target_group_exists = sqlx::query_scalar!( " @@ -940,29 +938,29 @@ pub async fn assign( ) .fetch_one(pool.as_ref()) .await - .wrap_internal_err("failed to check target attribution group")?; + .internal_context("failed to check target attribution group")?; if !target_group_exists { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } if !can_edit_attribution_group(pool.as_ref(), source_group_id, &user) .await - .wrap_api_err("checking edit attribution group")? + .api_context("checking edit attribution group")? || !can_edit_attribution_group( pool.as_ref(), body.target_group_id, &user, ) .await - .wrap_api_err("checking edit attribution group")? + .api_context("checking edit attribution group")? { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "This attribution group cannot be edited", ))); } - let mut txn = pool.begin().await.wrap_internal_err( + let mut txn = pool.begin().await.internal_context( "failed to begin attribution assignment transaction", )?; @@ -996,10 +994,10 @@ pub async fn assign( ) .execute(&mut txn) .await - .wrap_internal_err("failed to insert assigned attribution file")?; + .internal_context("failed to insert assigned attribution file")?; if result.rows_affected() == 0 { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } sqlx::query!( @@ -1017,15 +1015,15 @@ pub async fn assign( ) .execute(&mut txn) .await - .wrap_internal_err("failed to remove old assigned attribution files")?; + .internal_context("failed to remove old assigned attribution files")?; - txn.commit().await.wrap_internal_err( + txn.commit().await.internal_context( "failed to commit attribution assignment transaction", )?; cleanup_empty_groups(pool.as_ref()) .await - .wrap_internal_err("failed to clean up empty attribution groups")?; + .internal_context("failed to clean up empty attribution groups")?; clear_project_sha1_version_cache( pool.as_ref(), @@ -1034,7 +1032,7 @@ pub async fn assign( &sha1_bytes, ) .await - .wrap_api_err("executing `clear_project_sha1_version_cache`")?; + .api_context("executing `clear_project_sha1_version_cache`")?; Ok(()) } @@ -1067,11 +1065,11 @@ pub async fn split( Scopes::VERSION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let sha1 = body.sha1.trim().to_lowercase(); if hex_to_bytes(&sha1).is_none() { - return Err(ApiError::Request(eyre::eyre!("invalid sha1 hex string",))); + return Err(ApiError::Request(anyhow!("invalid sha1 hex string",))); } let sha1_bytes = sha1.as_bytes().to_vec(); let project_id: DBProjectId = body.project_id.into(); @@ -1087,17 +1085,17 @@ pub async fn split( ) .fetch_optional(pool.as_ref()) .await - .wrap_internal_err("failed to fetch attribution file to split")?; + .internal_context("failed to fetch attribution file to split")?; let Some(existing) = existing else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; if !can_edit_attribution_group(pool.as_ref(), existing.group_id, &user) .await - .wrap_api_err("checking edit attribution group")? + .api_context("checking edit attribution group")? { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "This attribution group cannot be edited", ))); } @@ -1105,11 +1103,11 @@ pub async fn split( let mut txn = pool .begin() .await - .wrap_internal_err("failed to begin attribution split transaction")?; + .internal_context("failed to begin attribution split transaction")?; let new_group_id = generate_attribution_group_id(&mut txn) .await - .wrap_internal_err("failed to generate attribution group id")?; + .internal_context("failed to generate attribution group id")?; sqlx::query!( " @@ -1121,7 +1119,7 @@ pub async fn split( ) .execute(&mut txn) .await - .wrap_internal_err("failed to insert split attribution group")?; + .internal_context("failed to insert split attribution group")?; sqlx::query!( " @@ -1135,15 +1133,15 @@ pub async fn split( ) .execute(&mut txn) .await - .wrap_internal_err("failed to move attribution file to split group")?; + .internal_context("failed to move attribution file to split group")?; txn.commit() .await - .wrap_internal_err("failed to commit attribution split transaction")?; + .internal_context("failed to commit attribution split transaction")?; cleanup_empty_groups(pool.as_ref()) .await - .wrap_internal_err("failed to clean up empty attribution groups")?; + .internal_context("failed to clean up empty attribution groups")?; clear_project_sha1_version_cache( pool.as_ref(), @@ -1152,7 +1150,7 @@ pub async fn split( &sha1_bytes, ) .await - .wrap_api_err("executing `clear_project_sha1_version_cache`")?; + .api_context("executing `clear_project_sha1_version_cache`")?; Ok(()) } @@ -1177,11 +1175,11 @@ async fn clear_group_version_cache( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch attribution group versions")?; + .internal_context("failed to fetch attribution group versions")?; DBVersion::clear_cache_ids(&version_ids, redis) .await - .wrap_internal_err("failed to clear version attribution cache")?; + .internal_context("failed to clear version attribution cache")?; Ok(()) } @@ -1206,11 +1204,11 @@ async fn clear_project_sha1_version_cache( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch attribution file versions")?; + .internal_context("failed to fetch attribution file versions")?; DBVersion::clear_cache_ids(&version_ids, redis) .await - .wrap_internal_err("failed to clear version attribution cache")?; + .internal_context("failed to clear version attribution cache")?; Ok(()) } @@ -1230,8 +1228,8 @@ async fn can_edit_attribution_group( ) .fetch_optional(pool) .await - .wrap_internal_err("failed to fetch attribution group")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch attribution group")? + .not_found_context("resource not found")?; ensure_can_upload_versions_to_project( pool, @@ -1240,7 +1238,7 @@ async fn can_edit_attribution_group( "you do not have permission to edit this attribution group", ) .await - .wrap_api_err("validating can upload versions to project")?; + .api_context("validating can upload versions to project")?; let attribution: Option = group .attribution @@ -1271,13 +1269,13 @@ async fn ensure_can_upload_versions_to_project( pool, ) .await - .wrap_internal_err("failed to fetch project team member")?; + .internal_context("failed to fetch project team member")?; let organization = DBOrganization::get_associated_organization_project_id( project_id, pool, ) .await - .wrap_internal_err("failed to fetch associated organization")?; + .internal_context("failed to fetch associated organization")?; let organization_team_member = if let Some(organization) = organization { DBTeamMember::get_from_user_id( @@ -1286,7 +1284,7 @@ async fn ensure_can_upload_versions_to_project( pool, ) .await - .wrap_internal_err("failed to fetch organization team member")? + .internal_context("failed to fetch organization team member")? } else { None }; @@ -1299,7 +1297,7 @@ async fn ensure_can_upload_versions_to_project( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::UPLOAD_VERSION) { - return Err(ApiError::Auth(eyre!(permission_error))); + return Err(ApiError::Auth(anyhow!(permission_error))); } Ok(()) @@ -1316,7 +1314,7 @@ async fn cleanup_empty_groups(pool: &PgPool) -> Result<(), ApiError> { ) .execute(pool) .await - .wrap_internal_err("failed to delete empty attribution groups")?; + .internal_context("failed to delete empty attribution groups")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/billing.rs b/apps/labrinth/src/routes/internal/billing.rs index d3cb8004291..4e463b8b779 100644 --- a/apps/labrinth/src/routes/internal/billing.rs +++ b/apps/labrinth/src/routes/internal/billing.rs @@ -28,6 +28,7 @@ use crate::util::error::Context as _; use crate::util::stripe::StripeContext as _; use ::stripe_webhook::{EventObject, Webhook, WebhookError}; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, post, web}; +use anyhow::anyhow; use ariadne::ids::base62_impl::{parse_base62, to_base62}; use chrono::{Duration, Utc}; use rust_decimal::Decimal; @@ -86,7 +87,7 @@ pub async fn products( &**pool, &redis, ) .await - .wrap_internal_err("fetching query product with prices from Redis")?; + .internal_context("fetching query product with prices from Redis")?; let products = products .into_iter() @@ -145,7 +146,7 @@ pub async fn subscriptions( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let db_subscriptions = user_subscription_item::DBUserSubscription::get_all_user( @@ -153,7 +154,7 @@ pub async fn subscriptions( if scopes.contains(Scopes::ADMIN_READ) { user_id.into() } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot see the subscriptions of other users!", ))); } @@ -163,14 +164,14 @@ pub async fn subscriptions( &**pool, ) .await - .wrap_internal_err("fetching user subscriptions from database")?; + .internal_context("fetching user subscriptions from database")?; let mut subscriptions = Vec::with_capacity(db_subscriptions.len()); for subscription in db_subscriptions { let next_charge_tax_amount = DBCharge::get_open_subscription(subscription.id, &**pool) .await - .wrap_internal_err("fetching charge from database")? + .internal_context("fetching charge from database")? .map(|charge| charge.tax_amount); subscriptions.push(UserSubscriptionWithNextChargeTaxAmount { @@ -224,23 +225,23 @@ pub async fn refund_charge( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (id,) = info.into_inner(); if !scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to refund a subscription!", ))); } if let Some(charge) = DBCharge::get(id.into(), &**pool) .await - .wrap_internal_err("fetching charge from database")? + .internal_context("fetching charge from database")? { let refunds = DBCharge::get_children(id.into(), &**pool) .await - .wrap_internal_err("fetching charges from database")?; + .internal_context("fetching charges from database")?; let refunds = -refunds .into_iter() .filter_map(|x| match x.status { @@ -262,13 +263,13 @@ pub async fn refund_charge( }; if charge.status != ChargeStatus::Succeeded { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "This charge cannot be refunded!", ))); } if (refundable - refund_amount) < 0 { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot refund more than the amount of the charge!", ))); } @@ -299,7 +300,7 @@ pub async fn refund_charge( .expand(["payment_method".to_owned()]) .send(&**stripe_client) .await - .wrap_stripe_err( + .stripe_context( "communicating with payment provider", )?; @@ -308,7 +309,7 @@ pub async fn refund_charge( .and_then(|x| x.into_object()) .and_then(|x| x.billing_details.address) else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Couldn't retrieve billing address for payment method!" .to_owned(), ))); @@ -319,10 +320,10 @@ pub async fn refund_charge( &**pool, ) .await - .wrap_api_err( + .api_context( "executing `product_info_by_product_price_id`", )? - .wrap_request_err_with(|| { + .request_context_with(|| { "could not find product tax info for price ID!" .to_owned() })? @@ -341,7 +342,7 @@ pub async fn refund_charge( .zip(charge.tax_transaction_version) .zip(charge.tax_platform_accounting_time) else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Charge is missing full tax information. Please wait for the original charge to be synchronized with the tax processor." .to_owned(), ))); @@ -354,7 +355,7 @@ pub async fn refund_charge( .expand(["balance_transaction".to_owned()]) .send(&**stripe_client) .await - .wrap_stripe_err( + .stripe_context( "communicating with payment provider", )?; @@ -385,13 +386,13 @@ pub async fn refund_charge( Some(anrok_txn_result), ) } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Charge does not have attached payment id!", ))); } } PaymentPlatform::None => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "This charge was not processed via a payment platform." .to_owned(), ))); @@ -402,11 +403,11 @@ pub async fn refund_charge( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let charge_id = generate_charge_id(&mut transaction) .await - .wrap_internal_err("generating charge ID")?; + .internal_context("generating charge ID")?; DBCharge { id: charge_id, user_id: charge.user_id, @@ -436,7 +437,7 @@ pub async fn refund_charge( } .upsert(&mut transaction) .await - .wrap_internal_err("generating charge ID")?; + .internal_context("generating charge ID")?; if body.0.unprovision.unwrap_or(false) && let Some(subscription_id) = charge.subscription_id @@ -444,7 +445,7 @@ pub async fn refund_charge( let open_charge = DBCharge::get_open_subscription(subscription_id, &**pool) .await - .wrap_internal_err("fetching charge from database")?; + .internal_context("fetching charge from database")?; if let Some(mut open_charge) = open_charge { open_charge.status = ChargeStatus::Cancelled; open_charge.due = Utc::now(); @@ -452,27 +453,27 @@ pub async fn refund_charge( open_charge .upsert(&mut transaction) .await - .wrap_internal_err("cancelling subscription charge")?; + .internal_context("cancelling subscription charge")?; } } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; if let Some(Err(error)) = anrok_result { if let anrok::AnrokError::Conflict(m) = &error && m.contains("transactionExpectedVersionMismatch") { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "This refund has been processed on Stripe's end, but not on the tax processor's end. The tax transaction has been modified externally since its creation. \ This is likely caused by a change in nexus for the customer's jurisdiction, which lead to a new tax amount paid by the seller being calculated on the transaction. \ Manual intervention is required to verify the tax transaction on the platform's end and update the refund's tax transaction record." .to_owned(), ))); } else { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "This refund has been processed on Stripe's end, but not on the tax processor's end. An unexpected error occurred, preventing the refund transaction from being processed \ on the tax platform's end. Error: {error}" )))); @@ -507,12 +508,12 @@ pub async fn reprocess_charge_tax( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (id,) = info.into_inner(); if !scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to reprocess a tax transaction!", ))); } @@ -520,39 +521,39 @@ pub async fn reprocess_charge_tax( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let charge_refund = charge_item::DBCharge::get(id.into(), &mut txn) .await - .wrap_internal_err("fetching charge from database")? - .wrap_not_found_err_with(|| "resource not found")?; + .internal_context("fetching charge from database")? + .not_found_context_with(|| "resource not found")?; let Some(parent_charge_id) = charge_refund.parent_charge_id else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "This charge does not have a parent!", ))); }; match charge_refund.tax_platform_id { Some(_) => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Refund charge already has a tax transaction ID!", ))); } None => { let charge = charge_item::DBCharge::get(parent_charge_id, &mut txn) .await - .wrap_internal_err("fetching charge from database")? - .wrap_not_found_err_with(|| "resource not found")?; + .internal_context("fetching charge from database")? + .not_found_context_with(|| "resource not found")?; let payment_platform_id = charge .payment_platform_id - .wrap_internal_err_with( + .internal_context_with( || "parent charge is missing a payment platform ID", )? .parse::() - .map_err(|err| eyre::eyre!(err)) - .wrap_internal_err( + .map_err(|err| anyhow!(err)) + .internal_context( "parent charge has an invalid payment platform ID.", )?; @@ -560,14 +561,14 @@ pub async fn reprocess_charge_tax( .expand(["payment_method".to_owned()]) .send(&**stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; let Some(billing_address) = pi .payment_method .and_then(|x| x.into_object()) .and_then(|x| x.billing_details.address) else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Missing billing address for payment method.".to_owned(), ))); }; @@ -575,10 +576,10 @@ pub async fn reprocess_charge_tax( let tax_id = product_info_by_product_price_id(charge.price_id, &mut txn) .await - .wrap_api_err( + .api_context( "executing `product_info_by_product_price_id`", )? - .wrap_request_err_with(|| { + .request_context_with(|| { "could not find product tax info for price ID!" .to_owned() })? @@ -594,19 +595,19 @@ pub async fn reprocess_charge_tax( .zip(charge.tax_transaction_version) .zip(charge.tax_platform_accounting_time) else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Charge is missing full tax information. Please wait for the original charge to be synchronized with the tax processor." .to_owned(), ))); }; let refund_id = - charge_refund.payment_platform_id.wrap_internal_err_with( + charge_refund.payment_platform_id.internal_context_with( || "refund charge is missing a payment platform ID!", )?; let refund_id = RefundId::from_str(&refund_id) - .map_err(|err| eyre::eyre!(err)) - .wrap_internal_err("invalid refund ID!")?; + .map_err(|err| anyhow!(err)) + .internal_context("invalid refund ID!")?; let anrok_txn_result = anrok_client .negate_or_create_partial_negation( @@ -643,7 +644,7 @@ pub async fn reprocess_charge_tax( .await; if let Err(error) = anrok_txn_result { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "There was an error processing the tax transaction: {error}. Please make sure the version has been incremented in case of an external modification." )))); } @@ -652,7 +653,7 @@ pub async fn reprocess_charge_tax( txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().finish()) } @@ -696,7 +697,7 @@ async fn refresh_charge_tax( let quote = quote_charge_tax(pool, redis, stripe_client, anrok_client, charge) .await - .wrap_api_err("calculating tax amount for resubscription")?; + .api_context("calculating tax amount for resubscription")?; charge.tax_amount = quote.tax_amount; charge.tax_last_updated = Some(Utc::now()); @@ -735,7 +736,7 @@ pub async fn edit_subscription( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; #[derive(Clone, Copy, PartialEq, Eq)] enum PaymentRequirement { @@ -756,8 +757,8 @@ pub async fn edit_subscription( &mut *txn, ) .await - .wrap_internal_err("fetching product from database")? - .wrap_request_err_with(|| { + .internal_context("fetching product from database")? + .request_context_with(|| { "could not link new product price to product.".to_owned() })?; let current_product = product_item::DBProduct::get( @@ -765,8 +766,8 @@ pub async fn edit_subscription( &mut *txn, ) .await - .wrap_internal_err("fetching product from database")? - .wrap_request_err_with(|| { + .internal_context("fetching product from database")? + .request_context_with(|| { "could not link current product price to product.".to_owned() })?; @@ -819,7 +820,7 @@ pub async fn edit_subscription( let current_amount = match ¤t_price.prices { Price::OneTime { price } => *price, Price::Recurring { intervals } => { - *intervals.get(&duration).wrap_request_err_with(|| { + *intervals.get(&duration).request_context_with(|| { "could not find a valid price for the user's duration" .to_owned() })? @@ -829,7 +830,7 @@ pub async fn edit_subscription( let amount = match &new_product_price.prices { Price::OneTime { price } => *price, Price::Recurring { intervals } => { - *intervals.get(&duration).wrap_request_err_with(|| { + *intervals.get(&duration).request_context_with(|| { "could not find a valid price for the user's duration" .to_owned() })? @@ -841,7 +842,7 @@ pub async fn edit_subscription( let proration = (Decimal::from(amount - current_amount) * complete) .floor() .to_i32() - .wrap_request_err_with(|| { + .request_context_with(|| { "could not convert proration to i32".to_owned() })?; @@ -864,27 +865,27 @@ pub async fn edit_subscription( let subscription = user_subscription_item::DBUserSubscription::get(id.into(), &**pool) .await - .wrap_internal_err("fetching user subscription from database")? - .wrap_not_found_err_with(|| "resource not found")?; + .internal_context("fetching user subscription from database")? + .not_found_context_with(|| "resource not found")?; if subscription.user_id != user.id.into() && !scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut open_charge = charge_item::DBCharge::get_open_subscription( subscription.id, &mut transaction, ) .await - .wrap_internal_err("fetching charge from database")? - .wrap_request_err_with(|| { + .internal_context("fetching charge from database")? + .request_context_with(|| { "could not find open charge for this subscription".to_string() })?; @@ -893,8 +894,8 @@ pub async fn edit_subscription( &mut transaction, ) .await - .wrap_internal_err("fetching product price from database")? - .wrap_request_err_with(|| { + .internal_context("fetching product price from database")? + .request_context_with(|| { "could not find current product price".to_string() })?; @@ -969,17 +970,17 @@ pub async fn edit_subscription( &mut transaction, ) .await - .wrap_internal_err("fetching product prices from database")? + .internal_context("fetching product prices from database")? .into_iter() .find(|x| x.currency_code == current_price.currency_code) - .wrap_request_err_with(|| { + .request_context_with(|| { "could not find a valid price for your currency code!" .to_owned() })?; // The price is the same! The request likely asked to edit the product to what it already is. if new_product_price.id == current_price.id { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot use the existing product when modifying a subscription! Modifications to only the billing interval aren't yet supported." .to_owned(), ))); @@ -992,7 +993,7 @@ pub async fn edit_subscription( } let currency = parse_currency(¤t_price.currency_code) - .wrap_request_err("invalid currency code".to_string())?; + .request_context("invalid currency code".to_string())?; // The next charge is an expiring charge, so we are promoting the subscription to a paid product. // Instead of doing a proration (since the product is likely free) we either: @@ -1003,8 +1004,8 @@ pub async fn edit_subscription( // // ..depending on the special cases defined in `promotion_payment_requirement`. if open_charge.status == ChargeStatus::Expiring { - let new_region = region.wrap_request_err_with(|| "you need to specify a region when promoting an expiring charge.".to_owned())?; - let new_interval = interval.wrap_request_err_with(|| "you need to specify an interval when promoting an expiring charge.".to_owned())?; + let new_region = region.request_context_with(|| "you need to specify a region when promoting an expiring charge.".to_owned())?; + let new_interval = interval.request_context_with(|| "you need to specify an interval when promoting an expiring charge.".to_owned())?; let req = promotion_payment_requirement( &mut transaction, @@ -1012,7 +1013,7 @@ pub async fn edit_subscription( &new_product_price, ) .await - .wrap_api_err("executing `promotion_payment_requirement`")?; + .api_context("executing `promotion_payment_requirement`")?; if dry { // Note: we aren't committing the transaction here and it will be aborted. @@ -1026,7 +1027,7 @@ pub async fn edit_subscription( let payment_request_type = PaymentRequestType::from_stripe_id(payment_method) - .wrap_request_err_with(|| { + .request_context_with(|| { "invalid payment method ID".to_owned() })?; @@ -1053,14 +1054,14 @@ pub async fn edit_subscription( }, ) .await - .wrap_api_err("creating subscription charge")?; + .api_context("creating subscription charge")?; Some(results) } else { /* open_charge.status = ChargeStatus::Open; open_charge.payment_platform = PaymentPlatform::Stripe; - open_charge.amount = new_product_price.prices.get_interval(new_interval).wrap_request_err_with(|| "could not find a valid price for the user's duration".to_owned())?; + open_charge.amount = new_product_price.prices.get_interval(new_interval).request_context_with(|| "could not find a valid price for the user's duration".to_owned())?; open_charge.currency_code = new_product_price.currency_code; open_charge.subscription_interval = Some(new_interval); open_charge.price_id = new_product_price.id; @@ -1079,7 +1080,7 @@ pub async fn edit_subscription( ¤t_price, &new_product_price, ) - .wrap_api_err("executing `proration_amount`")?; + .api_context("executing `proration_amount`")?; if dry { // Note: we aren't committing the transaction here and it will be aborted. @@ -1144,7 +1145,7 @@ pub async fn edit_subscription( }, ) .await - .wrap_api_err("creating subscription charge")?; + .api_context("creating subscription charge")?; Some(results) } @@ -1158,7 +1159,7 @@ pub async fn edit_subscription( interval, .. } if region.is_some() || interval.is_some() => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "It is not currently possible to only modify the region or interval of a subscription".to_owned(), ))); } @@ -1167,13 +1168,13 @@ pub async fn edit_subscription( payment_method: None, .. } => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "A known payment method is required at this point to calculate tax information".to_owned(), ))); } _ => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Unexpected combination of fields in subscription PATCH request. Please either only specify `cancelled`, or specify `product` \ alongside optionally specifying a `region` and `interval`. In some cases, you may be required to provide `region` and `interval`.".to_owned(), ))); @@ -1201,11 +1202,11 @@ pub async fn edit_subscription( open_charge .upsert(&mut transaction) .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } if let Some(PaymentBootstrapResults { @@ -1249,7 +1250,7 @@ pub async fn user_customer( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let customer_id = get_or_create_customer( user.id, @@ -1260,7 +1261,7 @@ pub async fn user_customer( &redis, ) .await - .wrap_api_err("fetching or creating Stripe customer")?; + .api_context("fetching or creating Stripe customer")?; let customer = retrieve_customer(&stripe_client, &customer_id, &[]).await?; Ok(HttpResponse::Ok().json(customer)) @@ -1294,7 +1295,7 @@ pub async fn charges( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let charges = crate::database::models::charge_item::DBCharge::get_from_user( @@ -1302,7 +1303,7 @@ pub async fn charges( if scopes.contains(Scopes::ADMIN_READ) { user_id.into() } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot see the subscriptions of other users!", ))); } @@ -1312,7 +1313,7 @@ pub async fn charges( &**pool, ) .await - .wrap_internal_err("fetching user charges from database")?; + .internal_context("fetching user charges from database")?; Ok(HttpResponse::Ok().json( charges @@ -1363,7 +1364,7 @@ pub async fn add_payment_method_flow( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let customer = get_or_create_customer( user.id, @@ -1374,7 +1375,7 @@ pub async fn add_payment_method_flow( &redis, ) .await - .wrap_api_err("fetching or creating Stripe customer")?; + .api_context("fetching or creating Stripe customer")?; let mut automatic_payment_methods = CreateSetupIntentAutomaticPaymentMethods::new(true); @@ -1386,7 +1387,7 @@ pub async fn add_payment_method_flow( .automatic_payment_methods(automatic_payment_methods) .send(&**stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; Ok(HttpResponse::Ok().json(serde_json::json!({ "client_secret": intent.client_secret @@ -1421,12 +1422,12 @@ pub async fn edit_payment_method( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (id,) = info.into_inner(); let Some(payment_method_id) = parse_payment_method_id(&id) else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; let customer = get_or_create_customer( @@ -1438,12 +1439,12 @@ pub async fn edit_payment_method( &redis, ) .await - .wrap_api_err("fetching or creating Stripe customer")?; + .api_context("fetching or creating Stripe customer")?; let payment_method = RetrievePaymentMethod::new(payment_method_id) .send(&**stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; if payment_method .customer @@ -1460,7 +1461,7 @@ pub async fn edit_payment_method( Ok(HttpResponse::NoContent().finish()) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1487,12 +1488,12 @@ pub async fn remove_payment_method( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (id,) = info.into_inner(); let Some(payment_method_id) = parse_payment_method_id(&id) else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; let customer = get_or_create_customer( @@ -1504,12 +1505,12 @@ pub async fn remove_payment_method( &redis, ) .await - .wrap_api_err("fetching or creating Stripe customer")?; + .api_context("fetching or creating Stripe customer")?; let payment_method = RetrievePaymentMethod::new(payment_method_id.clone()) .send(&**stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; let user_subscriptions = user_subscription_item::DBUserSubscription::get_all_user( @@ -1517,7 +1518,7 @@ pub async fn remove_payment_method( &**pool, ) .await - .wrap_internal_err("fetching user subscriptions from database")?; + .internal_context("fetching user subscriptions from database")?; if user_subscriptions .iter() @@ -1534,7 +1535,7 @@ pub async fn remove_payment_method( }) .unwrap_or(false) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You may not remove the default payment method if you have active subscriptions!", ))); } @@ -1549,7 +1550,7 @@ pub async fn remove_payment_method( DetachPaymentMethod::new(payment_method_id.clone()) .send(&**stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; if let Some(owner_id) = payment_method.customer.map(|x| x.into_id()) && let Err(err) = promote_default_payment_method( @@ -1569,7 +1570,7 @@ pub async fn remove_payment_method( Ok(HttpResponse::NoContent().finish()) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1598,7 +1599,7 @@ pub async fn payment_methods( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if let Some(customer_id) = user .stripe_customer_id @@ -1650,7 +1651,7 @@ pub async fn active_servers( .get("X-Master-Key") .is_none_or(|it| it.as_bytes() != master_key.as_bytes()) { - return Err(ApiError::Auth(eyre::eyre!("Invalid master key",))); + return Err(ApiError::Auth(anyhow!("Invalid master key",))); } let servers = user_subscription_item::DBUserSubscription::get_all_servers( @@ -1658,7 +1659,7 @@ pub async fn active_servers( &**pool, ) .await - .wrap_internal_err("fetching user subscriptions from database")?; + .internal_context("fetching user subscriptions from database")?; let server_ids = servers .into_iter() @@ -1764,7 +1765,7 @@ pub async fn initiate_payment( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let payment_request = payment_request.into_inner(); @@ -1772,7 +1773,7 @@ pub async fn initiate_payment( .existing_payment_intent .map(|id| { parse_stripe_id::(&id, &["pi_"]) - .wrap_request_err("invalid existing payment intent id") + .request_context("invalid existing payment intent id") }) .transpose()?; @@ -1792,7 +1793,7 @@ pub async fn initiate_payment( payment_request.charge, ) .await - .wrap_api_err( + .api_context( "executing `AttachedCharge::from_charge_request_type`", )?, currency: CurrencyMode::Infer, @@ -1800,7 +1801,7 @@ pub async fn initiate_payment( }, ) .await - .wrap_api_err("executing `AttachedCharge::from_charge_request_type`")?; + .api_context("executing `AttachedCharge::from_charge_request_type`")?; match results.new_payment_intent { Some(payment_intent) => { @@ -1888,7 +1889,7 @@ pub async fn stripe_webhook( user_id, pool, redis, ) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? else { break 'metadata; }; @@ -1930,14 +1931,14 @@ pub async fn stripe_webhook( charge_id, pool, ) .await - .wrap_internal_err("fetching charge from database")? + .internal_context("fetching charge from database")? { let Some(price) = product_item::DBProductPrice::get( charge.price_id, pool, ) .await - .wrap_internal_err( + .internal_context( "fetching product price from database", )? else { @@ -1949,7 +1950,7 @@ pub async fn stripe_webhook( pool, ) .await - .wrap_internal_err("fetching product from database")? + .internal_context("fetching product from database")? else { break 'metadata; }; @@ -1960,7 +1961,7 @@ pub async fn stripe_webhook( Some(payment_intent_id.to_string()); charge.tax_amount = tax_amount; charge.tax_platform_id = None; - charge.upsert(transaction).await.wrap_internal_err( + charge.upsert(transaction).await.internal_context( "updating payment intent charge", )?; @@ -1970,7 +1971,7 @@ pub async fn stripe_webhook( subscription_id, pool, ) - .await.wrap_internal_err("fetching user subscription from database")?; + .await.internal_context("fetching user subscription from database")?; let Some(mut subscription) = maybe_subscription else { @@ -1990,18 +1991,16 @@ pub async fn stripe_webhook( subscription.price_id = charge.price_id; } ChargeType::Refund => { - return Err(ApiError::Internal( - eyre::eyre!( - "invalid charge type `Refund` for payment intent", - ), - )); + return Err(ApiError::Internal(anyhow!( + "invalid charge type `Refund` for payment intent", + ))); } } subscription .upsert(transaction) .await - .wrap_internal_err("upserting subscription")?; + .internal_context("upserting subscription")?; ( charge, @@ -2029,7 +2028,7 @@ pub async fn stripe_webhook( let Some(price) = product_item::DBProductPrice::get(price_id, pool) .await - .wrap_internal_err( + .internal_context( "fetching product price from database", )? else { @@ -2041,7 +2040,7 @@ pub async fn stripe_webhook( pool, ) .await - .wrap_internal_err("fetching product from database")?; + .internal_context("fetching product from database")?; let Some(product) = maybe_product else { break 'metadata; @@ -2067,7 +2066,7 @@ pub async fn stripe_webhook( break 'metadata; }; - let subscription = if let Some(mut subscription) = user_subscription_item::DBUserSubscription::get(subscription_id, pool).await.wrap_internal_err("fetching user subscription from database")? { + let subscription = if let Some(mut subscription) = user_subscription_item::DBUserSubscription::get(subscription_id, pool).await.internal_context("fetching user subscription from database")? { subscription.status = SubscriptionStatus::Unprovisioned; subscription.price_id = price_id; subscription.interval = interval; @@ -2089,7 +2088,7 @@ pub async fn stripe_webhook( subscription .upsert(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "upserting subscription", )?; } @@ -2135,7 +2134,7 @@ pub async fn stripe_webhook( charge .upsert(&mut *transaction) .await - .wrap_internal_err("upserting charge")?; + .internal_context("upserting charge")?; } (charge, price, product, subscription, new_region) @@ -2153,7 +2152,7 @@ pub async fn stripe_webhook( }); } - Err(ApiError::Internal(eyre::eyre!( + Err(ApiError::Internal(anyhow!( "payment intent is missing required metadata", ))) } @@ -2182,7 +2181,7 @@ pub async fn stripe_webhook( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut metadata = get_payment_intent_metadata( payment_intent.id, @@ -2195,14 +2194,14 @@ pub async fn stripe_webhook( &mut transaction, ) .await - .wrap_api_err("fetching payment intent metadata")?; + .api_context("fetching payment intent metadata")?; if let Some(latest_charge) = payment_intent.latest_charge { let charge = RetrieveCharge::new(latest_charge.into_id()) .expand(["balance_transaction".to_owned()]) .send(&**stripe_client) .await - .wrap_stripe_err( + .stripe_context( "communicating with payment provider", )?; @@ -2215,7 +2214,7 @@ pub async fn stripe_webhook( .charge_item .upsert(&mut transaction) .await - .wrap_internal_err("upserting charge")?; + .internal_context("upserting charge")?; } } @@ -2241,7 +2240,7 @@ pub async fn stripe_webhook( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `get_payment_intent_metadata`")?; + .internal_context("querying database for `get_payment_intent_metadata`")?; } ProductMetadata::Pyro { ram, @@ -2267,7 +2266,7 @@ pub async fn stripe_webhook( let region = metadata.new_region.clone(); if region.is_none() { - return Err(ApiError::Internal(eyre::eyre!( + return Err(ApiError::Internal(anyhow!( "We attempted to promote a subscription with type=medal, which requires specifying \ a new region to move the server to. However, no new region was present in the payment \ intent metadata.".to_owned() @@ -2305,8 +2304,8 @@ pub async fn stripe_webhook( )) .header("X-Master-Key", &ENV.PYRO_API_KEY) .send() - .await.wrap_internal_err("sending HTTP request")? - .error_for_status().wrap_internal_err("sending HTTP request")?; + .await.internal_context("sending HTTP request")? + .error_for_status().internal_context("sending HTTP request")?; client .post(format!( @@ -2320,8 +2319,8 @@ pub async fn stripe_webhook( ) .json(&body) .send() - .await.wrap_internal_err("deserializing HTTP response")? - .error_for_status().wrap_internal_err("deserializing HTTP response")?; + .await.internal_context("deserializing HTTP response")? + .error_for_status().internal_context("deserializing HTTP response")?; // As the subscription has been promoted, this is now a Pyro subscription. // Ensure the metadata is properly updated. @@ -2397,10 +2396,10 @@ pub async fn stripe_webhook( }) })) .send() - .await.wrap_internal_err("sending HTTP request")? - .error_for_status().wrap_internal_err("sending HTTP request")? + .await.internal_context("sending HTTP request")? + .error_for_status().internal_context("sending HTTP request")? .json::() - .await.wrap_internal_err("deserializing HTTP response")?; + .await.internal_context("deserializing HTTP response")?; if let Some(ref mut subscription) = metadata.user_subscription_item @@ -2423,12 +2422,12 @@ pub async fn stripe_webhook( &mut transaction, ) .await - .wrap_internal_err("fetching charge from database")?; + .internal_context("fetching charge from database")?; let new_price = match metadata.product_price_item.prices { Price::OneTime { price } => price, Price::Recurring { intervals } => { - *intervals.get(&subscription.interval).wrap_internal_err_with(|| "could not find a valid price for the user's country" + *intervals.get(&subscription.interval).internal_context_with(|| "could not find a valid price for the user's country" .to_string())? } }; @@ -2469,13 +2468,13 @@ pub async fn stripe_webhook( charge .upsert(&mut transaction) .await - .wrap_internal_err("upserting charge")?; + .internal_context("upserting charge")?; } else if metadata.charge_item.status != ChargeStatus::Cancelled { let charge_id = generate_charge_id(&mut transaction) .await - .wrap_internal_err("generating charge ID")?; + .internal_context("generating charge ID")?; DBCharge { id: charge_id, user_id: metadata.user_item.id, @@ -2510,14 +2509,14 @@ pub async fn stripe_webhook( } .upsert(&mut transaction) .await - .wrap_internal_err("upserting subscription charge")?; + .internal_context("upserting subscription charge")?; }; subscription.status = SubscriptionStatus::Provisioned; subscription .upsert(&mut transaction) .await - .wrap_internal_err( + .internal_context( "updating subscription in database", )?; } @@ -2525,19 +2524,19 @@ pub async fn stripe_webhook( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::user_item::DBUser::clear_caches( &[(metadata.user_item.id, None)], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } EventObject::PaymentIntentProcessing(payment_intent) => { let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; get_payment_intent_metadata( payment_intent.id, payment_intent.amount, @@ -2549,17 +2548,17 @@ pub async fn stripe_webhook( &mut transaction, ) .await - .wrap_api_err("fetching payment intent metadata")?; + .api_context("fetching payment intent metadata")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } EventObject::PaymentIntentPaymentFailed(payment_intent) => { let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let metadata = get_payment_intent_metadata( payment_intent.id, @@ -2572,7 +2571,7 @@ pub async fn stripe_webhook( &mut transaction, ) .await - .wrap_api_err("fetching payment intent metadata")?; + .api_context("fetching payment intent metadata")?; if metadata.user_item.email.is_some() { let money = rusty_money::Money::from_minor( @@ -2602,7 +2601,7 @@ pub async fn stripe_webhook( } .insert(metadata.user_item.id, &mut transaction, &redis) .await - .wrap_internal_err( + .internal_context( "inserting payment failure notification", )?; } @@ -2610,7 +2609,7 @@ pub async fn stripe_webhook( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } EventObject::PaymentMethodAttached(payment_method) => { if let Some(customer_id) = @@ -2637,10 +2636,10 @@ pub async fn stripe_webhook( } } else if let Err(WebhookError::BadParse(err)) = result { return Err(ApiError::Internal( - eyre::eyre!(err).wrap_err("parsing webhook event"), + anyhow!(err).context("parsing webhook event"), )); } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Webhook signature validation failed!", ))); } @@ -2667,7 +2666,7 @@ async fn apply_credit_many( &mut *transaction, ) .await - .wrap_internal_err("fetching user subscriptions from database")?; + .internal_context("fetching user subscriptions from database")?; let provisioned_count = subs .iter() @@ -2696,8 +2695,8 @@ async fn apply_credit_many( &mut *transaction, ) .await - .wrap_internal_err("fetching charge from database")? - .wrap_request_err_with(|| { + .internal_context("fetching charge from database")? + .request_context_with(|| { format!( "could not find open charge for subscription `{}`", to_base62(subscription.id.0 as u64) @@ -2710,7 +2709,7 @@ async fn apply_credit_many( open_charge .upsert(&mut *transaction) .await - .wrap_internal_err("updating next due in database")?; + .internal_context("updating next due in database")?; credit_sub_ids.push(subscription.id); credit_user_ids.push(subscription.user_id); @@ -2731,7 +2730,7 @@ async fn apply_credit_many( } .insert(subscription.user_id, &mut *transaction, redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `apply_credit_many`", )?; } @@ -2747,8 +2746,8 @@ async fn apply_credit_many( &credit_next_dues, ) .await - .map_err(|err| eyre::eyre!(err)) - .wrap_internal_err("inserting subscription credits into database")?; + .map_err(|err| anyhow!(err)) + .internal_context("inserting subscription credits into database")?; Ok(()) } @@ -2799,10 +2798,10 @@ pub async fn credit( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to credit subscriptions!", ))); } @@ -2815,19 +2814,19 @@ pub async fn credit( } = body.into_inner(); if days <= 0 { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Days must be greater than zero", ))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; match target { CreditTarget::Subscriptions { subscription_ids } => { if subscription_ids.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You must specify at least one subscription id", ))); } @@ -2841,11 +2840,11 @@ pub async fn credit( message, ) .await - .wrap_api_err("crediting user subscriptions")?; + .api_context("crediting user subscriptions")?; } CreditTarget::Nodes { nodes } => { if nodes.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You must specify at least one node hostname", ))); } @@ -2854,7 +2853,7 @@ pub async fn credit( let ids = archon_client .get_servers_by_hostname(&hostname) .await - .wrap_internal_err( + .internal_context( "fetching servers by hostname from Archon", )?; server_ids.extend(ids.into_iter().map(|id| id.to_string())); @@ -2864,9 +2863,9 @@ pub async fn credit( &server_ids, &mut transaction, ) - .await.wrap_internal_err("fetching user subscriptions from database")?; + .await.internal_context("fetching user subscriptions from database")?; if subs.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "No subscriptions found for provided nodes", ))); } @@ -2880,20 +2879,20 @@ pub async fn credit( message, ) .await - .wrap_api_err("crediting server subscriptions")?; + .api_context("crediting server subscriptions")?; } CreditTarget::Region { region } => { let servers = archon_client .get_active_servers_by_region(®ion) .await - .wrap_internal_err("fetching servers from database")?; + .internal_context("fetching servers from database")?; let subs = user_subscription_item::DBUserSubscription::get_many_by_server_ids( &servers.into_iter().map(|id| id.to_string()).collect::>(), &mut transaction, ) - .await.wrap_internal_err("fetching user subscriptions from database")?; + .await.internal_context("fetching user subscriptions from database")?; if subs.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "No subscriptions found for provided region", ))); } @@ -2907,14 +2906,14 @@ pub async fn credit( message, ) .await - .wrap_api_err("crediting region subscriptions")?; + .api_context("crediting region subscriptions")?; } } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().finish()) } diff --git a/apps/labrinth/src/routes/internal/billing/payments.rs b/apps/labrinth/src/routes/internal/billing/payments.rs index 00a2c179522..3b4559187fe 100644 --- a/apps/labrinth/src/routes/internal/billing/payments.rs +++ b/apps/labrinth/src/routes/internal/billing/payments.rs @@ -10,6 +10,7 @@ use crate::routes::ApiError; use crate::util::anrok; use crate::util::error::{ApiContext as _, Context as _}; use crate::util::stripe::StripeContext as _; +use anyhow::anyhow; use xredis::RedisPool; use crate::database::PgPool; @@ -145,8 +146,8 @@ impl AttachedCharge { ChargeRequestType::Existing { id } => AttachedCharge::UseExisting { charge: DBCharge::get(id.into(), exec) .await - .wrap_internal_err("fetching charge from database")? - .wrap_request_err_with(|| { + .internal_context("fetching charge from database")? + .request_context_with(|| { "could not find charge".to_string() })?, }, @@ -259,7 +260,7 @@ pub async fn create_or_update_payment_intent( redis, ) .await - .wrap_api_err("fetching or creating Stripe customer")?; + .api_context("fetching or creating Stripe customer")?; if let Some(payment_intent_id) = &existing_payment_intent { ensure_payment_intent_owned_by( @@ -277,12 +278,12 @@ pub async fn create_or_update_payment_intent( payment_request_type: PaymentRequestType::PaymentMethod { id }, } => { let payment_method_id = parse_payment_method_id(id) - .wrap_request_err("invalid payment method id".to_string())?; + .request_context("invalid payment method id".to_string())?; RetrievePaymentMethod::new(payment_method_id) .send(stripe_client) .await - .wrap_stripe_err("communicating with payment provider")? + .stripe_context("communicating with payment provider")? } PaymentSession::Interactive { payment_request_type: @@ -291,18 +292,18 @@ pub async fn create_or_update_payment_intent( intent_uses_confirmation_token = true; let token: ConfirmationTokenId = - parse_stripe_id(token, &["ctoken_"]).wrap_request_err( + parse_stripe_id(token, &["ctoken_"]).request_context( "invalid confirmation token".to_string(), )?; let confirmation = RetrieveConfirmationToken::new(token) .send(stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; let preview = confirmation .payment_method_preview - .wrap_request_err_with(|| { + .request_context_with(|| { "confirmation token is missing payment method".to_string() })?; @@ -310,14 +311,14 @@ pub async fn create_or_update_payment_intent( } PaymentSession::AutomatedRenewal => { if attached_charge.as_charge().is_none() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Missing attached charge for automated renewal", ))); } get_default_payment_method(stripe_client, &customer_id) .await? - .wrap_request_err_with(|| { + .request_context_with(|| { "customer has no default payment method".to_string() })? } @@ -334,7 +335,7 @@ pub async fn create_or_update_payment_intent( CurrencyMode::Set(currency) => currency, CurrencyMode::Infer => { parse_currency(&infer_currency_code(user_country)) - .wrap_request_err("invalid currency code".to_string())? + .request_context("invalid currency code".to_string())? } }; @@ -368,7 +369,7 @@ pub async fn create_or_update_payment_intent( inferred_stripe_currency, ) .await - .wrap_api_err("deriving proration charge data")?; + .api_context("deriving proration charge data")?; charge_data.amount = amount; charge_data.charge_type = ChargeType::Proration; @@ -387,7 +388,7 @@ pub async fn create_or_update_payment_intent( inferred_stripe_currency, ) .await - .wrap_api_err("deriving promotion charge data")?, + .api_context("deriving promotion charge data")?, AttachedCharge::BaseUpon { product_id, interval, @@ -399,7 +400,7 @@ pub async fn create_or_update_payment_intent( inferred_stripe_currency, ) .await - .wrap_api_err("deriving base charge data")?, + .api_context("deriving base charge data")?, }; // Create an ephemeral transaction to calculate the tax amount if needed @@ -420,8 +421,8 @@ pub async fn create_or_update_payment_intent( pg, ) .await - .wrap_internal_err("fetching product tax identifier")? - .wrap_request_err_with(|| { + .internal_context("fetching product tax identifier")? + .request_context_with(|| { "missing product tax identifier for charge to continue" .to_owned() })?; @@ -430,7 +431,7 @@ pub async fn create_or_update_payment_intent( .billing_details .address .clone() - .wrap_request_err("finding billing details on payment method")?; + .request_context("finding billing details on payment method")?; let ephemeral_invoice = anrok_client .create_ephemeral_txn(&anrok::TransactionFields { @@ -446,7 +447,7 @@ pub async fn create_or_update_payment_intent( customer_name: None, }) .await - .wrap_internal_err("inserting database records for `create_or_update_payment_intent`")?; + .internal_context("inserting database records for `create_or_update_payment_intent`")?; ephemeral_invoice.tax_amount_to_collect }; @@ -464,7 +465,7 @@ pub async fn create_or_update_payment_intent( metadata.insert( MODRINTH_PAYMENT_METADATA.to_owned(), serde_json::to_string(&payment_metadata) - .wrap_request_err("inserting payment metadata into database")?, + .request_context("inserting payment metadata into database")?, ); } @@ -490,10 +491,10 @@ pub async fn create_or_update_payment_intent( let mut transaction = pg .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let charge_id = generate_charge_id(&mut transaction) .await - .wrap_internal_err("generating charge ID")?; + .internal_context("generating charge ID")?; metadata.insert( MODRINTH_CHARGE_ID.to_owned(), @@ -522,10 +523,10 @@ pub async fn create_or_update_payment_intent( let mut transaction = pg .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let charge_id = generate_charge_id(&mut transaction) .await - .wrap_internal_err("generating charge ID")?; + .internal_context("generating charge ID")?; metadata.insert( MODRINTH_CHARGE_ID.to_owned(), @@ -549,13 +550,13 @@ pub async fn create_or_update_payment_intent( let mut transaction = pg .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let charge_id = generate_charge_id(&mut transaction) .await - .wrap_internal_err("generating charge ID")?; + .internal_context("generating charge ID")?; let subscription_id = generate_user_subscription_id(&mut transaction) .await - .wrap_internal_err("generating charge ID")?; + .internal_context("generating charge ID")?; metadata.insert( MODRINTH_CHARGE_ID.to_owned(), @@ -584,9 +585,9 @@ pub async fn create_or_update_payment_intent( UpdatePaymentIntent::new(payment_intent_id) .amount(charge_data.amount + tax_amount) .currency( - charge_data.stripe_currency_code().wrap_api_err( - "converting charge currency for Stripe", - )?, + charge_data + .stripe_currency_code() + .api_context("converting charge currency for Stripe")?, ) .customer(customer_id.as_str()) .metadata(metadata); @@ -605,7 +606,7 @@ pub async fn create_or_update_payment_intent( update_payment_intent .send(stripe_client) .await - .wrap_stripe_err( + .stripe_context( "updating database records for `create_or_update_payment_intent`", )?; @@ -624,7 +625,7 @@ pub async fn create_or_update_payment_intent( charge_data.amount + tax_amount, charge_data .stripe_currency_code() - .wrap_api_err("converting charge currency for Stripe")?, + .api_context("converting charge currency for Stripe")?, ) .capture_method(PaymentIntentCaptureMethod::Automatic) .customer(customer_id.as_str()) @@ -641,7 +642,7 @@ pub async fn create_or_update_payment_intent( .set_payment_intent_session_options(intent) .send(stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; Ok(PaymentBootstrapResults { new_payment_intent: Some(payment_intent), @@ -677,7 +678,7 @@ pub async fn get_or_create_customer( let customer = create_customer .send(client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; sqlx::query!( " @@ -690,14 +691,14 @@ pub async fn get_or_create_customer( ) .execute(pool) .await - .wrap_internal_err("querying database for `get_or_create_customer`")?; + .internal_context("querying database for `get_or_create_customer`")?; crate::database::models::user_item::DBUser::clear_caches( &[(user_id.into(), None)], redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(customer.id) } @@ -712,16 +713,16 @@ fn payment_method_from_preview( preview: &stripe_payment::ConfirmationTokensResourcePaymentMethodPreview, ) -> Result { let mut value = serde_json::to_value(preview) - .wrap_internal_err("serializing payment method preview")?; + .internal_context("serializing payment method preview")?; let object = value .as_object_mut() - .wrap_internal_err("payment method preview is not an object")?; + .internal_context("payment method preview is not an object")?; object.insert("id".to_owned(), "pm_1PirTdJygY5LJFfKmPIaM1N1".into()); object.insert("created".to_owned(), 1723183475.into()); object.insert("livemode".to_owned(), false.into()); serde_json::from_value(value) - .wrap_internal_err("converting payment method preview") + .internal_context("converting payment method preview") } /// Checks that a payment intent exists and belongs to the Stripe customer. @@ -733,8 +734,7 @@ async fn ensure_payment_intent_owned_by( payment_intent_id: &PaymentIntentId, customer_id: &CustomerId, ) -> Result<(), ApiError> { - let not_found = - || ApiError::NotFound(eyre::eyre!("payment intent not found")); + let not_found = || ApiError::NotFound(anyhow!("payment intent not found")); let payment_intent = match RetrievePaymentIntent::new(payment_intent_id.clone()) @@ -745,7 +745,7 @@ async fn ensure_payment_intent_owned_by( Err(stripe::StripeError::Stripe(_, 404)) => return Err(not_found()), Err(err) => { return Err(err) - .wrap_stripe_err("communicating with payment provider"); + .stripe_context("communicating with payment provider"); } }; @@ -775,12 +775,12 @@ pub async fn retrieve_customer( let customer = request .send(client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; match customer { RetrieveCustomerReturned::Customer(customer) => Ok(customer), RetrieveCustomerReturned::DeletedCustomer(_) => Err(ApiError::Request( - eyre::eyre!("Stripe customer has been deleted"), + anyhow!("Stripe customer has been deleted"), )), } } @@ -795,7 +795,7 @@ pub async fn list_payment_methods( .limit(limit) .send(client) .await - .wrap_stripe_err("communicating with payment provider")? + .stripe_context("communicating with payment provider")? .data) } @@ -813,7 +813,7 @@ pub async fn set_default_payment_method( .invoice_settings(invoice_settings) .send(client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; Ok(()) } @@ -876,8 +876,8 @@ pub async fn quote_charge_tax( pg, ) .await - .wrap_api_err("fetching price")? - .wrap_internal_err("finding product tax identifier for price")?; + .api_context("fetching price")? + .internal_context("finding product tax identifier for price")?; let user = crate::database::models::user_item::DBUser::get_id( charge.user_id, @@ -885,18 +885,18 @@ pub async fn quote_charge_tax( redis, ) .await - .wrap_internal_err("fetching Stripe customer from database")? - .wrap_internal_err("finding Stripe customer in database")?; + .internal_context("fetching Stripe customer from database")? + .internal_context("finding Stripe customer in database")?; let stripe_customer_id: CustomerId = user .stripe_customer_id - .wrap_request_err("finding Stripe customer ID on user")? + .request_context("finding Stripe customer ID on user")? .parse() - .wrap_request_err("parsing user Stripe customer ID")?; + .request_context("parsing user Stripe customer ID")?; let payment_method = get_default_payment_method(stripe_client, &stripe_customer_id) .await? - .wrap_request_err_with(|| { + .request_context_with(|| { "customer has no default payment method".to_string() })?; @@ -908,7 +908,7 @@ pub async fn quote_charge_tax( retrieve_customer(stripe_client, &stripe_customer_id, &[]) .await? .address - .wrap_request_err_with(|| { + .request_context_with(|| { "couldn't get an address for the Stripe customer".to_owned() })? } @@ -930,7 +930,7 @@ pub async fn quote_charge_tax( customer_name: None, }) .await - .wrap_internal_err("calculating tax amount for charge")? + .internal_context("calculating tax amount for charge")? .tax_amount_to_collect; Ok(ChargeTaxQuote { @@ -1039,7 +1039,7 @@ struct ChargeData { impl ChargeData { pub fn stripe_currency_code(&self) -> Result { parse_currency(&self.currency_code) - .ok_or_else(|| ApiError::Request(eyre::eyre!( + .ok_or_else(|| ApiError::Request(anyhow!( format!("Invalid currency code '{}': could not convert to Stripe currency", &self.currency_code) ))) } @@ -1056,8 +1056,8 @@ async fn derive_charge_data_from_product_selector( let product = product_item::DBProduct::get(product_id.into(), pool) .await - .wrap_internal_err("fetching product from database")? - .wrap_request_err_with(|| { + .internal_context("fetching product from database")? + .request_context_with(|| { "specified product could not be found!".to_string() })?; @@ -1066,7 +1066,7 @@ async fn derive_charge_data_from_product_selector( product.id, pool, ) .await - .wrap_internal_err("fetching product prices from database")?; + .internal_context("fetching product prices from database")?; let price_item = if let Some(pos) = product_prices .iter() @@ -1078,7 +1078,7 @@ async fn derive_charge_data_from_product_selector( { product_prices.remove(pos) } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Could not find a valid price for the user's country", ))); }; @@ -1086,12 +1086,12 @@ async fn derive_charge_data_from_product_selector( let price = match price_item.prices { Price::OneTime { price } => price, Price::Recurring { ref intervals } => { - let interval = interval.wrap_request_err_with(|| { + let interval = interval.request_context_with(|| { "could not find a valid price for the user's country" .to_string() })?; - *intervals.get(&interval).wrap_request_err_with(|| { + *intervals.get(&interval).request_context_with(|| { "could not find a valid price for the user's country" .to_string() })? @@ -1107,7 +1107,7 @@ async fn derive_charge_data_from_product_selector( pool, ) .await - .wrap_internal_err("fetching user subscriptions from database")?; + .internal_context("fetching user subscriptions from database")?; let user_products = product_item::DBProductPrice::get_many( &user_subscriptions @@ -1118,13 +1118,13 @@ async fn derive_charge_data_from_product_selector( pool, ) .await - .wrap_internal_err("fetching product prices from database")?; + .internal_context("fetching product prices from database")?; if user_products .into_iter() .any(|x| x.product_id == product.id) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You are already subscribed to this product!", ))); } diff --git a/apps/labrinth/src/routes/internal/billing/update_subscriptions.rs b/apps/labrinth/src/routes/internal/billing/update_subscriptions.rs index 592d11a00aa..3185f830f3f 100644 --- a/apps/labrinth/src/routes/internal/billing/update_subscriptions.rs +++ b/apps/labrinth/src/routes/internal/billing/update_subscriptions.rs @@ -52,7 +52,7 @@ pub async fn update_many( let mut txn = pool .begin() .await - .wrap_internal_err("failed to begin transaction")?; + .internal_context("failed to begin transaction")?; // Only supports hosting subscriptions now, so gather the server IDs and // fetch the subscriptions from them @@ -66,7 +66,7 @@ pub async fn update_many( let found_subscriptions = DBUserSubscription::get_many_by_server_ids(&server_ids, &mut txn) .await - .wrap_internal_err("failed to fetch subscriptions to update")?; + .internal_context("failed to fetch subscriptions to update")?; let mut subscriptions_by_target = HashMap::::new(); @@ -107,12 +107,12 @@ pub async fn update_many( subscription .upsert(&mut txn) .await - .wrap_internal_err("updating uuid in database")?; + .internal_context("updating uuid in database")?; } txn.commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/blocked_users.rs b/apps/labrinth/src/routes/internal/blocked_users.rs index acffff0475b..bc431426f30 100644 --- a/apps/labrinth/src/routes/internal/blocked_users.rs +++ b/apps/labrinth/src/routes/internal/blocked_users.rs @@ -5,6 +5,7 @@ use crate::routes::ApiError; use crate::util::error::Context as _; use crate::util::guards::admin_key_guard; use actix_web::{get, web}; +use anyhow::anyhow; use ariadne::ids::base62_impl::parse_base62; use serde::Serialize; @@ -28,18 +29,18 @@ pub async fn block_status( let user_id = DBUserId( parse_base62(&user_id) - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("invalid user_id".to_string())? as i64, + .map_err(|err| anyhow!(err)) + .request_context("invalid user_id".to_string())? as i64, ); let target_id = DBUserId( parse_base62(&target_id) - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("invalid target_id".to_string())? as i64, + .map_err(|err| anyhow!(err)) + .request_context("invalid target_id".to_string())? as i64, ); let blocked = DBBlockedUser::is_blocked(user_id, target_id, &**pool) .await - .wrap_internal_err("checking whether user is blocked")?; + .internal_context("checking whether user is blocked")?; Ok(web::Json(BlockStatus { blocked })) } diff --git a/apps/labrinth/src/routes/internal/campaign.rs b/apps/labrinth/src/routes/internal/campaign.rs index 43aaee209e8..4375db4f474 100644 --- a/apps/labrinth/src/routes/internal/campaign.rs +++ b/apps/labrinth/src/routes/internal/campaign.rs @@ -1,8 +1,8 @@ use crate::util::error::ApiContext as _; use actix_web::{HttpRequest, get, post, web}; +use anyhow::anyhow; use base64::Engine; use chrono::{DateTime, Duration, Utc}; -use eyre::eyre; use hmac::{Hmac, KeyInit, Mac}; use reqwest::Method; use rust_decimal::Decimal; @@ -138,7 +138,7 @@ impl CampaignDonation { ) .fetch_optional(transaction) .await - .wrap_internal_err("inserting campaign donation")?; + .internal_context("inserting campaign donation")?; Ok(inserted.is_some()) } @@ -160,17 +160,17 @@ pub async fn tiltify_webhook( body: String, ) -> Result<(), ApiError> { verify_tiltify_webhook_signature(&req, &body) - .wrap_api_err("executing `verify_tiltify_webhook_signature`")?; + .api_context("executing `verify_tiltify_webhook_signature`")?; let raw_payload = serde_json::from_str::(&body) - .wrap_internal_err_with(|| eyre!("invalid Tiltify webhook JSON"))?; + .internal_context_with(|| anyhow!("invalid Tiltify webhook JSON"))?; // deserialize the JSON in the request handler, not in the params, // since if the JSON fails to deserialize then it's *our* fault, // not the caller's. let payload = TiltifyWebhook::deserialize(&raw_payload) - .wrap_internal_err_with(|| { - eyre!( + .internal_context_with(|| { + anyhow!( "invalid Tiltify webhook payload schema\n{}", serde_json::to_string_pretty(&raw_payload) .expect("serializing should not fail") @@ -182,10 +182,10 @@ pub async fn tiltify_webhook( let mut transaction = pool .begin() .await - .wrap_internal_err("beginning transaction")?; + .internal_context("beginning transaction")?; let id = generate_campaign_donation_id(&mut transaction) .await - .wrap_internal_err("generating campaign donation ID")?; + .internal_context("generating campaign donation ID")?; let mut donation = CampaignDonation { id, @@ -201,13 +201,15 @@ pub async fn tiltify_webhook( let username = payload.data.donor_name.clone(); let user = DBUser::get(&username, &**pool, &redis) .await - .wrap_err("fetching user from database")? - .wrap_err_with(|| { - eyre!("got donation for user '{username}' which does not exist") + .context("fetching user from database")? + .with_context(|| { + anyhow!( + "got donation for user '{username}' which does not exist" + ) })?; donation.user_id = Some(user.id); - eyre::Ok(username) + anyhow::Ok(username) } .await .inspect_err(|err| { @@ -220,10 +222,10 @@ pub async fn tiltify_webhook( let amount_usd = amount_raised_usd(&payload.data.amount, &payouts_queue) .await - .wrap_err("failed to get donation amount")?; + .context("failed to get donation amount")?; donation.amount_usd = Some(amount_usd); - eyre::Ok(amount_usd) + anyhow::Ok(amount_usd) } .await .inspect_err(|err| warn!("Failed to resolve donation amount: {err:?}")) @@ -240,13 +242,13 @@ pub async fn tiltify_webhook( let inserted = donation .insert(&mut transaction) .await - .wrap_internal_err("inserting donation")?; + .internal_context("inserting donation")?; if !inserted { transaction .commit() .await - .wrap_internal_err("committing duplicate donation transaction")?; + .internal_context("committing duplicate donation transaction")?; info!("Ignoring duplicate Tiltify webhook {}", payload.meta.id); return Ok(()); } @@ -254,12 +256,12 @@ pub async fn tiltify_webhook( transaction .commit() .await - .wrap_internal_err("committing transaction")?; + .internal_context("committing transaction")?; if let Some(user_id) = donation.user_id { DBUser::clear_caches(&[(user_id, username)], &redis) .await - .wrap_internal_err("clearing user caches")?; + .internal_context("clearing user caches")?; } Ok(()) @@ -273,40 +275,40 @@ fn verify_tiltify_webhook_signature( .headers() .get("X-Tiltify-Signature") .and_then(|x| x.to_str().ok()) - .wrap_request_err("missing Tiltify webhook signature")?; + .request_context("missing Tiltify webhook signature")?; let signature = base64::engine::general_purpose::STANDARD .decode(signature) - .wrap_request_err("invalid Tiltify webhook signature")?; + .request_context("invalid Tiltify webhook signature")?; let timestamp = req .headers() .get("X-Tiltify-Timestamp") .and_then(|x| x.to_str().ok()) - .wrap_request_err("missing Tiltify webhook timestamp")?; + .request_context("missing Tiltify webhook timestamp")?; let parsed_timestamp = DateTime::parse_from_rfc3339(timestamp) - .wrap_request_err("invalid Tiltify webhook timestamp")?; + .request_context("invalid Tiltify webhook timestamp")?; let parsed_timestamp = parsed_timestamp.with_timezone(&Utc); let age = Utc::now().signed_duration_since(parsed_timestamp); if age < -Duration::minutes(1) || age > Duration::minutes(1) { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "expired Tiltify webhook timestamp", ))); } if ENV.TILTIFY_WEBHOOK_SIGNING_KEY.is_empty() { - return Err(ApiError::Internal(eyre!( + return Err(ApiError::Internal(anyhow!( "TILTIFY_WEBHOOK_SIGNING_KEY must be set" ))); } let mut mac: Hmac = Hmac::new_from_slice(ENV.TILTIFY_WEBHOOK_SIGNING_KEY.as_bytes()) - .wrap_internal_err("initializing Tiltify webhook HMAC")?; + .internal_context("initializing Tiltify webhook HMAC")?; mac.update(timestamp.as_bytes()); mac.update(b"."); mac.update(body.as_bytes()); mac.verify_slice(&signature) - .wrap_request_err("invalid Tiltify webhook signature")?; + .request_context("invalid Tiltify webhook signature")?; Ok(()) } @@ -327,7 +329,7 @@ pub async fn pride_26( let mut redis_connection = redis .connect() .await - .wrap_internal_err("connecting to redis")?; + .internal_context("connecting to redis")?; let cache_key = redis .key() .entity(CAMPAIGN_INFO_CACHE_NAMESPACE, campaign_id); @@ -335,7 +337,7 @@ pub async fn pride_26( let cached = redis_connection .get_deserialized::(&cache_key) .await - .wrap_internal_err("getting cached campaign info")?; + .internal_context("getting cached campaign info")?; if let Some(cached) = &cached && !cached.is_stale() @@ -347,7 +349,7 @@ pub async fn pride_26( let access_token = tiltify .access_token() .await - .wrap_internal_err("fetching Tiltify access token")?; + .internal_context("fetching Tiltify access token")?; let url = format!( "https://v5api.tiltify.com/api/public/team_campaigns/{campaign_id}", ); @@ -356,23 +358,23 @@ pub async fn pride_26( .bearer_auth(&access_token) .send() .await - .wrap_internal_err("fetching campaign from Tiltify")? + .internal_context("fetching campaign from Tiltify")? .error_for_status() - .wrap_internal_err("fetching campaign from Tiltify")? + .internal_context("fetching campaign from Tiltify")? .json::() .await - .wrap_internal_err("parsing Tiltify response")?; + .internal_context("parsing Tiltify response")?; let raised_currency = &response.data.total_amount_raised.currency; if raised_currency != "USD" { - return Err(ApiError::Internal(eyre!( + return Err(ApiError::Internal(anyhow!( "total amount raised is in {raised_currency}, must be USD" ))); } let goal_currency = &response.data.goal.currency; if goal_currency != "USD" { - return Err(ApiError::Internal(eyre!( + return Err(ApiError::Internal(anyhow!( "goal amount is in {goal_currency}, must be USD" ))); } @@ -382,7 +384,7 @@ pub async fn pride_26( target_usd: response.data.goal.value, num_donators: num_donators(&http, &access_token, campaign_id) .await - .wrap_api_err("executing `num_donators`")?, + .api_context("executing `num_donators`")?, cached_at: Utc::now(), }; @@ -393,7 +395,7 @@ pub async fn pride_26( Some(CAMPAIGN_INFO_CACHE_TTL_SECONDS), ) .await - .wrap_internal_err("caching campaign info")?; + .internal_context("caching campaign info")?; Ok(campaign_info) } @@ -438,12 +440,12 @@ async fn num_donators( let response = request .send() .await - .wrap_internal_err("fetching donations from Tiltify")? + .internal_context("fetching donations from Tiltify")? .error_for_status() - .wrap_internal_err("fetching donations from Tiltify")? + .internal_context("fetching donations from Tiltify")? .json::() .await - .wrap_internal_err("parsing Tiltify donations response")?; + .internal_context("parsing Tiltify donations response")?; donors.extend( response @@ -475,14 +477,14 @@ async fn amount_raised_usd( let forex: TremendousForexResponse = payouts_queue .make_tremendous_request(Method::GET, "forex", None::<()>) .await - .wrap_internal_err("failed to fetch Tremendous forex data")?; + .internal_context("failed to fetch Tremendous forex data")?; let usd_to_currency = forex .forex .get(¤cy) .copied() - .wrap_internal_err_with(|| { - eyre!("no Tremendous forex rate for '{currency}'") + .internal_context_with(|| { + anyhow!("no Tremendous forex rate for '{currency}'") })?; Ok(amount.value / usd_to_currency) diff --git a/apps/labrinth/src/routes/internal/delphi/mod.rs b/apps/labrinth/src/routes/internal/delphi/mod.rs index 1607157f28a..8bff1ca7243 100644 --- a/apps/labrinth/src/routes/internal/delphi/mod.rs +++ b/apps/labrinth/src/routes/internal/delphi/mod.rs @@ -6,8 +6,8 @@ use xredis::RedisPool; use crate::env::ENV; use crate::{database::PgPool, util::http::HttpClient}; use actix_web::{HttpRequest, HttpResponse, get, post, web}; +use anyhow::anyhow; use chrono::{DateTime, Utc}; -use eyre::eyre; use serde::{Deserialize, Serialize}; use tokio::sync::Mutex; use tracing::info; @@ -45,7 +45,7 @@ pub fn config(cfg: &mut actix_web::web::ServiceConfig) { web::JsonConfig::default() .limit(10 * 1024 * 1024) .error_handler(|err, _req| { - ApiError::Request(eyre!("{err}")).into() + ApiError::Request(anyhow!("{err}")).into() }), ) .service(ingest_report) @@ -172,8 +172,8 @@ pub async fn ingest_report( // client's side - it's *our* fault for handling the Delphi schema wrong // this could happen if Delphi updates and Labrinth doesn't let report = serde_json::from_value::(report.clone()) - .wrap_internal_err_with(|| { - eyre!( + .internal_context_with(|| { + anyhow!( "received a Delphi response which does not match our schema\n\n{}", serde_json::to_string_pretty(&report).unwrap() ) @@ -208,20 +208,20 @@ async fn ingest_report_deserialized( let mut transaction = pool .begin() .await - .wrap_internal_err("failed to begin Delphi ingest transaction")?; + .internal_context("failed to begin Delphi ingest transaction")?; let file_id = DBFileId(report.file_id.0 as i64); AdvisoryLock::DelphiScan(report.identifier) .acquire(&mut transaction) .await - .wrap_internal_err("locking Delphi scan callback transition")?; + .internal_context("locking Delphi scan callback transition")?; if let Some(outcome) = crate::queue::delphi_scan::scan_outcome( &mut transaction, report.identifier, ) .await - .wrap_internal_err("checking Delphi scan callback state")? + .internal_context("checking Delphi scan callback state")? { info!(?outcome, "Ignoring callback for terminal Delphi file scan"); return Ok(()); @@ -236,7 +236,7 @@ async fn ingest_report_deserialized( AdvisoryLock::DelphiFile(file_id) .acquire(&mut transaction) .await - .wrap_internal_err("locking file for Delphi report ingest")?; + .internal_context("locking file for Delphi report ingest")?; let report_id = DBDelphiReport { id: DelphiReportId(0), // This will be set by the database @@ -248,7 +248,7 @@ async fn ingest_report_deserialized( } .upsert(&mut transaction) .await - .wrap_internal_err("failed to upsert Delphi report")?; + .internal_context("failed to upsert Delphi report")?; crate::queue::delphi_scan::record_succeeded_scan( &mut transaction, @@ -258,7 +258,7 @@ async fn ingest_report_deserialized( report_id, ) .await - .wrap_internal_err("recording successful Delphi file scan")?; + .internal_context("recording successful Delphi file scan")?; sqlx::query!( "DELETE FROM delphi_report_issues WHERE report_id = $1", @@ -266,7 +266,7 @@ async fn ingest_report_deserialized( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to remove old Delphi report issues")?; + .internal_context("failed to remove old Delphi report issues")?; if !clean { info!( @@ -284,7 +284,7 @@ async fn ingest_report_deserialized( } .insert(&mut transaction) .await - .wrap_internal_err("failed to insert Delphi report issue")?; + .internal_context("failed to insert Delphi report issue")?; for issue_detail in issue_details { let decompiled_source = @@ -305,7 +305,7 @@ async fn ingest_report_deserialized( } .insert(&mut transaction) .await - .wrap_internal_err("failed to insert Delphi issue detail")?; + .internal_context("failed to insert Delphi issue detail")?; inserted_detail_ids.push(detail_id); } } @@ -315,7 +315,7 @@ async fn ingest_report_deserialized( &mut transaction, ) .await - .wrap_internal_err("failed to apply delphi rules to new issue details")?; + .internal_context("failed to apply delphi rules to new issue details")?; let exited_projects = tech_review_queue::sync_projects( &[DBProjectId::from(report.project_id)], @@ -323,7 +323,7 @@ async fn ingest_report_deserialized( &mut transaction, ) .await - .wrap_api_err("synchronizing project technical-review state")?; + .api_context("synchronizing project technical-review state")?; let prepared = crate::routes::v3::projects::mutation::prepare_technical_review_exits( @@ -369,7 +369,7 @@ pub async fn _run( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; crate::queue::delphi_scan::publish_file_scan( &kafka_client, @@ -378,7 +378,7 @@ pub async fn _run( true, ) .await - .wrap_internal_err("enqueueing Delphi file scan")?; + .internal_context("enqueueing Delphi file scan")?; Ok(HttpResponse::NoContent().finish()) } @@ -424,8 +424,8 @@ pub async fn get_file( ) .fetch_optional(&**pool) .await - .wrap_internal_err("fetching file from database")? - .wrap_not_found_err("file not found")?; + .internal_context("fetching file from database")? + .not_found_context("file not found")?; Ok(web::Json(DelphiFile { id: file_id, @@ -458,13 +458,13 @@ pub async fn version( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; Ok(HttpResponse::Ok().json( sqlx::query_scalar!("SELECT MAX(delphi_version) FROM delphi_reports") .fetch_one(&**pool) .await - .wrap_internal_err("deserializing HTTP response")?, + .internal_context("deserializing HTTP response")?, )) } @@ -490,7 +490,7 @@ pub async fn issue_type_schema( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("deserializing HTTP response")?; + .auth_context("deserializing HTTP response")?; // This route is expected to be called often by the frontend, and Delphi is not necessarily // built to scale beyond malware analysis, so cache the result of its quasi-constant-valued @@ -511,10 +511,10 @@ pub async fn issue_type_schema( .send() .await .and_then(|res| res.error_for_status()) - .wrap_internal_err("fetching the Delphi schema")? + .internal_context("fetching the Delphi schema")? .json::>() .await - .wrap_internal_err("deserializing the Delphi schema")?, + .internal_context("deserializing the Delphi schema")?, Instant::now(), )) .0, diff --git a/apps/labrinth/src/routes/internal/delphi/rescan.rs b/apps/labrinth/src/routes/internal/delphi/rescan.rs index 1d63d995b71..bdd6ba5daca 100644 --- a/apps/labrinth/src/routes/internal/delphi/rescan.rs +++ b/apps/labrinth/src/routes/internal/delphi/rescan.rs @@ -1,4 +1,4 @@ -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use tracing::info; use crate::{ @@ -16,7 +16,7 @@ pub async fn enqueue_tech_review_files_for_new_delphi_version( sqlx::query_scalar!("SELECT MAX(delphi_version) FROM delphi_reports") .fetch_one(pool) .await - .wrap_err("fetching latest stored Delphi version")?; + .context("fetching latest stored Delphi version")?; if stored_delphi_version == Some(delphi_version) { info!( @@ -37,12 +37,12 @@ pub async fn enqueue_tech_review_files_for_new_delphi_version( ) .fetch_all(pool) .await - .wrap_err("fetching technical review files for Delphi rescan")?; + .context("fetching technical review files for Delphi rescan")?; for file_id in &file_ids { delphi_scan::publish_file_scan(kafka_client, *file_id, false, false) .await - .wrap_err_with(|| { + .with_context(|| { format!("enqueueing file `{file_id:?}` for Delphi rescan") })?; } diff --git a/apps/labrinth/src/routes/internal/delphi/tech_review_queue.rs b/apps/labrinth/src/routes/internal/delphi/tech_review_queue.rs index 46eae8e0305..8edf25aaf57 100644 --- a/apps/labrinth/src/routes/internal/delphi/tech_review_queue.rs +++ b/apps/labrinth/src/routes/internal/delphi/tech_review_queue.rs @@ -39,7 +39,7 @@ pub(crate) async fn lock_projects( ) .fetch_all(&mut *txn) .await - .wrap_internal_err("locking projects for technical review transitions")?; + .internal_context("locking projects for technical review transitions")?; Ok(()) } @@ -77,7 +77,7 @@ pub async fn add_projects( ) .fetch_all(&mut *txn) .await - .wrap_internal_err("failed to add projects to technical review queue")?; + .internal_context("failed to add projects to technical review queue")?; for row in rows { ThreadMessageBuilder { @@ -88,7 +88,7 @@ pub async fn add_projects( } .insert(txn) .await - .wrap_internal_err("failed to add entering technical review message")?; + .internal_context("failed to add entering technical review message")?; } Ok(()) @@ -128,7 +128,7 @@ pub async fn remove_projects( ) .fetch_all(&mut *txn) .await - .wrap_internal_err( + .internal_context( "failed to remove projects from technical review queue", )?; @@ -153,7 +153,7 @@ pub async fn remove_projects( } .insert(txn) .await - .wrap_internal_err("failed to add exiting technical review message")?; + .internal_context("failed to add exiting technical review message")?; } Ok(removed_project_ids) @@ -216,7 +216,7 @@ pub async fn sync_projects( ) .fetch_all(&mut *txn) .await - .wrap_internal_err( + .internal_context( "failed to determine technical review queue membership", )?; @@ -262,5 +262,5 @@ pub async fn sync_projects_with_membership( ) .fetch_all(&mut *txn) .await - .wrap_internal_err("fetching synchronized technical review membership") + .internal_context("fetching synchronized technical review membership") } diff --git a/apps/labrinth/src/routes/internal/external_notifications.rs b/apps/labrinth/src/routes/internal/external_notifications.rs index f71bdf1dfaf..00b4186952a 100644 --- a/apps/labrinth/src/routes/internal/external_notifications.rs +++ b/apps/labrinth/src/routes/internal/external_notifications.rs @@ -23,8 +23,8 @@ use crate::util::guards::external_notification_key_guard; use actix_web::http::StatusCode; use actix_web::web; use actix_web::{HttpRequest, HttpResponse, delete, post}; +use anyhow::anyhow; use ariadne::ids::UserId; -use eyre::eyre; use lettre::message::Mailbox; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -156,20 +156,20 @@ async fn create_impl( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if !DBUser::exists_many(&user_ids, &mut txn) .await - .wrap_internal_err("fetching users from database")? + .internal_context("fetching users from database")? { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "One of the specified users do not exist.".to_owned(), ))); } // Skip users who already have an identical notification let body_value = serde_json::value::to_value(&body) - .wrap_request_err("serializing external notification body")?; + .request_context("serializing external notification body")?; let already_notified = sqlx::query!( " SELECT DISTINCT user_id @@ -181,7 +181,7 @@ async fn create_impl( ) .fetch_all(&mut txn) .await - .wrap_internal_err("fetching already notified from database")? + .internal_context("fetching already notified from database")? .into_iter() .map(|row| DBUserId(row.user_id)) .collect::>(); @@ -198,7 +198,7 @@ async fn create_impl( notification_builder .insert_many(notification_user_ids, &mut txn, &redis) .await - .wrap_internal_err("inserting notification IDs into database")? + .internal_context("inserting notification IDs into database")? } else { notification_builder .insert_many_without_delivery( @@ -207,17 +207,17 @@ async fn create_impl( &redis, ) .await - .wrap_internal_err("inserting database records for `create_impl`")? + .internal_context("inserting database records for `create_impl`")? }; let notifications = get_site_exposed_notifications(¬ification_ids, &mut txn) .await - .wrap_api_err("fetching site exposed notifications")?; + .api_context("fetching site exposed notifications")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; broadcast_notifications(&redis, notifications).await; @@ -225,12 +225,12 @@ async fn create_impl( let mut email_txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut failed = HashMap::new(); let users = DBUser::get_many_ids(&user_ids, &mut email_txn, &redis) .await - .wrap_internal_err("fetching users from database")? + .internal_context("fetching users from database")? .into_iter() .map(|user| (user.id, user)) .collect::>(); @@ -272,7 +272,7 @@ async fn create_impl( email_txn .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; let status = if failed .values() @@ -311,13 +311,13 @@ pub async fn remove( notification_filter.into_inner(); if user_ids.is_empty() { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "at least one user must be provided to remove notifications from" ))); } if body.is_empty() { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "at least one `body` field must be provided to match notifications" ))); } @@ -332,17 +332,17 @@ pub async fn remove( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; DBNotification::remove_many_matching_body( &filters, &user_ids, &mut txn, &redis, ) .await - .wrap_internal_err("deleting notifications from database")?; + .internal_context("deleting notifications from database")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().finish()) } @@ -376,10 +376,10 @@ pub async fn send_custom_email( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to send custom emails!", ))); } @@ -399,7 +399,7 @@ pub async fn send_custom_email( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; NotificationBuilder { body: NotificationBody::Custom { @@ -410,11 +410,11 @@ pub async fn send_custom_email( } .insert_many(users, &mut txn, &redis) .await - .wrap_internal_err("inserting database records for `send_custom_email`")?; + .internal_context("inserting database records for `send_custom_email`")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Accepted().finish()) } @@ -436,14 +436,14 @@ async fn get_site_exposed_notifications( ) .fetch_all(&mut *txn) .await - .wrap_internal_err("fetching exposed IDs from database")? + .internal_context("fetching exposed IDs from database")? .into_iter() .map(DBNotificationId) .collect::>(); Ok(DBNotification::get_many(&exposed_ids, txn) .await - .wrap_internal_err("fetching notifications from database")? + .internal_context("fetching notifications from database")? .into_iter() .map(Notification::from) .collect()) diff --git a/apps/labrinth/src/routes/internal/flows.rs b/apps/labrinth/src/routes/internal/flows.rs index 060565cc7bb..e553bf5a866 100644 --- a/apps/labrinth/src/routes/internal/flows.rs +++ b/apps/labrinth/src/routes/internal/flows.rs @@ -35,13 +35,13 @@ use actix_http::header::LOCATION; use actix_web::http::StatusCode; use actix_web::web::{Data, Query}; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, post, web}; +use anyhow::anyhow; use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier}; use ariadne::ids::base62_impl::{parse_base62, to_base62}; use ariadne::ids::random_base62_rng; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use chrono::{Duration, Utc}; -use eyre::eyre; use hmac::{Hmac, KeyInit, Mac}; use lettre::message::Mailbox; use rand::RngExt; @@ -187,7 +187,7 @@ impl TempUser { if let Some(email) = &self.email && crate::database::models::DBUser::get_by_email(email, client) .await - .wrap_internal_err("fetching existing user by email")? + .internal_context("fetching existing user by email")? .is_some() { return Err(CreateAccountError::DuplicateEmail); @@ -195,11 +195,11 @@ impl TempUser { let user_id = crate::database::models::generate_user_id(transaction) .await - .wrap_internal_err("generating user ID")?; + .internal_context("generating user ID")?; let existing_id = DBUser::get(&username, client, redis) .await - .wrap_internal_err("fetching existing user by ID")?; + .internal_context("fetching existing user by ID")?; if existing_id.is_some() { return Err(CreateAccountError::UsernameTaken); @@ -210,7 +210,7 @@ impl TempUser { { let res = reqwest::get(&avatar_url) .await - .wrap_internal_err("fetching OAuth user avatar")?; + .internal_context("fetching OAuth user avatar")?; let headers = res.headers().clone(); let img_data = if let Some(content_type) = headers @@ -226,7 +226,7 @@ impl TempUser { let bytes = res .bytes() .await - .wrap_internal_err("reading OAuth user avatar")?; + .internal_context("reading OAuth user avatar")?; let upload_result = upload_image_optimized( &format!("user/{}", ariadne::ids::UserId::from(user_id)), @@ -258,7 +258,7 @@ impl TempUser { self.id .clone() .parse() - .wrap_internal_err("parsing GitHub user ID")?, + .internal_context("parsing GitHub user ID")?, ) } else { None @@ -267,7 +267,7 @@ impl TempUser { Some( self.id .parse() - .wrap_internal_err("parsing Discord user ID")?, + .internal_context("parsing Discord user ID")?, ) } else { None @@ -276,7 +276,7 @@ impl TempUser { Some( self.id .parse() - .wrap_internal_err("parsing GitLab user ID")?, + .internal_context("parsing GitLab user ID")?, ) } else { None @@ -290,7 +290,7 @@ impl TempUser { Some( self.id .parse() - .wrap_internal_err("parsing Steam user ID")?, + .internal_context("parsing Steam user ID")?, ) } else { None @@ -333,7 +333,7 @@ impl TempUser { } .insert(transaction) .await - .wrap_internal_err("inserting user into database")?; + .internal_context("inserting user into database")?; Ok(user_id) } @@ -1307,7 +1307,7 @@ pub async fn auth_callback( flow.insert_with_state(Duration::minutes(10), &redis, &state) .await - .wrap_internal_err("failed to insert new flow state")?; + .internal_context("failed to insert new flow state")?; Ok(()) } @@ -1322,8 +1322,8 @@ pub async fn auth_callback( let res: Result = async move { let flow = DBFlow::get(&state, &redis) .await - .wrap_err("failed to fetch flow state")? - .wrap_err("no flow for state")?; + .context("failed to fetch flow state")? + .context("no flow for state")?; // Extract cookie header from request let DBFlow::OAuth { @@ -1333,7 +1333,7 @@ pub async fn auth_callback( existing_user_id, } = flow else { - return Err(AuthenticationError::Internal(eyre!( + return Err(AuthenticationError::Internal(anyhow!( "invalid flow kind" ))); }; @@ -1346,16 +1346,16 @@ pub async fn auth_callback( let token = provider .get_token(query) .await - .wrap_err("failed to get token from provider")?; + .context("failed to get token from provider")?; let oauth_user = provider .get_user(&token) .await - .wrap_err("failed to get user from provider")?; + .context("failed to get user from provider")?; let mut transaction = client .begin() .await - .wrap_err("failed to begin transaction")?; + .context("failed to begin transaction")?; // PayPal isn't actually an SSO method; we allow users to link their PayPal // account to their Modrinth account via this OAuth flow. However, we MUST @@ -1364,7 +1364,7 @@ pub async fn auth_callback( // Instead, we check who they're already logged in as, and just update // the PayPal info for that account. if provider == AuthProvider::PayPal { - let existing_user_id = existing_user_id.wrap_err( + let existing_user_id = existing_user_id.context( "attempting to link a PayPal account without being logged in", )?; @@ -1377,12 +1377,12 @@ pub async fn auth_callback( ) .acquire(&mut transaction) .await - .wrap_err("failed to lock PayPal account for linking")?; + .context("failed to lock PayPal account for linking")?; let linked_user_id = provider .get_user_id(&oauth_user.id, &mut transaction) .await - .wrap_err("failed to get linked user ID from PayPal")?; + .context("failed to get linked user ID from PayPal")?; if linked_user_id.is_some_and(|id| id != existing_user_id) { return Err(AuthenticationError::ProviderAlreadyLinked); @@ -1401,18 +1401,18 @@ pub async fn auth_callback( ) .execute(&mut transaction) .await - .wrap_err("failed to update user PayPal info")?; + .context("failed to update user PayPal info")?; transaction .commit() .await - .wrap_err("failed to commit transaction")?; + .context("failed to commit transaction")?; crate::database::models::DBUser::clear_caches( &[(existing_user_id, None)], &redis, ) .await - .wrap_err("failed to clear user caches")?; + .context("failed to clear user caches")?; return Ok(HttpResponse::TemporaryRedirect() .append_header(("Location", url.as_str())) @@ -1422,7 +1422,7 @@ pub async fn auth_callback( let user_id_opt = provider .get_user_id(&oauth_user.id, &**client) .await - .wrap_err("failed to get user ID from provider")?; + .context("failed to get user ID from provider")?; if let Some(id) = user_id { if user_id_opt.is_some() { @@ -1522,7 +1522,7 @@ pub async fn auth_callback( user: oauth_user, }) .await - .wrap_err("failed to replace flow for state")?; + .context("failed to replace flow for state")?; let mut redirect_url = url.clone(); redirect_url @@ -1574,7 +1574,7 @@ struct NewOAuthAccount { fn validate_account_consent(account_consent: bool) -> Result<(), ApiError> { if account_consent { info!("account consent trigger, denying"); - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "Sorry, something went wrong. Please try again" ))); } @@ -1591,7 +1591,7 @@ async fn send_verify_email( ) -> Result<(), ApiError> { let mailbox: Mailbox = email_address .parse() - .wrap_request_err("invalid email address!".to_string())?; + .request_context("invalid email address!".to_string())?; let flow = DBFlow::ConfirmEmail { user_id, @@ -1599,7 +1599,7 @@ async fn send_verify_email( } .insert(Duration::hours(24), redis) .await - .wrap_internal_err("storing email-verification flow in Redis")?; + .internal_context("storing email-verification flow in Redis")?; email_queue .send_one( @@ -1609,9 +1609,9 @@ async fn send_verify_email( mailbox, ) .await - .wrap_api_err("sending account email")? + .api_context("sending account email")? .as_user_error() - .wrap_api_err("validating email delivery status")?; + .api_context("validating email delivery status")?; Ok(()) } @@ -1638,26 +1638,25 @@ pub async fn create_oauth_account( ) -> Result { new_account .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; validate_account_consent(new_account.account_consent) - .wrap_api_err("validating account consent")?; + .api_context("validating account consent")?; if !check_turnstile(&req, &new_account.challenge, &redis) .await - .wrap_api_err("checking captcha response")? + .api_context("checking captcha response")? { - return Err(ApiError::Request(eyre::eyre!( - "captcha validation failed" - )) - .into()); + return Err( + ApiError::Request(anyhow!("captcha validation failed")).into() + ); } let flow = DBFlow::get(&new_account.state, &redis) .await - .wrap_internal_err("failed to fetch flow state")? - .wrap_request_err("no flow for state")?; + .internal_context("failed to fetch flow state")? + .request_context("no flow for state")?; let DBFlow::OAuthPending { url: _url, @@ -1665,19 +1664,19 @@ pub async fn create_oauth_account( user, } = flow else { - return Err(ApiError::Internal(eyre!("invalid flow kind")).into()); + return Err(ApiError::Internal(anyhow!("invalid flow kind")).into()); }; if let Some(email) = &user.email { ensure_email_passes_gate(&redis, email) .await - .wrap_api_err("validating email passes the signup gate")?; + .api_context("validating email passes the signup gate")?; } let mut txn = db .begin() .await - .wrap_internal_err("failed to begin transaction")?; + .internal_context("failed to begin transaction")?; let account_email = user.email.clone(); @@ -1718,10 +1717,10 @@ pub async fn create_oauth_account( new_account.app_session, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().json(res)) } @@ -1770,7 +1769,7 @@ pub async fn discord_community_link( if ENV.DISCORD_COMMUNITY_LINK_SECRET.is_empty() || ENV.DISCORD_COMMUNITY_BOT_HANDOFF_URL.is_empty() { - return Err(ApiError::Internal(eyre!( + return Err(ApiError::Internal(anyhow!( "discord community linking is not configured" ))); } @@ -1783,11 +1782,13 @@ pub async fn discord_community_link( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .1; let Some(discord_id) = db_user.discord_id else { - return Err(ApiError::Request(eyre!("discord account is not linked"))); + return Err(ApiError::Request(anyhow!( + "discord account is not linked" + ))); }; let now = Utc::now().timestamp(); @@ -1806,7 +1807,7 @@ pub async fn discord_community_link( nonce, }; - let payload_json = serde_json::to_vec(&payload).wrap_internal_err( + let payload_json = serde_json::to_vec(&payload).internal_context( "failed to serialize discord community handoff payload", )?; let payload_b64 = URL_SAFE_NO_PAD.encode(payload_json); @@ -1814,7 +1815,7 @@ pub async fn discord_community_link( let mut mac = HmacSha256::new_from_slice( ENV.DISCORD_COMMUNITY_LINK_SECRET.as_bytes(), ) - .wrap_internal_err("failed to initialize discord community link hmac")?; + .internal_context("failed to initialize discord community link hmac")?; mac.update(payload_b64.as_bytes()); let sig = URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()); @@ -1855,13 +1856,13 @@ pub async fn delete_auth_provider( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; if user.auth_providers.is_none_or(|x| x.len() <= 1) && !user.has_password.unwrap_or(false) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You must have another authentication method added to this account!", ))); } @@ -1869,15 +1870,13 @@ pub async fn delete_auth_provider( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; delete_provider .provider .update_user_id(user.id.into(), None, &mut transaction) .await - .wrap_auth_err( - "updating database records for `delete_auth_provider`", - )?; + .auth_context("updating database records for `delete_auth_provider`")?; if delete_provider.provider != AuthProvider::PayPal { NotificationBuilder { @@ -1887,7 +1886,7 @@ pub async fn delete_auth_provider( } .insert(user.id.into(), &mut transaction, &redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `delete_auth_provider`", )?; } @@ -1895,13 +1894,13 @@ pub async fn delete_auth_provider( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::DBUser::clear_caches( &[(user.id.into(), None)], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().finish()) } @@ -2025,7 +2024,7 @@ fn ensure_email_domain_is_not_blacklisted(email: &str) -> Result<(), ApiError> { "blacklisted email domain, denying", ); - Err(ApiError::Request(eyre!( + Err(ApiError::Request(anyhow!( "This domain name may not be used ({domain})!" ))) } @@ -2043,7 +2042,7 @@ async fn ensure_email_passes_gate( let action = check_email_gate(redis, email) .await - .wrap_request_err("checking email address")?; + .request_context("checking email address")?; if action == DecisionAction::Block { return Err(ApiError::Request(gate_block_error())); @@ -2064,7 +2063,7 @@ async fn ensure_email_is_usable( let result = check_email(redis, email) .await - .wrap_request_err("checking email address")?; + .request_context("checking email address")?; if matches!( result, @@ -2095,7 +2094,7 @@ impl AccountRegisterFlow { redis, ) .await - .wrap_internal_err("fetching existing user with username")? + .internal_context("fetching existing user with username")? .is_some() { return Err(CreateAccountError::UsernameTaken); @@ -2117,7 +2116,7 @@ impl AccountRegisterFlow { &mut *transaction, ) .await - .wrap_internal_err("fetching existing user with email")? + .internal_context("fetching existing user with email")? .is_empty() { return Err(CreateAccountError::DuplicateEmail); @@ -2139,13 +2138,13 @@ impl ReadyAccountRegisterFlow { let user_id = crate::database::models::generate_user_id(transaction) .await - .wrap_internal_err("generating user ID")?; + .internal_context("generating user ID")?; let hasher = Argon2::default(); let salt = rand::random::<[u8; 16]>(); let password_hash = hasher .hash_password_with_salt(register_flow.password.as_bytes(), &salt) - .wrap_internal_err("hashing password")? + .internal_context("hashing password")? .to_string(); let insert_result = crate::database::models::DBUser { @@ -2196,7 +2195,7 @@ impl ReadyAccountRegisterFlow { } } - return Err(ApiError::Internal(eyre::eyre!( + return Err(ApiError::Internal(anyhow!( "inserting registered user: {err}" )) .into()); @@ -2211,7 +2210,7 @@ impl ReadyAccountRegisterFlow { register_flow.app_session, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; send_verify_email( email_queue, @@ -2246,7 +2245,7 @@ pub async fn validate_create_account_with_password( let mut transaction = pool .begin() .await - .wrap_internal_err("beginning transaction")?; + .internal_context("beginning transaction")?; AccountRegisterFlow::from(new_account.into_inner()) .validate(&mut transaction, &redis) @@ -2276,7 +2275,7 @@ pub async fn create_account_with_password( let new_account = new_account.into_inner(); validate_account_consent(new_account.account_consent) - .wrap_api_err("validating account consent")?; + .api_context("validating account consent")?; if !check_turnstile( &req, @@ -2284,22 +2283,21 @@ pub async fn create_account_with_password( &redis, ) .await - .wrap_api_err("checking captcha response")? + .api_context("checking captcha response")? { - return Err(ApiError::Request(eyre::eyre!( - "captcha validation failed" - )) - .into()); + return Err( + ApiError::Request(anyhow!("captcha validation failed")).into() + ); } ensure_email_is_usable(&redis, &new_account.email) .await - .wrap_api_err("validating email is usable")?; + .api_context("validating email is usable")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let ready_flow = AccountRegisterFlow::from(new_account) .validate(&mut transaction, &redis) @@ -2311,7 +2309,7 @@ pub async fn create_account_with_password( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().json(res)) } @@ -2346,11 +2344,9 @@ pub async fn login_password( ) -> Result { if !check_turnstile(&req, &login.challenge, &redis) .await - .wrap_api_err("checking captcha response")? + .api_context("checking captcha response")? { - return Err(ApiError::Request(eyre::eyre!( - "captcha validation failed" - ))); + return Err(ApiError::Request(anyhow!("captcha validation failed"))); } let user = if let Some(user) = crate::database::models::DBUser::get( @@ -2359,7 +2355,7 @@ pub async fn login_password( &redis, ) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? { user } else { @@ -2368,15 +2364,15 @@ pub async fn login_password( &**pool, ) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("fetching user from database")?; + .auth_context("fetching user from database")?; crate::database::models::DBUser::get_id(user, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("fetching user from database")? + .auth_context("fetching user from database")? }; let hasher = Argon2::default(); @@ -2387,18 +2383,18 @@ pub async fn login_password( &user .password .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("authenticating API request")?, + .auth_context("authenticating API request")?, ) - .wrap_internal_err("validating data")?, + .internal_context("validating data")?, ) .map_err(|_| AuthenticationError::InvalidCredentials) - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if user.totp_secret.is_some() { let flow = DBFlow::Login2FA { user_id: user.id } .insert(Duration::minutes(30), &redis) .await - .wrap_internal_err("inserting authentication flow into database")?; + .internal_context("inserting authentication flow into database")?; Ok(HttpResponse::Ok().json(serde_json::json!({ "error": "2fa_required", @@ -2409,7 +2405,7 @@ pub async fn login_password( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let res = issue_auth_sessions( req, user.id, @@ -2418,11 +2414,11 @@ pub async fn login_password( login.app_session, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().json(res)) } @@ -2527,27 +2523,27 @@ pub async fn login_2fa( ) -> Result { let flow = DBFlow::get(&login.flow, &redis) .await - .wrap_internal_err("fetching login flow from Redis")? + .internal_context("fetching login flow from Redis")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("finding login flow")?; + .auth_context("finding login flow")?; if let DBFlow::Login2FA { user_id } = flow { let user = crate::database::models::DBUser::get_id(user_id, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("fetching user from database")?; + .auth_context("fetching user from database")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if !validate_2fa_code( login.code.clone(), user.totp_secret .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("authenticating API request")?, + .auth_context("authenticating API request")?, true, user.id, &redis, @@ -2555,15 +2551,15 @@ pub async fn login_2fa( &mut transaction, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } DBFlow::remove(&login.flow, &redis) .await - .wrap_internal_err("removing authentication flow from Redis")?; + .internal_context("removing authentication flow from Redis")?; let res = issue_auth_sessions( req, @@ -2573,15 +2569,15 @@ pub async fn login_2fa( login.app_session, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().json(res)) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))) } @@ -2614,7 +2610,7 @@ pub async fn begin_2fa_flow( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; if !user.has_totp.unwrap_or(false) { @@ -2627,14 +2623,14 @@ pub async fn begin_2fa_flow( } .insert(Duration::minutes(30), &redis) .await - .wrap_internal_err("inserting database records for `begin_2fa_flow`")?; + .internal_context("inserting database records for `begin_2fa_flow`")?; Ok(HttpResponse::Ok().json(serde_json::json!({ "secret": encoded.to_string(), "flow": flow, }))) } else { - Err(ApiError::Request(eyre::eyre!( + Err(ApiError::Request(anyhow!( "User already has 2FA enabled on their account!", ))) } @@ -2662,9 +2658,9 @@ pub async fn finish_2fa_flow( ) -> Result { let flow = DBFlow::get(&login.flow, &redis) .await - .wrap_internal_err("fetching 2FA initialization flow from Redis")? + .internal_context("fetching 2FA initialization flow from Redis")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("finding 2FA initialization flow")?; + .auth_context("finding 2FA initialization flow")?; if let DBFlow::Initialize2FA { user_id, secret } = flow { let user = get_user_from_headers( @@ -2675,11 +2671,11 @@ pub async fn finish_2fa_flow( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; if user.id != user_id.into() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } @@ -2687,7 +2683,7 @@ pub async fn finish_2fa_flow( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if !validate_2fa_code( login.code.clone(), @@ -2699,16 +2695,16 @@ pub async fn finish_2fa_flow( &mut transaction, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } DBFlow::remove(&login.flow, &redis) .await - .wrap_internal_err("removing authentication flow from Redis")?; + .internal_context("removing authentication flow from Redis")?; sqlx::query!( " @@ -2721,7 +2717,7 @@ pub async fn finish_2fa_flow( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `finish_2fa_flow`")?; + .internal_context("querying database for `finish_2fa_flow`")?; sqlx::query!( " @@ -2732,7 +2728,7 @@ pub async fn finish_2fa_flow( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `finish_2fa_flow`")?; + .internal_context("querying database for `finish_2fa_flow`")?; let mut codes = Vec::new(); @@ -2754,7 +2750,7 @@ pub async fn finish_2fa_flow( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `finish_2fa_flow`")?; + .internal_context("querying database for `finish_2fa_flow`")?; codes.push(to_base62(val)); } @@ -2764,26 +2760,24 @@ pub async fn finish_2fa_flow( } .insert(user.id.into(), &mut transaction, &redis) .await - .wrap_internal_err( - "inserting database records for `finish_2fa_flow`", - )?; + .internal_context("inserting database records for `finish_2fa_flow`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::DBUser::clear_caches( &[(user.id.into(), None)], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::Ok().json(serde_json::json!({ "backup_codes": codes, }))) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))) } @@ -2823,12 +2817,12 @@ pub async fn remove_2fa( false, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !scopes.contains(Scopes::USER_AUTH_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } @@ -2836,11 +2830,11 @@ pub async fn remove_2fa( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if !validate_2fa_code( login.code.clone(), - user.totp_secret.wrap_request_err_with(|| { + user.totp_secret.request_context_with(|| { "user does not have 2FA enabled on the account!".to_string() })?, true, @@ -2850,31 +2844,31 @@ pub async fn remove_2fa( &mut transaction, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } DBUser::remove_2fa(user.id, &mut transaction) .await - .wrap_internal_err("removing 2FA")?; + .internal_context("removing 2FA")?; NotificationBuilder { body: NotificationBody::TwoFactorRemoved, } .insert(user.id, &mut transaction, &redis) .await - .wrap_internal_err("inserting database records for `remove_2fa`")?; + .internal_context("inserting database records for `remove_2fa`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::DBUser::clear_caches(&[(user.id, None)], &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().finish()) } @@ -2907,17 +2901,15 @@ pub async fn reset_password_begin( ) -> Result { if !check_turnstile(&req, &reset_password.challenge, &redis) .await - .wrap_api_err("checking captcha response")? + .api_context("checking captcha response")? { - return Err(ApiError::Request(eyre::eyre!( - "captcha validation failed" - ))); + return Err(ApiError::Request(anyhow!("captcha validation failed"))); } let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let user = match crate::database::models::DBUser::get_by_case_insensitive_email( @@ -2925,7 +2917,7 @@ pub async fn reset_password_begin( &mut txn, ) .await - .wrap_internal_err("fetching user from database")?[..] + .internal_context("fetching user from database")?[..] { [] => { // Try finding by username or ID @@ -2935,7 +2927,7 @@ pub async fn reset_password_begin( &redis, ) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? } [user_id] => { // If there is only one user with the given email, ignoring case, @@ -2944,7 +2936,7 @@ pub async fn reset_password_begin( user_id, &mut txn, &redis, ) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? } _ => { // When several users use variations of the same email with @@ -2957,15 +2949,13 @@ pub async fn reset_password_begin( &mut txn, ) .await - .wrap_internal_err( - "fetching password-reset user by email", - )? + .internal_context("fetching password-reset user by email")? { crate::database::models::DBUser::get_id( user_id, &mut txn, &redis, ) .await - .wrap_internal_err("fetching password-reset user by ID")? + .internal_context("fetching password-reset user by ID")? } else { None } @@ -2985,7 +2975,7 @@ pub async fn reset_password_begin( } .insert(Duration::hours(24), &redis) .await - .wrap_internal_err("inserting authentication flow into database")?; + .internal_context("inserting authentication flow into database")?; email .send_one( @@ -2995,14 +2985,14 @@ pub async fn reset_password_begin( mailbox, ) .await - .wrap_api_err("sending account email")? + .api_context("sending account email")? .as_user_error() - .wrap_api_err("validating email delivery status")?; + .api_context("validating email delivery status")?; } txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().finish()) } @@ -3038,7 +3028,7 @@ pub async fn change_password( let user = if let Some(flow) = &change_password.flow { let flow = DBFlow::get(flow, &redis) .await - .wrap_internal_err("fetching password-reset flow from Redis")?; + .internal_context("fetching password-reset flow from Redis")?; let (user_id, flow_email, allow_locked) = match flow { Some(DBFlow::ForgotPassword { user_id, email }) => { @@ -3048,7 +3038,7 @@ pub async fn change_password( (user_id, email, true) } _ => { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The password change flow code is invalid or has expired. Did you copy it promptly and correctly?", ))); } @@ -3056,12 +3046,12 @@ pub async fn change_password( let user = DBUser::get_id(user_id, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("fetching user from database")?; + .auth_context("fetching user from database")?; if user.email.as_deref() != Some(flow_email.as_str()) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The password change flow code is invalid or has expired. Did you copy it promptly and correctly?", ))); } @@ -3089,12 +3079,12 @@ pub async fn change_password( false, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !scopes.contains(Scopes::USER_AUTH_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } @@ -3103,7 +3093,7 @@ pub async fn change_password( let old_password = change_password .old_password .as_ref() - .wrap_auth_err_with(|| { + .auth_context_with(|| { "you must specify the old password to change your password!" .to_string() })?; @@ -3113,9 +3103,9 @@ pub async fn change_password( .verify_password( old_password.as_bytes(), &PasswordHash::new(pass) - .wrap_internal_err("validating data")?, + .internal_context("validating data")?, ) - .wrap_internal_err("validating data")?; + .internal_context("validating data")?; } user @@ -3124,7 +3114,7 @@ pub async fn change_password( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let update_password = if let Some(new_password) = &change_password.new_password @@ -3140,11 +3130,11 @@ pub async fn change_password( .and_then(|feedback| feedback.warning()) .map_or_else( || { - eyre::eyre!( + anyhow!( "Specified password is too weak! Please improve its strength." ) }, - |feedback| eyre::eyre!("Password too weak: {feedback}"), + |feedback| anyhow!("Password too weak: {feedback}"), ); return Err(ApiError::Request(report)); } @@ -3153,7 +3143,7 @@ pub async fn change_password( let salt = rand::random::<[u8; 16]>(); let password_hash = hasher .hash_password_with_salt(new_password.as_bytes(), &salt) - .wrap_internal_err("hashing password")? + .internal_context("hashing password")? .to_string(); Some(password_hash) @@ -3165,7 +3155,7 @@ pub async fn change_password( || user.steam_id.is_some() || user.discord_id.is_some()) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You must have another authentication method added to remove password authentication!", ))); } @@ -3184,12 +3174,12 @@ pub async fn change_password( ) .execute(&mut transaction) .await - .wrap_internal_err("updating database records for `change_password`")?; + .internal_context("updating database records for `change_password`")?; if let Some(flow) = &change_password.flow { DBFlow::remove(flow, &redis) .await - .wrap_internal_err("removing authentication flow from Redis")?; + .internal_context("removing authentication flow from Redis")?; } if update_password.is_some() { @@ -3198,27 +3188,23 @@ pub async fn change_password( } .insert(user.id, &mut transaction, &redis) .await - .wrap_internal_err( - "inserting database records for `change_password`", - )?; + .internal_context("inserting database records for `change_password`")?; } else { NotificationBuilder { body: NotificationBody::PasswordRemoved, } .insert(user.id, &mut transaction, &redis) .await - .wrap_internal_err( - "inserting database records for `change_password`", - )?; + .internal_context("inserting database records for `change_password`")?; } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::DBUser::clear_caches(&[(user.id, None)], &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::Ok().finish()) } @@ -3255,12 +3241,12 @@ pub async fn set_email( email_address .0 .validate() - .wrap_request_err("validating request")?; + .request_context("validating request")?; let mailbox: Mailbox = email_address .email .parse() - .wrap_request_err("invalid email address!".to_string())?; + .request_context("invalid email address!".to_string())?; let user = get_user_from_headers( &req, @@ -3270,7 +3256,7 @@ pub async fn set_email( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; if !crate::database::models::DBUser::get_by_case_insensitive_email( @@ -3278,22 +3264,22 @@ pub async fn set_email( &**pool, ) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? .is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Email is already registered on Modrinth! Try 'Forgot password' in incognito to access and delete your other account.", ))); } ensure_email_is_usable(&redis, &email_address.email) .await - .wrap_api_err("validating email is usable")?; + .api_context("validating email is usable")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -3306,7 +3292,7 @@ pub async fn set_email( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `set_email`")?; + .internal_context("querying database for `set_email`")?; if let Some(user_email) = user.email.clone() { NotificationBuilder { @@ -3317,7 +3303,7 @@ pub async fn set_email( } .insert(user.id.into(), &mut transaction, &redis) .await - .wrap_internal_err("inserting database records for `set_email`")?; + .internal_context("inserting database records for `set_email`")?; } if let Some(customer_id) = user @@ -3329,7 +3315,7 @@ pub async fn set_email( .email(email_address.email.as_str()) .send(&**stripe_client) .await - .wrap_stripe_err("communicating with payment provider")?; + .stripe_context("communicating with payment provider")?; } let flow = DBFlow::ConfirmEmail { @@ -3338,7 +3324,7 @@ pub async fn set_email( } .insert(Duration::hours(24), &redis) .await - .wrap_internal_err("inserting database records for `set_email`")?; + .internal_context("inserting database records for `set_email`")?; email .send_one( @@ -3348,21 +3334,21 @@ pub async fn set_email( mailbox, ) .await - .wrap_api_err("sending account email")? + .api_context("sending account email")? .as_user_error() - .wrap_api_err("validating email delivery status")?; + .api_context("validating email delivery status")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::DBUser::clear_caches( &[(user.id.into(), None)], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::Ok().finish()) } @@ -3395,12 +3381,12 @@ pub async fn resend_verify_email( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; if let Some(email_address) = user.email { if user.email_verified.unwrap_or(false) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "User email is already verified!", ))); } @@ -3411,18 +3397,18 @@ pub async fn resend_verify_email( } .insert(Duration::hours(24), &redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `resend_verify_email`", )?; let mailbox: Mailbox = email_address .parse() - .wrap_request_err("invalid email address!".to_string())?; + .request_context("invalid email address!".to_string())?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; email .send_one( @@ -3432,20 +3418,18 @@ pub async fn resend_verify_email( mailbox, ) .await - .wrap_api_err("sending account email")? + .api_context("sending account email")? .as_user_error() - .wrap_api_err("validating email delivery status")?; + .api_context("validating email delivery status")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().finish()) } else { - Err(ApiError::Request(eyre::eyre!( - "User does not have an email.", - ))) + Err(ApiError::Request(anyhow!("User does not have an email.",))) } } @@ -3473,7 +3457,7 @@ pub async fn verify_email( ) -> Result { let flow = DBFlow::get(&email.flow, &redis) .await - .wrap_internal_err("fetching email-verification flow from Redis")?; + .internal_context("fetching email-verification flow from Redis")?; if let Some(DBFlow::ConfirmEmail { user_id, @@ -3483,12 +3467,12 @@ pub async fn verify_email( let user = crate::database::models::DBUser::get_id(user_id, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? .ok_or_else(|| AuthenticationError::InvalidCredentials) - .wrap_auth_err("fetching user from database")?; + .auth_context("fetching user from database")?; if user.email != Some(confirm_email) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "E-mail does not match verify email. Try re-requesting the verification link.", ))); } @@ -3496,7 +3480,7 @@ pub async fn verify_email( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -3508,25 +3492,25 @@ pub async fn verify_email( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `verify_email`")?; + .internal_context("querying database for `verify_email`")?; DBFlow::remove(&email.flow, &redis) .await - .wrap_internal_err("removing authentication flow from Redis")?; + .internal_context("removing authentication flow from Redis")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::DBUser::clear_caches( &[(user.id, None)], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().finish()) } else { - Err(ApiError::Request(eyre::eyre!( + Err(ApiError::Request(anyhow!( "Flow does not exist. Try re-requesting the verification link.", ))) } @@ -3559,7 +3543,7 @@ pub async fn subscribe_newsletter( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; sqlx::query!( @@ -3572,14 +3556,14 @@ pub async fn subscribe_newsletter( ) .execute(&**pool) .await - .wrap_internal_err("querying database for `subscribe_newsletter`")?; + .internal_context("querying database for `subscribe_newsletter`")?; crate::database::models::DBUser::clear_caches( &[(user.id.into(), None)], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().finish()) } @@ -3611,14 +3595,14 @@ pub async fn get_newsletter_subscription_status( Scopes::USER_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .1; let is_subscribed = user.is_subscribed_to_newsletter || if let Some(email) = user.email { check_sendy_subscription(&email) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? } else { false }; @@ -3665,20 +3649,20 @@ pub async fn register_passkey_start( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; // Get currently registered credentials, so an authenticator knows not to register // duplicate credentials let excluded_credentials = DBPasskey::get_for_user(user.id.into(), &**pool) .await - .wrap_internal_err("failed to fetch passkeys for user")? + .internal_context("failed to fetch passkeys for user")? .into_iter() .map(|cred| CredentialID::from(cred.credential_id)) .collect::>(); if excluded_credentials.len() >= MAX_PASSKEYS_PER_USER { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "maximum of {MAX_PASSKEYS_PER_USER} passkeys per user reached" ))); } @@ -3697,7 +3681,7 @@ pub async fn register_passkey_start( &user.username, Some(excluded_credentials), ) - .wrap_internal_err("failed to start passkey registration")?; + .internal_context("failed to start passkey registration")?; // This is not ideal, but webauthn-rs doesn't expose anything that allows us to force a resident // key. And since we are implementing a one-click login flow without input of a username, @@ -3716,7 +3700,7 @@ pub async fn register_passkey_start( } .insert(Duration::minutes(30), &redis) .await - .wrap_internal_err("failed to store passkey registration flow")?; + .internal_context("failed to store passkey registration flow")?; Ok(web::Json(RegisterPasskeyResponse { options: ccr, flow })) } @@ -3768,13 +3752,13 @@ pub async fn register_passkey_finish( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; response .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let db_user_id: DBUserId = user.id.into(); let flow = DBFlow::take_if( @@ -3782,29 +3766,29 @@ pub async fn register_passkey_finish( |f| matches!(f, DBFlow::RegisterPasskey { user_id, .. } if *user_id == db_user_id), &redis, ) - .await.wrap_internal_err("executing `DBFlow::take_if`")?; + .await.internal_context("executing `DBFlow::take_if`")?; if let Some(DBFlow::RegisterPasskey { user_id, state }) = flow { if user_id != db_user_id { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } let result = webauthn .finish_passkey_registration(&response.credential, &state) - .wrap_request_err("failed to finish passkey registration")?; + .request_context("failed to finish passkey registration")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let existing_passkeys = DBPasskey::get_for_user(db_user_id, &mut transaction) .await - .wrap_internal_err("failed to fetch passkeys for user")?; + .internal_context("failed to fetch passkeys for user")?; if existing_passkeys.len() >= MAX_PASSKEYS_PER_USER { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "maximum of {MAX_PASSKEYS_PER_USER} passkeys per user reached" ))); } @@ -3812,7 +3796,7 @@ pub async fn register_passkey_finish( let passkey_id = crate::database::models::generate_passkey_id(&mut transaction) .await - .wrap_internal_err("failed to generate passkey id")?; + .internal_context("failed to generate passkey id")?; let passkey = DBPasskey { id: passkey_id, @@ -3826,12 +3810,12 @@ pub async fn register_passkey_finish( passkey .insert(&mut transaction) .await - .wrap_internal_err("failed to create passkey object")?; + .internal_context("failed to create passkey object")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(( web::Json(PasskeyResponse { id: passkey.id.into(), @@ -3842,7 +3826,7 @@ pub async fn register_passkey_finish( StatusCode::CREATED, )) } else { - Err(ApiError::Request(eyre!( + Err(ApiError::Request(anyhow!( "flow does not exist. try restarting the passkey registration process" ))) } @@ -3872,7 +3856,7 @@ pub async fn authenticate_passkey_start( ) -> Result, ApiError> { let (mut ccr, auth_state) = webauthn .start_discoverable_authentication() - .wrap_internal_err("failed to start passkey authentication")?; + .internal_context("failed to start passkey authentication")?; // Webauthn-rs implements discoverable credentials as if they will only ever be used with // conditional UI, but as their own documentation says this has poor UX due to browser and OS @@ -3883,7 +3867,7 @@ pub async fn authenticate_passkey_start( let flow = DBFlow::AuthenticatePasskey { state: auth_state } .insert(Duration::minutes(30), &redis) .await - .wrap_internal_err("failed to store passkey authentication flow")?; + .internal_context("failed to store passkey authentication flow")?; Ok(web::Json(AuthenticatePasskeyResponse { options: ccr, @@ -3925,20 +3909,20 @@ pub async fn authenticate_passkey_finish( &redis, ) .await - .wrap_internal_err("executing `DBFlow::take_if`")?; + .internal_context("executing `DBFlow::take_if`")?; if let Some(DBFlow::AuthenticatePasskey { state }) = flow { let credential_id = response.credential.get_credential_id(); let db_passkey = DBPasskey::get_by_credential_id(credential_id, &**pool) .await - .wrap_internal_err("failed to fetch passkey")? - .wrap_request_err_with(|| "passkey not found")?; + .internal_context("failed to fetch passkey")? + .request_context_with(|| "passkey not found")?; let mut transaction = pool .begin() .await - .wrap_internal_err("failed to begin transaction")?; + .internal_context("failed to begin transaction")?; let auth_result = match webauthn.finish_discoverable_authentication( &response.credential, @@ -3949,9 +3933,7 @@ pub async fn authenticate_passkey_finish( Err(WebauthnError::CredentialPossibleCompromise) => { DBPasskey::remove(db_passkey.id, &mut transaction) .await - .wrap_internal_err( - "failed to remove compromised passkey", - )?; + .internal_context("failed to remove compromised passkey")?; // Log out all sessions let sessions = DBSession::remove_all_for_user( @@ -3959,24 +3941,24 @@ pub async fn authenticate_passkey_finish( &mut transaction, ) .await - .wrap_internal_err("failed to invalidate user sessions")?; + .internal_context("failed to invalidate user sessions")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBSession::clear_user_sessions_cache( db_passkey.user_id, sessions, &redis, ) .await - .wrap_internal_err("failed to clear user session cache")?; + .internal_context("failed to clear user session cache")?; - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "the credential may have been compromised and has been invalidated, please try another login method" ))); } - Err(e) => return Err(ApiError::Request(eyre::Report::from(e))), + Err(e) => return Err(ApiError::Request(anyhow::Error::from(e))), }; let mut updated_passkey = db_passkey.passkey; @@ -3988,9 +3970,9 @@ pub async fn authenticate_passkey_finish( &mut transaction, ) .await - .wrap_internal_err("failed to update passkey")?; + .internal_context("failed to update passkey")?; if !updated { - return Err(ApiError::Internal(eyre!( + return Err(ApiError::Internal(anyhow!( "failed to update passkey information" ))); } @@ -4003,15 +3985,15 @@ pub async fn authenticate_passkey_finish( response.app_session, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(web::Json(res)) } else { - Err(ApiError::Request(eyre!( + Err(ApiError::Request(anyhow!( "flow does not exist. try restarting the passkey authentication process" ))) } @@ -4044,12 +4026,12 @@ pub async fn list_passkeys( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let passkeys = DBPasskey::get_for_user(user.id.into(), &**pool) .await - .wrap_internal_err("failed to fetch passkeys")? + .internal_context("failed to fetch passkeys")? .into_iter() .map(|p| PasskeyResponse { id: p.id.into(), @@ -4098,35 +4080,35 @@ pub async fn rename_passkey( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; body.validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let id = DBPasskeyId( parse_base62(&info.into_inner().0) - .wrap_request_err("invalid passkey id")? as i64, + .request_context("invalid passkey id")? as i64, ); let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let found = DBPasskey::rename(id, user.id.into(), &body.name, &mut transaction) .await - .wrap_internal_err("failed to rename passkey")?; + .internal_context("failed to rename passkey")?; if !found { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().finish()) } @@ -4158,30 +4140,30 @@ pub async fn delete_passkey( Scopes::USER_AUTH_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let id = DBPasskeyId( parse_base62(&info.into_inner().0) - .wrap_request_err("invalid passkey id")? as i64, + .request_context("invalid passkey id")? as i64, ); let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let found = DBPasskey::remove_for_user(id, user.id.into(), &mut transaction) .await - .wrap_internal_err("failed to delete passkey")?; + .internal_context("failed to delete passkey")?; if !found { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().finish()) } diff --git a/apps/labrinth/src/routes/internal/gdpr.rs b/apps/labrinth/src/routes/internal/gdpr.rs index 39a230a2532..d93bed0b546 100644 --- a/apps/labrinth/src/routes/internal/gdpr.rs +++ b/apps/labrinth/src/routes/internal/gdpr.rs @@ -32,21 +32,21 @@ pub async fn export( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let user_id = user.user.id.into(); let collection_ids = crate::database::models::DBUser::get_collections(user_id, &**pool) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let collections = crate::database::models::DBCollection::get_many( &collection_ids, &**pool, &redis, ) .await - .wrap_internal_err("fetching collections from database")? + .internal_context("fetching collections from database")? .into_iter() .map(crate::models::collections::Collection::from) .collect::>(); @@ -54,7 +54,7 @@ pub async fn export( let follows = crate::database::models::DBUser::get_follows(user_id, &**pool) .await - .wrap_internal_err("fetching users from database")? + .internal_context("fetching users from database")? .into_iter() .map(crate::models::ids::ProjectId::from) .collect::>(); @@ -62,7 +62,7 @@ pub async fn export( let projects = crate::database::models::DBUser::get_projects(user_id, &**pool, &redis) .await - .wrap_internal_err("fetching users from database")? + .internal_context("fetching users from database")? .into_iter() .map(crate::models::ids::ProjectId::from) .collect::>(); @@ -70,12 +70,12 @@ pub async fn export( let org_ids = crate::database::models::DBUser::get_organizations(user_id, &**pool) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let orgs = crate::database::models::organization_item::DBOrganization::get_many_ids( &org_ids, &**pool, &redis, ) - .await.wrap_internal_err("fetching organizations from database")? + .await.internal_context("fetching organizations from database")? .into_iter() // TODO: add team members .map(|x| crate::models::organizations::Organization::from(x, vec![])) @@ -84,7 +84,7 @@ pub async fn export( let notifs = crate::database::models::notification_item::DBNotification::get_all_user( user_id, &**pool, ) - .await.wrap_internal_err("fetching notifications from database")? + .await.internal_context("fetching notifications from database")? .into_iter() .map(crate::models::notifications::Notification::from) .collect::>(); @@ -92,7 +92,7 @@ pub async fn export( let notifs_deliveries = crate::database::models::notifications_deliveries_item::DBNotificationDelivery::get_all_user( user_id, &**pool, ) - .await.wrap_internal_err("fetching notification deliveries from database")? + .await.internal_context("fetching notification deliveries from database")? .into_iter() .map(crate::models::notifications::NotificationDelivery::from) .collect::>(); @@ -101,7 +101,7 @@ pub async fn export( crate::database::models::oauth_client_item::DBOAuthClient::get_all_user_clients( user_id, &**pool, ) - .await.wrap_internal_err("fetching OAuth clients from database")? + .await.internal_context("fetching OAuth clients from database")? .into_iter() .map(crate::models::oauth_clients::OAuthClient::from) .collect::>(); @@ -109,7 +109,7 @@ pub async fn export( let oauth_authorizations = crate::database::models::oauth_client_authorization_item::DBOAuthClientAuthorization::get_all_for_user( user_id, &**pool, ) - .await.wrap_internal_err("fetching OAuth client authorizations from database")? + .await.internal_context("fetching OAuth client authorizations from database")? .into_iter() .map(crate::models::oauth_clients::OAuthClientAuthorization::from) .collect::>(); @@ -118,13 +118,13 @@ pub async fn export( crate::database::models::pat_item::DBPersonalAccessToken::get_user_pats( user_id, &**pool, &redis, ) - .await.wrap_internal_err("fetching personal access tokens from database")?; + .await.internal_context("fetching personal access tokens from database")?; let pats = crate::database::models::pat_item::DBPersonalAccessToken::get_many_ids( &pat_ids, &**pool, &redis, ) .await - .wrap_internal_err("fetching personal access tokens from database")? + .internal_context("fetching personal access tokens from database")? .into_iter() .map(|x| crate::models::pats::PersonalAccessToken::from(x, false)) .collect::>(); @@ -134,14 +134,14 @@ pub async fn export( user_id, &**pool, ) .await - .wrap_internal_err("fetching payouts from database")?; + .internal_context("fetching payouts from database")?; let payouts = crate::database::models::payout_item::DBPayout::get_many( &payout_ids, &**pool, ) .await - .wrap_internal_err("fetching payouts from database")? + .internal_context("fetching payouts from database")? .into_iter() .map(crate::models::payouts::Payout::from) .collect::>(); @@ -150,13 +150,13 @@ pub async fn export( user_id, &**pool, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let reports = crate::database::models::report_item::DBReport::get_many( &report_ids, &**pool, ) .await - .wrap_internal_err("fetching reports from database")? + .internal_context("fetching reports from database")? .into_iter() .map(crate::models::reports::Report::from) .collect::>(); @@ -168,7 +168,7 @@ pub async fn export( user_id.0 ) .fetch_all(pool.as_ref()) - .await.wrap_internal_err("fetching message IDs from database")? + .await.internal_context("fetching message IDs from database")? .into_iter() .map(|x| crate::database::models::ids::DBThreadMessageId(x.id)) .collect::>(); @@ -179,7 +179,7 @@ pub async fn export( &**pool, ) .await - .wrap_internal_err("fetching thread messages from database")? + .internal_context("fetching thread messages from database")? .into_iter() .map(|x| crate::models::threads::ThreadMessage::from(x, &user)) .collect::>(); @@ -190,7 +190,7 @@ pub async fn export( ) .fetch_all(pool.as_ref()) .await - .wrap_internal_err("fetching uploaded images IDs from database")? + .internal_context("fetching uploaded images IDs from database")? .into_iter() .map(|x| crate::database::models::ids::DBImageId(x.id)) .collect::>(); @@ -202,7 +202,7 @@ pub async fn export( &redis, ) .await - .wrap_internal_err("fetching images from database")? + .internal_context("fetching images from database")? .into_iter() .map(crate::models::images::Image::from) .collect::>(); @@ -211,7 +211,7 @@ pub async fn export( crate::database::models::user_subscription_item::DBUserSubscription::get_all_user( user_id, &**pool, ) - .await.wrap_internal_err("fetching user subscriptions from database")? + .await.internal_context("fetching user subscriptions from database")? .into_iter() .map(crate::models::billing::UserSubscription::from) .collect::>(); diff --git a/apps/labrinth/src/routes/internal/gotenberg.rs b/apps/labrinth/src/routes/internal/gotenberg.rs index fb3ef2c0d18..7b1ab6530da 100644 --- a/apps/labrinth/src/routes/internal/gotenberg.rs +++ b/apps/labrinth/src/routes/internal/gotenberg.rs @@ -59,7 +59,7 @@ pub async fn success_callback( ); let payout_id = maybe_payment_id - .wrap_request_err("no payout ID for document")? + .request_context("no payout ID for document")? .0 .0; @@ -67,7 +67,7 @@ pub async fn success_callback( let mut redis = redis .connect() .await - .wrap_internal_err("failed to get Redis connection")?; + .internal_context("failed to get Redis connection")?; let body = base64::engine::general_purpose::STANDARD.encode(&body); @@ -75,12 +75,12 @@ pub async fn success_callback( GotenbergDocument, GotenbergError, >(GotenbergDocument { body })) - .wrap_internal_err("failed to serialize Redis document response")?; + .internal_context("failed to serialize Redis document response")?; redis .lpush(&response_key, &redis_msg) .await - .wrap_internal_err("failed to send document over Redis")?; + .internal_context("failed to send document over Redis")?; Ok(()) } @@ -128,25 +128,25 @@ pub async fn error_callback( ); let payout_id = maybe_payment_id - .wrap_request_err("no payout ID for document")? + .request_context("no payout ID for document")? .0 .0; let response_key = payment_statement_key(redis.get_ref(), &payout_id); let mut redis = redis .connect() .await - .wrap_internal_err("failed to get Redis connection")?; + .internal_context("failed to get Redis connection")?; let redis_msg = postcard::to_allocvec(&Err::< GotenbergDocument, GotenbergError, >(error_body)) - .wrap_internal_err("failed to serialize Redis error response")?; + .internal_context("failed to serialize Redis error response")?; redis .lpush(&response_key, &redis_msg) .await - .wrap_internal_err("failed to send error over Redis")?; + .internal_context("failed to send error over Redis")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/medal.rs b/apps/labrinth/src/routes/internal/medal.rs index ae61c6ac121..3dfa8db0064 100644 --- a/apps/labrinth/src/routes/internal/medal.rs +++ b/apps/labrinth/src/routes/internal/medal.rs @@ -1,5 +1,6 @@ use crate::database::PgPool; use actix_web::{HttpResponse, post, web}; +use anyhow::anyhow; use ariadne::ids::UserId; use serde::{Deserialize, Serialize}; @@ -34,7 +35,7 @@ pub async fn verify( _pool: web::Data, web::Query(MedalQuery { username: _ }): web::Query, ) -> Result { - Err(ApiError::Request(eyre::eyre!( + Err(ApiError::Request(anyhow!( "This offer is no longer available" ))) @@ -46,10 +47,10 @@ pub async fn verify( Offer::Medal, ) .await - .wrap_internal_err("executing `RedeemalLookupFields::redeemal_status_by_username_and_offer`")?; + .internal_context("executing `RedeemalLookupFields::redeemal_status_by_username_and_offer`")?; match maybe_fields { - None => Err(ApiError::NotFound(eyre::eyre!("resource not found"))), + None => Err(ApiError::NotFound(anyhow!("resource not found"))), Some(fields) => Ok(HttpResponse::Ok().json(VerifyResponse { user_id: fields.user_id.into(), redeemed: fields.redeemal_status.is_some(), @@ -73,7 +74,7 @@ pub async fn redeem( // Check the offer hasn't been redeemed yet, then insert into the table. // In a transaction to avoid double inserts. - Err(ApiError::Request(eyre::eyre!( + Err(ApiError::Request(anyhow!( "This offer is no longer available" ))) @@ -81,7 +82,7 @@ pub async fn redeem( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let maybe_fields = RedeemalLookupFields::redeemal_status_by_username_and_offer( @@ -90,15 +91,15 @@ pub async fn redeem( Offer::Medal, ) .await - .wrap_internal_err("executing `RedeemalLookupFields::redeemal_status_by_username_and_offer`")?; + .internal_context("executing `RedeemalLookupFields::redeemal_status_by_username_and_offer`")?; let user_id = match maybe_fields { None => { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } Some(fields) => { if fields.redeemal_status.is_some() { - return Err(ApiError::Conflict(eyre::eyre!( + return Err(ApiError::Conflict(anyhow!( "User already redeemed this offer", ))); } @@ -121,11 +122,11 @@ pub async fn redeem( redeemal .insert(&mut txn) .await - .wrap_internal_err("inserting database records for `redeem`")?; + .internal_context("inserting database records for `redeem`")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; // Immediately try to process the redeemal if let Err(error) = try_process_user_redeemal(&pool, &redis, redeemal).await diff --git a/apps/labrinth/src/routes/internal/moderation/copyright_archives/mod.rs b/apps/labrinth/src/routes/internal/moderation/copyright_archives/mod.rs index 00a0dab6306..b55ee637731 100644 --- a/apps/labrinth/src/routes/internal/moderation/copyright_archives/mod.rs +++ b/apps/labrinth/src/routes/internal/moderation/copyright_archives/mod.rs @@ -1,5 +1,5 @@ use actix_web::{HttpRequest, delete, get, patch, put, web}; -use eyre::eyre; +use anyhow::anyhow; use serde::Deserialize; use std::collections::{HashMap, HashSet}; use xredis::RedisPool; @@ -80,7 +80,7 @@ pub async fn list( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let archives = sqlx::query!( r#" @@ -95,7 +95,7 @@ pub async fn list( ) .fetch_all(&***ro_pool) .await - .wrap_internal_err("fetching copyright archives")?; + .internal_context("fetching copyright archives")?; Ok(web::Json( archives @@ -136,19 +136,19 @@ pub async fn create( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let body = body.into_inner(); let mut transaction = pool .begin() .await - .wrap_internal_err("starting copyright archive transaction")?; + .internal_context("starting copyright archive transaction")?; let mut ids = Vec::with_capacity(body.len()); for archive in body { let id = generate_copyright_archive_id(&mut transaction) .await - .wrap_internal_err("generating copyright archive ID")?; + .internal_context("generating copyright archive ID")?; replace_archive(id, archive, &mut transaction).await?; ids.push(id.into()); } @@ -156,7 +156,7 @@ pub async fn create( transaction .commit() .await - .wrap_internal_err("committing copyright archive transaction")?; + .internal_context("committing copyright archive transaction")?; Ok(web::Json(ids)) } @@ -191,13 +191,13 @@ pub async fn replace( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let body = body.into_inner(); let mut seen = HashSet::new(); for archive in &body { if !seen.insert(archive.id) { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "duplicate copyright archive ID `{}`", archive.id, ))); @@ -210,7 +210,7 @@ pub async fn replace( let mut transaction = pool .begin() .await - .wrap_internal_err("starting copyright archive transaction")?; + .internal_context("starting copyright archive transaction")?; let archives = sqlx::query!( r#" @@ -223,7 +223,7 @@ pub async fn replace( ) .fetch_all(&mut transaction) .await - .wrap_internal_err("locking copyright archives")?; + .internal_context("locking copyright archives")?; if archives.len() != ids.len() { let found: HashSet<_> = @@ -235,7 +235,7 @@ pub async fn replace( }) .map(|archive| format!("`{}`", archive.id)) .collect(); - return Err(ApiError::NotFound(eyre!( + return Err(ApiError::NotFound(anyhow!( "copyright archives not found: {}", missing.join(", "), ))); @@ -249,7 +249,7 @@ pub async fn replace( transaction .commit() .await - .wrap_internal_err("committing copyright archive transaction")?; + .internal_context("committing copyright archive transaction")?; Ok(()) } @@ -279,7 +279,7 @@ pub async fn delete( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let ids: Vec<_> = body .into_inner() @@ -289,7 +289,7 @@ pub async fn delete( let mut transaction = pool .begin() .await - .wrap_internal_err("starting copyright archive transaction")?; + .internal_context("starting copyright archive transaction")?; sqlx::query!( r#" @@ -302,7 +302,7 @@ pub async fn delete( ) .fetch_all(&mut transaction) .await - .wrap_internal_err("locking copyright archives")?; + .internal_context("locking copyright archives")?; sqlx::query!( r#" @@ -312,12 +312,12 @@ pub async fn delete( ) .execute(&mut transaction) .await - .wrap_internal_err("deleting copyright archives")?; + .internal_context("deleting copyright archives")?; transaction .commit() .await - .wrap_internal_err("committing copyright archive transaction")?; + .internal_context("committing copyright archive transaction")?; Ok(()) } @@ -330,7 +330,7 @@ async fn replace_archive( let mut paths = HashMap::new(); for file in &body.files { if let Some(previous_hash) = paths.insert(&file.path, &file.sha512) { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "duplicate archive file path `{}` with SHA-512 hashes `{}` and `{}`", file.path, hex::encode(previous_hash), @@ -347,7 +347,7 @@ async fn replace_archive( ) .execute(&mut *transaction) .await - .wrap_internal_err("deleting copyright archive files")?; + .internal_context("deleting copyright archive files")?; let meta = sqlx::types::Json(body.meta); sqlx::query!( @@ -361,7 +361,7 @@ async fn replace_archive( ) .execute(&mut *transaction) .await - .wrap_internal_err("replacing copyright archive")?; + .internal_context("replacing copyright archive")?; let (paths, hashes): (Vec<_>, Vec<_>) = body .files @@ -380,7 +380,7 @@ async fn replace_archive( ) .execute(transaction) .await - .wrap_internal_err("inserting copyright archive files")?; + .internal_context("inserting copyright archive files")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/moderation/external_license.rs b/apps/labrinth/src/routes/internal/moderation/external_license.rs index 5da4d85e18e..43cc6cc8d6b 100644 --- a/apps/labrinth/src/routes/internal/moderation/external_license.rs +++ b/apps/labrinth/src/routes/internal/moderation/external_license.rs @@ -1,5 +1,6 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context as _; +use anyhow::anyhow; use std::collections::HashMap; use actix_web::{HttpRequest, get, patch, post, web}; @@ -101,9 +102,9 @@ impl LicenseId { match self { LicenseId::Number(id) => Ok(id), LicenseId::String(id) => id.parse().map_err(|_| { - ApiError::Request(eyre::eyre!( - "license_id must be a valid integer", - )) + ApiError::Request( + anyhow!("license_id must be a valid integer",), + ) }), } } @@ -145,7 +146,7 @@ fn normalize_sha1_hashes(hashes: &[String]) -> Result, ApiError> { let hash = hash.trim().to_lowercase(); if hash.len() != 40 || !hash.chars().all(|c| c.is_ascii_hexdigit()) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "hash must be a valid SHA1 hex string", ))); } @@ -199,7 +200,7 @@ async fn fetch_linked_files( ) .fetch_all(pool) .await - .wrap_internal_err("fetching file rows from database")?; + .internal_context("fetching file rows from database")?; let mut map: HashMap> = HashMap::new(); for row in file_rows { @@ -250,12 +251,12 @@ async fn fetch_by_hashes( &hash_bytes, ) .fetch_all(pool) - .await.wrap_internal_err("querying database for `fetch_by_hashes`")?; + .await.internal_context("querying database for `fetch_by_hashes`")?; let license_ids = rows.iter().map(|row| row.id).collect::>(); let files_map = fetch_linked_files(pool, &license_ids) .await - .wrap_api_err("fetching linked files")?; + .api_context("fetching linked files")?; let mut results = HashMap::new(); for row in rows { @@ -315,12 +316,12 @@ async fn fetch_by_flame_ids( ) .fetch_all(pool) .await - .wrap_internal_err("querying database for `fetch_by_flame_ids`")?; + .internal_context("querying database for `fetch_by_flame_ids`")?; let license_ids = rows.iter().map(|row| row.id).collect::>(); let files_map = fetch_linked_files(pool, &license_ids) .await - .wrap_api_err("fetching linked files")?; + .api_context("fetching linked files")?; let mut results: HashMap> = HashMap::new(); for row in rows { @@ -359,7 +360,7 @@ pub async fn search( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating external license search")?; + .auth_context("authenticating external license search")?; let rows = sqlx::query_as!( LicenseRow, @@ -391,12 +392,12 @@ pub async fn search( ) .fetch_all(&**pool) .await - .wrap_internal_err("querying database for `search`")?; + .internal_context("querying database for `search`")?; let license_ids: Vec = rows.iter().map(|r| r.id).collect(); let files_map = fetch_linked_files(&pool, &license_ids) .await - .wrap_api_err("fetching linked files")?; + .api_context("fetching linked files")?; let results = rows .into_iter() @@ -432,17 +433,17 @@ pub async fn lookup( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let body = body.into_inner(); let hashes = normalize_sha1_hashes(&body.hashes) - .wrap_api_err("executing `normalize_sha1_hashes`")?; + .api_context("executing `normalize_sha1_hashes`")?; let flame_ids = fetch_by_flame_ids(&pool, &body.flame_ids) .await - .wrap_api_err("fetching by flame ids")?; + .api_context("fetching by flame ids")?; let hashes = fetch_by_hashes(&pool, &hashes) .await - .wrap_api_err("fetching by hashes")?; + .api_context("fetching by hashes")?; Ok(web::Json(ExternalLicenseLookupResponse { flame_ids, @@ -472,17 +473,17 @@ pub async fn get_by_sha1( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let hashes = normalize_sha1_hashes(&[path.into_inner().0]) - .wrap_api_err("normalizing SHA-1 hash")?; - let hash = hashes.first().wrap_not_found_err("resource not found")?; + .api_context("normalizing SHA-1 hash")?; + let hash = hashes.first().not_found_context("resource not found")?; let mut results = fetch_by_hashes(&pool, &hashes) .await - .wrap_api_err("fetching by hashes")?; + .api_context("fetching by hashes")?; let result = results .remove(hash) - .wrap_not_found_err("resource not found")?; + .not_found_context("resource not found")?; Ok(web::Json(result)) } @@ -509,13 +510,13 @@ pub async fn get_by_sha1_bulk( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let hashes = normalize_sha1_hashes(&body.hashes) - .wrap_api_err("executing `normalize_sha1_hashes`")?; + .api_context("executing `normalize_sha1_hashes`")?; let results = fetch_by_hashes(&pool, &hashes) .await - .wrap_api_err("fetching by hashes")?; + .api_context("fetching by hashes")?; Ok(web::Json(results)) } @@ -569,21 +570,21 @@ async fn upsert_file_license( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let body = body.into_inner(); let license_id = body .license_id .parse() - .wrap_api_err("parsing external license ID")?; + .api_context("parsing external license ID")?; if body.hashes.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "hashes must contain at least one SHA1 hex string", ))); } let hashes = normalize_sha1_hashes(&body.hashes) - .wrap_api_err("executing `normalize_sha1_hashes`")?; + .api_context("executing `normalize_sha1_hashes`")?; let hash_bytes = hashes .iter() .map(|hash| hash.as_bytes().to_vec()) @@ -594,7 +595,7 @@ async fn upsert_file_license( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let license = sqlx::query!( r#" @@ -617,8 +618,8 @@ async fn upsert_file_license( ) .fetch_optional(&mut transaction) .await - .wrap_internal_err("fetching license from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching license from database")? + .not_found_context("resource not found")?; ExternalLicense::insert_files( &mut transaction, @@ -628,18 +629,16 @@ async fn upsert_file_license( DBUserId(user.id.0 as i64), ) .await - .wrap_internal_err( - "inserting database records for `upsert_file_license`", - )?; + .internal_context("inserting database records for `upsert_file_license`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; let files_map = fetch_linked_files(&pool, &[license_id]) .await - .wrap_api_err("fetching linked files")?; + .api_context("fetching linked files")?; let linked_files = files_map.get(&license_id).cloned().unwrap_or_default(); Ok(web::Json( @@ -683,7 +682,7 @@ pub async fn update_license( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let id = path.into_inner().0; @@ -715,12 +714,12 @@ pub async fn update_license( ) .fetch_optional(&**pool) .await - .wrap_internal_err("querying database for `update_license`")? - .wrap_not_found_err("resource not found")?; + .internal_context("querying database for `update_license`")? + .not_found_context("resource not found")?; let files_map = fetch_linked_files(&pool, &[id]) .await - .wrap_api_err("fetching linked files")?; + .api_context("fetching linked files")?; let linked_files = files_map.get(&id).cloned().unwrap_or_default(); Ok(web::Json( diff --git a/apps/labrinth/src/routes/internal/moderation/mod.rs b/apps/labrinth/src/routes/internal/moderation/mod.rs index 2c365a33eb6..c350b387188 100644 --- a/apps/labrinth/src/routes/internal/moderation/mod.rs +++ b/apps/labrinth/src/routes/internal/moderation/mod.rs @@ -18,9 +18,9 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context; use crate::{auth::get_user_from_bearer_token, models::pats::Scopes}; use actix_web::{HttpRequest, delete, get, post, web}; +use anyhow::anyhow; use ariadne::ids::{UserId, random_base62}; use chrono::{DateTime, Utc}; -use eyre::eyre; use futures_util::future::try_join_all; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -277,7 +277,7 @@ pub async fn get_projects_internal( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let request_opts = request_opts.into_inner(); let query = normalize_optional_string(request_opts.query.as_deref()); @@ -523,7 +523,7 @@ pub async fn get_projects_internal( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch filtered projects awaiting review")?; + .internal_context("failed to fetch filtered projects awaiting review")?; let total = project_rows.first().map(|row| row.total_count).unwrap_or(0); @@ -550,7 +550,7 @@ pub async fn get_projects_internal( row.project_types, row.external_dependencies_count, ) - .wrap_api_err("executing `row_to_queue_project`")? + .api_context("executing `row_to_queue_project`")? { projects.push(project); } @@ -706,7 +706,7 @@ pub async fn get_projects_internal( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch projects awaiting review")?; + .internal_context("failed to fetch projects awaiting review")?; let total = project_rows.first().map(|row| row.total_count).unwrap_or(0); @@ -733,7 +733,7 @@ pub async fn get_projects_internal( row.project_types, row.external_dependencies_count, ) - .wrap_api_err("executing `row_to_queue_project`")? + .api_context("executing `row_to_queue_project`")? { projects.push(project); } @@ -773,7 +773,7 @@ pub async fn get_project_ids( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let request_opts = request_opts.into_inner(); let query = normalize_optional_string(request_opts.query.as_deref()); @@ -922,7 +922,7 @@ pub async fn get_project_ids( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch filtered project ids awaiting review")?; + .internal_context("failed to fetch filtered project ids awaiting review")?; project_rows .into_iter() @@ -955,7 +955,7 @@ pub async fn get_project_ids( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch project ids awaiting review")?; + .internal_context("failed to fetch project ids awaiting review")?; project_rows .into_iter() @@ -992,26 +992,28 @@ fn row_to_queue_project( }; let project_id = ProjectId::from(database::models::DBProjectId(id)); - let name = name.wrap_internal_err_with(|| { - eyre!("project {project_id} is missing `name` in moderation queue row") + let name = name.internal_context_with(|| { + anyhow!( + "project {project_id} is missing `name` in moderation queue row" + ) })?; - let summary = summary.wrap_internal_err_with(|| { - eyre!( + let summary = summary.internal_context_with(|| { + anyhow!( "project {project_id} is missing `summary` in moderation queue row" ) })?; - let status = status.wrap_internal_err_with(|| { - eyre!( + let status = status.internal_context_with(|| { + anyhow!( "project {project_id} is missing `status` in moderation queue row" ) })?; - let published = published.wrap_internal_err_with(|| { - eyre!( + let published = published.internal_context_with(|| { + anyhow!( "project {project_id} is missing `published` in moderation queue row" ) })?; - let updated = updated.wrap_internal_err_with(|| { - eyre!( + let updated = updated.internal_context_with(|| { + anyhow!( "project {project_id} is missing `updated` in moderation queue row" ) })?; @@ -1024,7 +1026,7 @@ fn row_to_queue_project( owner_name, owner_icon_url, ) - .wrap_api_err("executing `row_to_ownership`")?; + .api_context("executing `row_to_ownership`")?; Ok(Some(ModerationQueueProject { id: project_id, @@ -1068,8 +1070,8 @@ fn row_to_ownership( ) -> Result { if let Some(organization_id) = organization_id { let organization_name = - organization_name.wrap_internal_err_with(|| { - eyre!( + organization_name.internal_context_with(|| { + anyhow!( "project {project_id} is owned by organization {} without a valid name", OrganizationId::from(database::models::DBOrganizationId( organization_id @@ -1086,11 +1088,11 @@ fn row_to_ownership( }); } - let owner_id = owner_id.wrap_internal_err_with(|| { - eyre!("project {project_id} is owned by a team without a valid owner") + let owner_id = owner_id.internal_context_with(|| { + anyhow!("project {project_id} is owned by a team without a valid owner") })?; - let owner_name = owner_name.wrap_internal_err_with(|| { - eyre!( + let owner_name = owner_name.internal_context_with(|| { + anyhow!( "project {project_id} is owned by a team owner without a valid name" ) })?; @@ -1124,13 +1126,13 @@ pub async fn get_project_meta( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let project_id = info.into_inner().0; let project = database::models::DBProject::get(&project_id, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; if let Some(project) = project { let rows = sqlx::query!( @@ -1145,7 +1147,7 @@ pub async fn get_project_meta( ) .fetch_all(&**pool) .await - .wrap_internal_err("querying database for `get_project_meta`")?; + .internal_context("querying database for `get_project_meta`")?; let mut merged = MissingMetadata { identified: HashMap::new(), @@ -1185,7 +1187,7 @@ pub async fn get_project_meta( .collect::>() ) .fetch_all(&**pool) - .await.wrap_internal_err("querying database for `get_project_meta`")?; + .await.internal_context("querying database for `get_project_meta`")?; for row in rows { if let Some(sha1) = row.sha1 { @@ -1221,7 +1223,7 @@ pub async fn get_project_meta( ) .fetch_all(&**pool) .await - .wrap_internal_err("querying database for `get_project_meta`")?; + .internal_context("querying database for `get_project_meta`")?; for row in rows { if let Some(sha1) = merged @@ -1244,7 +1246,7 @@ pub async fn get_project_meta( Ok(web::Json(merged)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1287,13 +1289,13 @@ pub async fn set_project_meta( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut licenses = Vec::new(); let mut file_hashes = Vec::new(); @@ -1345,7 +1347,7 @@ pub async fn set_project_meta( user_id, ) .await - .wrap_internal_err("inserting database records for `set_project_meta`")?; + .internal_context("inserting database records for `set_project_meta`")?; moderation_external_item::ExternalLicense::insert_files( &mut transaction, @@ -1358,12 +1360,12 @@ pub async fn set_project_meta( user_id, ) .await - .wrap_internal_err("inserting database records for `set_project_meta`")?; + .internal_context("inserting database records for `set_project_meta`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(()) } @@ -1394,22 +1396,22 @@ pub async fn acquire_lock( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let project_id_str = path.into_inner().0; let project = database::models::DBProject::get(&project_id_str, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching project from database")? + .not_found_context("resource not found")?; let db_project_id = project.inner.id; let db_user_id = database::models::DBUserId::from(user.id); match DBModerationLock::acquire(db_project_id, db_user_id, &pool) .await - .wrap_internal_err("executing `DBModerationLock::acquire`")? + .internal_context("executing `DBModerationLock::acquire`")? { Ok(()) => Ok(web::Json(LockAcquireResponse { success: true, @@ -1459,22 +1461,22 @@ pub async fn override_lock( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let project_id_str = path.into_inner().0; let project = database::models::DBProject::get(&project_id_str, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching project from database")? + .not_found_context("resource not found")?; let db_project_id = project.inner.id; let db_user_id = database::models::DBUserId::from(user.id); DBModerationLock::force_acquire(db_project_id, db_user_id, &pool) .await - .wrap_internal_err("executing `DBModerationLock::force_acquire`")?; + .internal_context("executing `DBModerationLock::force_acquire`")?; Ok(web::Json(LockAcquireResponse { success: true, @@ -1508,11 +1510,11 @@ pub async fn get_lock_statuses( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let locks = DBModerationLock::get_all_with_user(&ro_pool) .await - .wrap_internal_err("fetching moderation locks from database")?; + .internal_context("fetching moderation locks from database")?; let user_id = DBUserId::from(user.id); Ok(web::Json( locks @@ -1580,22 +1582,22 @@ pub async fn get_lock_status( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let project_id_str = path.into_inner().0; let project = database::models::DBProject::get(&project_id_str, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching project from database")? + .not_found_context("resource not found")?; let db_project_id = project.inner.id; let db_user_id = database::models::DBUserId::from(user.id); let lock = DBModerationLock::get_with_user(db_project_id, &pool) .await - .wrap_internal_err("fetching moderation lock from database")?; + .internal_context("fetching moderation lock from database")?; Ok(web::Json(lock_status_response(lock, db_user_id))) } @@ -1624,22 +1626,22 @@ pub async fn release_lock( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let project_id_str = path.into_inner().0; let project = database::models::DBProject::get(&project_id_str, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching project from database")? + .not_found_context("resource not found")?; let db_project_id = project.inner.id; let db_user_id = database::models::DBUserId::from(user.id); let released = DBModerationLock::release(db_project_id, db_user_id, &pool) .await - .wrap_internal_err("executing `DBModerationLock::release`")?; + .internal_context("executing `DBModerationLock::release`")?; let _ = DBModerationLock::cleanup_expired(&pool).await; @@ -1675,7 +1677,7 @@ pub async fn release_lock_beacon( ) -> Result, ApiError> { let token = body.trim(); if token.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "missing token in request body", ))); } @@ -1690,10 +1692,10 @@ pub async fn release_lock_beacon( false, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "only moderators may release moderation locks", ))); } @@ -1703,15 +1705,15 @@ pub async fn release_lock_beacon( let project = database::models::DBProject::get(&project_id_str, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching project from database")? + .not_found_context("resource not found")?; let db_project_id = project.inner.id; let db_user_id = database::models::DBUserId::from(user.id); let released = DBModerationLock::release(db_project_id, db_user_id, &pool) .await - .wrap_internal_err("executing `DBModerationLock::release`")?; + .internal_context("executing `DBModerationLock::release`")?; let _ = DBModerationLock::cleanup_expired(&pool).await; @@ -1742,17 +1744,17 @@ pub async fn delete_all_locks( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You must be an admin to delete all locks", ))); } let deleted_count = DBModerationLock::delete_all(&pool) .await - .wrap_internal_err("deleting moderation locks from database")?; + .internal_context("deleting moderation locks from database")?; Ok(web::Json(DeleteAllLocksResponse { deleted_count })) } @@ -1782,13 +1784,13 @@ pub async fn get_user_project_by_status( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let target_user = database::models::DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching user from database")? + .not_found_context("resource not found")?; let counts = user_projects_by_status(target_user.id, &**pool, &redis).await?; @@ -1826,10 +1828,10 @@ pub async fn get_users_project_by_status( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let user_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; if user_ids.is_empty() { return Ok(web::Json(HashMap::new())); @@ -1838,7 +1840,7 @@ pub async fn get_users_project_by_status( let target_users = database::models::DBUser::get_many(&user_ids, &**pool, &redis) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let pool_ref = &**pool; let redis_ref = &*redis; @@ -1883,7 +1885,7 @@ pub async fn get_organization_project_by_status( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let target_org = database::models::DBOrganization::get( &info.into_inner().0, @@ -1891,8 +1893,8 @@ pub async fn get_organization_project_by_status( &redis, ) .await - .wrap_internal_err("fetching organization from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching organization from database")? + .not_found_context("resource not found")?; let grouped_projects = organization_projects_by_status(target_org.id, &**pool, &redis).await?; @@ -1931,10 +1933,10 @@ pub async fn get_organizations_project_by_status( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let organization_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; if organization_ids.is_empty() { return Ok(web::Json(HashMap::new())); @@ -1946,7 +1948,7 @@ pub async fn get_organizations_project_by_status( &redis, ) .await - .wrap_internal_err("fetching organizations from database")?; + .internal_context("fetching organizations from database")?; let pool_ref = &**pool; let redis_ref = &*redis; @@ -1983,7 +1985,7 @@ where let project_ids = database::models::DBUser::get_projects(user_id, pool, redis) .await - .wrap_internal_err("fetching user's projects from database")?; + .internal_context("fetching user's projects from database")?; group_projects_by_status(&project_ids, pool, redis).await } @@ -2001,7 +2003,7 @@ where { let project_ids = DBOrganization::get_projects(organization_id, pool) .await - .wrap_internal_err("fetching project IDs from database")?; + .internal_context("fetching project IDs from database")?; group_projects_by_status(&project_ids, pool, redis).await } @@ -2023,7 +2025,7 @@ where let projects = DBProject::get_many_ids(project_ids, pool, redis) .await - .wrap_internal_err("fetching projects from database")?; + .internal_context("fetching projects from database")?; let mut grouped_projects: HashMap> = HashMap::new(); diff --git a/apps/labrinth/src/routes/internal/moderation/ownership.rs b/apps/labrinth/src/routes/internal/moderation/ownership.rs index ac60c886e30..033428ca1f4 100644 --- a/apps/labrinth/src/routes/internal/moderation/ownership.rs +++ b/apps/labrinth/src/routes/internal/moderation/ownership.rs @@ -3,8 +3,8 @@ use crate::database::models::{DBOrganization, DBTeamId, DBTeamMember, DBUser}; use crate::models::ids::OrganizationId; use crate::routes::internal::moderation::Ownership; use crate::util::error::Context; +use anyhow::anyhow; use ariadne::ids::UserId; -use eyre::eyre; use xredis::RedisPool; /// Fetches ownership information for multiple projects efficiently @@ -26,7 +26,7 @@ pub async fn get_projects_ownership( let team_members = DBTeamMember::get_from_team_full_many(&team_ids, pool, redis) .await - .wrap_internal_err("failed to fetch team members")?; + .internal_context("failed to fetch team members")?; let users = DBUser::get_many_ids( &team_members .iter() @@ -36,10 +36,10 @@ pub async fn get_projects_ownership( redis, ) .await - .wrap_internal_err("failed to fetch user data of team members")?; + .internal_context("failed to fetch user data of team members")?; let orgs = DBOrganization::get_many(&org_ids, pool, redis) .await - .wrap_internal_err("failed to fetch organizations")?; + .internal_context("failed to fetch organizations")?; let mut ownerships = Vec::with_capacity(projects.len()); @@ -49,8 +49,8 @@ pub async fn get_projects_ownership( let org = orgs .iter() .find(|org| OrganizationId::from(org.id) == org_id) - .wrap_internal_err_with(|| { - eyre!( + .internal_context_with(|| { + anyhow!( "project {project_id} is owned by an invalid organization {org_id}" ) })?; @@ -65,10 +65,10 @@ pub async fn get_projects_ownership( let team_owner = team_members.iter().find(|member| { crate::models::ids::TeamId::from(member.team_id) == team_id && member.is_owner }) - .wrap_internal_err_with(|| eyre!("project {project_id} is owned by a team {team_id} which has no valid owner"))?; + .internal_context_with(|| anyhow!("project {project_id} is owned by a team {team_id} which has no valid owner"))?; let team_owner_id = team_owner.user_id; let user = users.iter().find(|user| user.id == team_owner_id) - .wrap_internal_err_with(|| eyre!("project {project_id} is owned by a team {team_id} which has owner {} which does not exist", UserId::from(team_owner_id)))?; + .internal_context_with(|| anyhow!("project {project_id} is owned by a team {team_id} which has owner {} which does not exist", UserId::from(team_owner_id)))?; Ownership::User { id: ariadne::ids::UserId::from(user.id), diff --git a/apps/labrinth/src/routes/internal/moderation/project_flag/project.rs b/apps/labrinth/src/routes/internal/moderation/project_flag/project.rs index d6ccb56f816..3d4c95fb13c 100644 --- a/apps/labrinth/src/routes/internal/moderation/project_flag/project.rs +++ b/apps/labrinth/src/routes/internal/moderation/project_flag/project.rs @@ -37,13 +37,13 @@ pub async fn get_project_flags( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; let project_id = path.into_inner().into(); let flags = DBProjectFlag::get_project_flags(project_id, &ro_pool) .await - .wrap_internal_err("fetching project flags")? - .wrap_not_found_err("project not found")?; + .internal_context("fetching project flags")? + .not_found_context("project not found")?; Ok(web::Json(flags)) } diff --git a/apps/labrinth/src/routes/internal/moderation/project_flag/rule.rs b/apps/labrinth/src/routes/internal/moderation/project_flag/rule.rs index dbfe98e264f..55ac8f3318c 100644 --- a/apps/labrinth/src/routes/internal/moderation/project_flag/rule.rs +++ b/apps/labrinth/src/routes/internal/moderation/project_flag/rule.rs @@ -1,5 +1,5 @@ use actix_web::{HttpRequest, delete, get, post, put, web}; -use eyre::eyre; +use anyhow::anyhow; use serde::Deserialize; use validator::Validate; use xredis::RedisPool; @@ -52,11 +52,11 @@ pub async fn get_rule_schema( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; Ok(web::Json( schema_example::generate::() - .wrap_internal_err("generating project flag context example")?, + .internal_context("generating project flag context example")?, )) } @@ -95,10 +95,10 @@ pub async fn list_rules( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; if query.limit == 0 || query.limit > 200 { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "`limit` must be between 1 and 200" ))); } @@ -108,7 +108,7 @@ pub async fn list_rules( &ro_pool, ) .await - .wrap_internal_err("listing project flag rules")?; + .internal_context("listing project flag rules")?; Ok(web::Json(rules)) } @@ -134,12 +134,12 @@ pub async fn get_rule( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; let rule = DBProjectFlagRule::get(path.into_inner(), &ro_pool) .await - .wrap_internal_err("fetching project flag rule")? - .wrap_not_found_err("project flag rule not found")?; + .internal_context("fetching project flag rule")? + .not_found_context("project flag rule not found")?; Ok(web::Json(rule)) } @@ -176,9 +176,9 @@ pub async fn create_rule( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; body.validate().map_err(|error| { - ApiError::Request(eyre!(validation_errors_to_string(error, None))) + ApiError::Request(anyhow!(validation_errors_to_string(error, None))) })?; let rule = DBProjectFlagRule::create( @@ -188,7 +188,7 @@ pub async fn create_rule( &pool, ) .await - .wrap_internal_err("creating project flag rule")?; + .internal_context("creating project flag rule")?; Ok(web::Json(rule)) } @@ -216,9 +216,9 @@ pub async fn update_rule( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; body.validate().map_err(|error| { - ApiError::Request(eyre!(validation_errors_to_string(error, None))) + ApiError::Request(anyhow!(validation_errors_to_string(error, None))) })?; let rule = DBProjectFlagRule::update( @@ -229,8 +229,8 @@ pub async fn update_rule( &pool, ) .await - .wrap_internal_err("updating project flag rule")? - .wrap_not_found_err("project flag rule not found")?; + .internal_context("updating project flag rule")? + .not_found_context("project flag rule not found")?; Ok(web::Json(rule)) } @@ -256,13 +256,13 @@ pub async fn delete_rule( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; if !DBProjectFlagRule::delete(path.into_inner(), &pool) .await - .wrap_internal_err("deleting project flag rule")? + .internal_context("deleting project flag rule")? { - return Err(ApiError::NotFound(eyre!("project flag rule not found"))); + return Err(ApiError::NotFound(anyhow!("project flag rule not found"))); } Ok(()) } @@ -313,10 +313,10 @@ pub async fn list_run_results( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; if query.limit == 0 || query.limit > 200 { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "`limit` must be between 1 and 200" ))); } @@ -327,8 +327,8 @@ pub async fn list_run_results( &ro_pool, ) .await - .wrap_internal_err("listing project flag run results")? - .wrap_not_found_err("project flag run not found")?; + .internal_context("listing project flag run results")? + .not_found_context("project flag run not found")?; Ok(web::Json(results)) } @@ -361,12 +361,12 @@ pub async fn get_run_activity( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; let (num_scanning, num_consumers) = tokio::try_join!( DBProjectFlagRun::num_scanning(&ro_pool), kafka.project_flag_scan_consumers(), ) - .wrap_internal_err("fetching project flag scan activity")?; + .internal_context("fetching project flag scan activity")?; Ok(web::Json(ProjectFlagRunActivity { num_scanning, num_consumers, @@ -405,10 +405,10 @@ pub async fn list_runs( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; if query.limit == 0 || query.limit > 200 { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "`limit` must be between 1 and 200" ))); } @@ -418,7 +418,7 @@ pub async fn list_runs( &ro_pool, ) .await - .wrap_internal_err("listing project flag runs")?; + .internal_context("listing project flag runs")?; let num_queued = if runs .iter() .any(|run| run.status == ProjectFlagRunStatus::Running) @@ -426,7 +426,7 @@ pub async fn list_runs( kafka .project_flag_scan_lag() .await - .wrap_internal_err("fetching project flag scan lag")? + .internal_context("fetching project flag scan lag")? } else { 0 }; @@ -459,18 +459,18 @@ pub async fn start_run( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; let rules = DBProjectFlagRule::all(&pool) .await - .wrap_internal_err("snapshotting project flag rules")?; + .internal_context("snapshotting project flag rules")?; let project_ids = DBProjectFlagRun::queued_project_ids(&pool) .await - .wrap_internal_err("fetching queued project IDs")?; + .internal_context("fetching queued project IDs")?; let mut run = DBProjectFlagRun::create(user.user.id.into(), &project_ids, &pool) .await - .wrap_internal_err("creating project flag run")?; + .internal_context("creating project flag run")?; let response_kafka = kafka.clone(); // Keep dispatch alive if the caller disconnects while Kafka is publishing. @@ -486,23 +486,23 @@ pub async fn start_run( } run.finish(Some(format!("{error:#}")), &pool) .await - .wrap_internal_err("recording project flag run dispatch failure")?; + .internal_context("recording project flag run dispatch failure")?; return Err(ApiError::Internal(error)); } if empty { run.finish(None, &pool) .await - .wrap_internal_err("completing empty project flag run")?; + .internal_context("completing empty project flag run")?; } Ok(run) }) .await - .wrap_internal_err("joining project flag run dispatch")??; + .internal_context("joining project flag run dispatch")??; let num_queued = if run.status == ProjectFlagRunStatus::Running { response_kafka .project_flag_scan_lag() .await - .wrap_internal_err("fetching project flag scan lag")? + .internal_context("fetching project flag scan lag")? } else { 0 }; @@ -533,13 +533,13 @@ pub async fn delete_run( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; let id = path.into_inner(); if !DBProjectFlagRun::delete(id, &pool) .await - .wrap_internal_err("deleting project flag run")? + .internal_context("deleting project flag run")? { - return Err(ApiError::NotFound(eyre!("project flag run not found"))); + return Err(ApiError::NotFound(anyhow!("project flag run not found"))); } let cleanup = async { let mut connection = redis.connect().await?; @@ -548,7 +548,7 @@ pub async fn delete_run( .arg(key) .query_async::(&mut connection) .await?; - eyre::Ok(()) + anyhow::Ok(()) } .await; if let Err(error) = cleanup { @@ -591,26 +591,26 @@ pub async fn eval_rule( Scopes::SESSION_ACCESS | Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating moderator")?; + .auth_context("authenticating moderator")?; body.validate().map_err(|error| { - ApiError::Request(eyre!(validation_errors_to_string(error, None))) + ApiError::Request(anyhow!(validation_errors_to_string(error, None))) })?; let body = body.into_inner(); let project_id = body.project_id.into(); DBProject::get_id(project_id, &***ro_pool, &redis) .await - .wrap_internal_err("fetching project for flag evaluation")? - .wrap_not_found_err("project not found")?; + .internal_context("fetching project for flag evaluation")? + .not_found_context("project not found")?; let compile_engine = engine.clone(); let call = tokio::task::spawn_blocking(move || { compile_engine.make_call(&body.params) }) .await - .wrap_internal_err("joining project flag compilation")? - .wrap_request_err("compiling project flag expression")?; + .internal_context("joining project flag compilation")? + .request_context("compiling project flag expression")?; let evaluation = engine .scan_flags_with_log(&call, project_id) .await - .wrap_request_err("evaluating project flag expression")?; + .request_context("evaluating project flag expression")?; Ok(web::Json(evaluation)) } diff --git a/apps/labrinth/src/routes/internal/moderation/project_flag/schema_example.rs b/apps/labrinth/src/routes/internal/moderation/project_flag/schema_example.rs index f7ed6a4bdca..299450e36fc 100644 --- a/apps/labrinth/src/routes/internal/moderation/project_flag/schema_example.rs +++ b/apps/labrinth/src/routes/internal/moderation/project_flag/schema_example.rs @@ -1,9 +1,9 @@ -use eyre::{Context, Result}; +use anyhow::{Context, Result}; use serde_json::{Map, Value, json}; pub(super) fn generate() -> Result { let schema = serde_json::to_value(T::schema()) - .wrap_err("serializing input schema")?; + .context("serializing input schema")?; let mut schemas = Vec::new(); T::schemas(&mut schemas); let components = schemas @@ -11,7 +11,7 @@ pub(super) fn generate() -> Result { .map(|(name, schema)| { serde_json::to_value(schema) .map(|schema| (name, schema)) - .wrap_err("serializing component schema") + .context("serializing component schema") }) .collect::>>()?; Ok(example(&schema, &components, &mut Vec::new(), 0)) diff --git a/apps/labrinth/src/routes/internal/moderation/tech_review.rs b/apps/labrinth/src/routes/internal/moderation/tech_review.rs index ff7a59b99ff..2e371b86bbd 100644 --- a/apps/labrinth/src/routes/internal/moderation/tech_review.rs +++ b/apps/labrinth/src/routes/internal/moderation/tech_review.rs @@ -42,8 +42,8 @@ use crate::{ search::SearchState, util::error::Context, }; +use anyhow::anyhow; use ariadne::ids::UserId; -use eyre::eyre; use futures_util::future::try_join_all; pub mod global; @@ -244,7 +244,7 @@ pub async fn get_issue( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (issue_id,) = path.into_inner(); let row = sqlx::query!( @@ -282,8 +282,8 @@ pub async fn get_issue( ) .fetch_optional(&**pool) .await - .wrap_internal_err("failed to fetch issue from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch issue from database")? + .not_found_context("resource not found")?; Ok(web::Json(row.data.0)) } @@ -311,7 +311,7 @@ pub async fn get_report( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (report_id,) = path.into_inner(); @@ -386,8 +386,8 @@ pub async fn get_report( ) .fetch_optional(&**pool) .await - .wrap_internal_err("failed to fetch report from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch report from database")? + .not_found_context("resource not found")?; Ok(web::Json(row.data.0)) } @@ -492,7 +492,7 @@ async fn fetch_project_reports( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch version ids")?; + .internal_context("failed to fetch version ids")?; let version_ids: Vec = version_id_rows .into_iter() @@ -501,7 +501,7 @@ async fn fetch_project_reports( let versions = DBVersion::get_many(&version_ids, pool, redis) .await - .wrap_internal_err("failed to fetch versions")?; + .internal_context("failed to fetch versions")?; let file_rows = sqlx::query!( r#" @@ -519,7 +519,7 @@ async fn fetch_project_reports( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch files")?; + .internal_context("failed to fetch files")?; let report_rows = sqlx::query!( r#" @@ -538,7 +538,7 @@ async fn fetch_project_reports( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch delphi reports")?; + .internal_context("failed to fetch delphi reports")?; let issue_rows = sqlx::query!( r#" @@ -557,7 +557,7 @@ async fn fetch_project_reports( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch delphi report issues")?; + .internal_context("failed to fetch delphi report issues")?; let issue_ids: Vec = issue_rows.iter().map(|i| i.id).collect(); @@ -586,7 +586,7 @@ async fn fetch_project_reports( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch delphi issue details")?; + .internal_context("failed to fetch delphi issue details")?; let versions_by_project: HashMap> = versions @@ -765,16 +765,16 @@ pub async fn search_projects( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let sort_by = search_req.sort_by.to_string(); let limit = search_req.limit.max(50); let offset = limit.saturating_mul(search_req.page); let limit = - i64::try_from(limit).wrap_request_err("limit cannot fit into `i64`")?; + i64::try_from(limit).request_context("limit cannot fit into `i64`")?; let offset = i64::try_from(offset) - .wrap_request_err("offset cannot fit into `i64`")?; + .request_context("offset cannot fit into `i64`")?; let replied_to_filter = search_req.filter.replied_to.map(|r| match r { RepliedTo::Replied => "replied", @@ -908,7 +908,7 @@ pub async fn search_projects( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch projects")?; + .internal_context("failed to fetch projects")?; for row in rows { project_ids.push(row.project_id); @@ -918,11 +918,11 @@ pub async fn search_projects( let project_reports = fetch_project_reports(&project_ids, &pool, &redis, false) .await - .wrap_api_err("fetching project reports")?; + .api_context("fetching project reports")?; let projects = DBProject::get_many_ids(&project_ids, &**pool, &redis) .await - .wrap_internal_err("failed to fetch projects")? + .internal_context("failed to fetch projects")? .into_iter() .map(|project| { (ProjectId::from(project.inner.id), Project::from(project)) @@ -930,7 +930,7 @@ pub async fn search_projects( .collect::>(); let db_threads = DBThread::get_many(&thread_ids, &**pool) .await - .wrap_internal_err("failed to fetch threads")?; + .internal_context("failed to fetch threads")?; let thread_author_ids = db_threads .iter() .flat_map(|thread| { @@ -944,7 +944,7 @@ pub async fn search_projects( let thread_authors = DBUser::get_many_ids(&thread_author_ids, &**pool, &redis) .await - .wrap_internal_err("failed to fetch thread authors")? + .internal_context("failed to fetch thread authors")? .into_iter() .map(From::from) .collect::>(); @@ -960,7 +960,7 @@ pub async fn search_projects( let ownerships = get_projects_ownership(&project_list, &pool, &redis) .await - .wrap_internal_err("failed to fetch project ownerships")?; + .internal_context("failed to fetch project ownerships")?; let ownership = projects .keys() .copied() @@ -1013,7 +1013,7 @@ pub async fn get_project_report( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (project_id,) = path.into_inner(); let db_project_id = DBProjectId::from(project_id); @@ -1028,13 +1028,13 @@ pub async fn get_project_report( ) .fetch_optional(&**pool) .await - .wrap_internal_err("failed to fetch thread")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch thread")? + .not_found_context("resource not found")?; let project_reports = fetch_project_reports(&[db_project_id], &pool, &redis, true) .await - .wrap_api_err("fetching project reports")?; + .api_context("fetching project reports")?; let project_report = project_reports.into_iter().next(); @@ -1050,11 +1050,11 @@ pub async fn get_project_report( ) .fetch_one(&**pool) .await - .wrap_internal_err("fetching project technical review membership")?; + .internal_context("fetching project technical review membership")?; let db_threads = DBThread::get_many(&[row.thread_id], &**pool) .await - .wrap_internal_err("failed to fetch thread")?; + .internal_context("failed to fetch thread")?; let thread_author_ids = db_threads .iter() .flat_map(|thread| { @@ -1068,7 +1068,7 @@ pub async fn get_project_report( let thread_authors = DBUser::get_many_ids(&thread_author_ids, &**pool, &redis) .await - .wrap_internal_err("failed to fetch thread authors")? + .internal_context("failed to fetch thread authors")? .into_iter() .map(From::from) .collect::>(); @@ -1083,7 +1083,7 @@ pub async fn get_project_report( let thread = threads .get(&row.thread_id.into()) .cloned() - .wrap_not_found_err("resource not found")?; + .not_found_context("resource not found")?; Ok(web::Json(ProjectReportResponse { project_report, @@ -1132,14 +1132,14 @@ pub async fn submit_report( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (project_id,) = path.into_inner(); let project_id = DBProjectId::from(project_id); let mut txn = pool .begin() .await - .wrap_internal_err("failed to begin transaction")?; + .internal_context("failed to begin transaction")?; sqlx::query!( r#" @@ -1152,8 +1152,8 @@ pub async fn submit_report( ) .fetch_optional(&mut txn) .await - .wrap_internal_err("locking project for technical review submission")? - .wrap_not_found_err("project not found")?; + .internal_context("locking project for technical review submission")? + .not_found_context("project not found")?; let issue_details = sqlx::query!( r#" @@ -1182,7 +1182,7 @@ pub async fn submit_report( ) .fetch_all(&mut txn) .await - .wrap_internal_err("failed to fetch issue verdicts")?; + .internal_context("failed to fetch issue verdicts")?; let pending_issue_details = issue_details .iter() @@ -1190,7 +1190,7 @@ pub async fn submit_report( .map(|detail| DelphiReportIssueDetailsId(detail.issue_detail_id)) .collect_vec(); if !pending_issue_details.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "report still has issue details with no verdict: {pending_issue_details:?}" ))); } @@ -1215,7 +1215,7 @@ pub async fn submit_report( ) .fetch_one(&mut txn) .await - .wrap_internal_err("failed to update reports")?; + .internal_context("failed to update reports")?; if let Some(body) = submit_report.message { ThreadMessageBuilder { @@ -1231,7 +1231,7 @@ pub async fn submit_report( } .insert(&mut txn) .await - .wrap_internal_err("failed to add moderator message")?; + .internal_context("failed to add moderator message")?; } let verdict = submit_report.verdict; @@ -1247,7 +1247,7 @@ pub async fn submit_report( } .insert(&mut txn) .await - .wrap_internal_err("failed to add tech review message")?; + .internal_context("failed to add tech review message")?; if verdict == DelphiVerdict::Unsafe { let record = sqlx::query!( @@ -1277,7 +1277,7 @@ pub async fn submit_report( ) .fetch_one(&mut txn) .await - .wrap_internal_err("failed to mark project as rejected")?; + .internal_context("failed to mark project as rejected")?; ThreadMessageBuilder { author_id: Some(user.user.id.into()), @@ -1290,7 +1290,7 @@ pub async fn submit_report( } .insert(&mut txn) .await - .wrap_internal_err("failed to add tech review message")?; + .internal_context("failed to add tech review message")?; } let mut prepared = if verdict == DelphiVerdict::Unsafe { @@ -1317,9 +1317,7 @@ pub async fn submit_report( ) .execute(&mut txn) .await - .wrap_internal_err( - "failed to remove project from technical review queue", - )?; + .internal_context("failed to remove project from technical review queue")?; if prepared.is_none() && removed.rows_affected() > 0 { prepared = Some(crate::routes::v3::projects::mutation::prepare_technical_review_exits( @@ -1338,7 +1336,7 @@ pub async fn submit_report( } else { txn.commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; } Ok(()) @@ -1392,12 +1390,12 @@ pub async fn update_issue_details( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("updating database records for `update_issue_details`")?; + .auth_context("updating database records for `update_issue_details`")?; let mut txn = pool .begin() .await - .wrap_internal_err("failed to start transaction")?; + .internal_context("failed to start transaction")?; let updates = update_reqs.into_inner(); let detail_ids = updates.iter().map(|u| u.detail_id.0).collect::>(); @@ -1483,10 +1481,10 @@ pub async fn update_issue_details( ) .fetch_one(&mut txn) .await - .wrap_internal_err("failed to update issue details")?; + .internal_context("failed to update issue details")?; if !record.all_found { - return Err(ApiError::Request(eyre!("issue detail does not exist"))); + return Err(ApiError::Request(anyhow!("issue detail does not exist"))); } let affected_projects = sqlx::query!( @@ -1499,7 +1497,7 @@ pub async fn update_issue_details( ) .fetch_all(&mut txn) .await - .wrap_internal_err( + .internal_context( "failed to fetch projects affected by issue detail updates", )?; @@ -1514,7 +1512,7 @@ pub async fn update_issue_details( &mut txn, ) .await - .wrap_api_err("executing `tech_review_queue::sync_projects`")?; + .api_context("executing `tech_review_queue::sync_projects`")?; let prepared = crate::routes::v3::projects::mutation::prepare_technical_review_exits( @@ -1555,7 +1553,7 @@ pub async fn update_global_issue_details( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err( + .auth_context( "updating database records for `update_global_issue_details`", )?; @@ -1564,7 +1562,7 @@ pub async fn update_global_issue_details( if updates.iter().any(|u| { u.detail_key.is_empty() || u.detail_key.starts_with(">(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; if user_ids.is_empty() { return Ok(web::Json(HashMap::new())); @@ -1758,7 +1756,7 @@ pub async fn get_users_flagged_projects( let target_users = DBUser::get_many(&user_ids, &**pool, &redis) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let pool_ref = &**pool; let redis_ref = &*redis; @@ -1802,12 +1800,12 @@ pub async fn get_organization_flagged_projects( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let target_org = DBOrganization::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching organization from database")? + .not_found_context("resource not found")?; let flagged = organization_flagged_projects(target_org.id, &**pool, &redis).await?; @@ -1843,10 +1841,10 @@ pub async fn get_organizations_flagged_projects( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let organization_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; if organization_ids.is_empty() { return Ok(web::Json(HashMap::new())); @@ -1855,7 +1853,7 @@ pub async fn get_organizations_flagged_projects( let target_orgs = DBOrganization::get_many(&organization_ids, &**pool, &redis) .await - .wrap_internal_err("fetching organizations from database")?; + .internal_context("fetching organizations from database")?; let pool_ref = &**pool; let redis_ref = &*redis; @@ -1893,7 +1891,7 @@ where { let project_ids = DBUser::get_projects(user_id, pool, redis) .await - .wrap_internal_err("fetching user's projects from database")?; + .internal_context("fetching user's projects from database")?; flagged_projects_among(&project_ids, pool, redis).await } @@ -1914,7 +1912,7 @@ where { let project_ids = DBOrganization::get_projects(organization_id, pool) .await - .wrap_internal_err("fetching project IDs from database")?; + .internal_context("fetching project IDs from database")?; flagged_projects_among(&project_ids, pool, redis).await } @@ -1940,7 +1938,7 @@ where // before pulling any thread data. let candidate_projects = DBProject::get_many_ids(project_ids, pool, redis) .await - .wrap_internal_err("fetching projects from database")? + .internal_context("fetching projects from database")? .into_iter() .filter(|project| { matches!( @@ -1961,7 +1959,7 @@ where let threads = DBThread::get_many(&thread_ids, pool) .await - .wrap_internal_err("fetching threads from database")? + .internal_context("fetching threads from database")? .into_iter() .map(|thread| (thread.id, thread)) .collect::>(); diff --git a/apps/labrinth/src/routes/internal/moderation/tech_review/global.rs b/apps/labrinth/src/routes/internal/moderation/tech_review/global.rs index e1ad20c5a8e..4223effe976 100644 --- a/apps/labrinth/src/routes/internal/moderation/tech_review/global.rs +++ b/apps/labrinth/src/routes/internal/moderation/tech_review/global.rs @@ -21,7 +21,7 @@ use crate::{ routes::ApiError, util::error::Context, }; -use eyre::eyre; +use anyhow::anyhow; pub fn config(cfg: &mut web::ServiceConfig) { cfg.service(search_global_issue_details) @@ -149,7 +149,7 @@ pub async fn search_global_issue_details( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating global issue search")?; + .auth_context("authenticating global issue search")?; let query = search_req .query @@ -160,9 +160,9 @@ pub async fn search_global_issue_details( let offset = limit.saturating_mul(search_req.page); let limit = - i64::try_from(limit).wrap_request_err("limit cannot fit into `i64`")?; + i64::try_from(limit).request_context("limit cannot fit into `i64`")?; let offset = i64::try_from(offset) - .wrap_request_err("offset cannot fit into `i64`")?; + .request_context("offset cannot fit into `i64`")?; let total = sqlx::query!( r#" @@ -187,7 +187,7 @@ pub async fn search_global_issue_details( ) .fetch_one(&**pool) .await - .wrap_internal_err("failed to count global issue details")? + .internal_context("failed to count global issue details")? .total; let global_rows = sqlx::query!( @@ -226,7 +226,7 @@ pub async fn search_global_issue_details( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch global issue details")?; + .internal_context("failed to fetch global issue details")?; let detail_keys = global_rows .iter() @@ -304,7 +304,7 @@ pub async fn search_global_issue_details( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch local issue detail traces")?; + .internal_context("failed to fetch local issue detail traces")?; let mut traces_by_key = local_rows .into_iter() @@ -373,18 +373,18 @@ pub async fn get_global_issue_detail( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating global issue detail request")?; + .auth_context("authenticating global issue detail request")?; let detail_key = get_req.detail_key.trim(); if detail_key.is_empty() { - return Err(ApiError::Request(eyre!("detail key cannot be empty"))); + return Err(ApiError::Request(anyhow!("detail key cannot be empty"))); } let limit = get_req.limit.clamp(1, 100); let query_limit = i64::try_from(limit + 1) - .wrap_request_err("limit cannot fit into `i64`")?; + .request_context("limit cannot fit into `i64`")?; let limit = usize::try_from(limit) - .wrap_request_err("limit cannot fit into `usize`")?; + .request_context("limit cannot fit into `usize`")?; let after_detail_id = get_req.after_detail_id.map(|id| id.0); let global_row = sqlx::query!( @@ -406,8 +406,8 @@ pub async fn get_global_issue_detail( ) .fetch_optional(&**pool) .await - .wrap_internal_err("failed to fetch global issue detail")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch global issue detail")? + .not_found_context("resource not found")?; let local_rows = sqlx::query!( r#" @@ -451,7 +451,7 @@ pub async fn get_global_issue_detail( ) .fetch_all(&**pool) .await - .wrap_internal_err("failed to fetch local issue detail traces")?; + .internal_context("failed to fetch local issue detail traces")?; let mut local_traces = local_rows .into_iter() diff --git a/apps/labrinth/src/routes/internal/moderation/tech_review/rules.rs b/apps/labrinth/src/routes/internal/moderation/tech_review/rules.rs index 07cbcf5c9a6..5c74e05d701 100644 --- a/apps/labrinth/src/routes/internal/moderation/tech_review/rules.rs +++ b/apps/labrinth/src/routes/internal/moderation/tech_review/rules.rs @@ -1,6 +1,6 @@ use actix_web::{HttpRequest, delete, get, post, put, web}; +use anyhow::anyhow; use chrono::{DateTime, Utc}; -use eyre::eyre; use serde::{Deserialize, Serialize}; use validator::Validate; use xredis::RedisPool; @@ -151,16 +151,16 @@ impl WriteDelphiRule { self.on_issue_types.sort(); self.on_issue_types.dedup(); Validate::validate(&self).map_err(|error| { - ApiError::Request(eyre!(validation_errors_to_string(error, None))) + ApiError::Request(anyhow!(validation_errors_to_string(error, None))) })?; let expression = self.rule.clone(); tokio::task::spawn_blocking(move || cel::Program::compile(&expression)) .await - .wrap_internal_err("failed to join cel compilation task")? + .internal_context("failed to join cel compilation task")? .map_err(|error| { ApiError::Request( - eyre!(error).wrap_err("invalid cel expression"), + anyhow!(error).context("invalid cel expression"), ) })?; @@ -197,12 +197,12 @@ pub async fn test_rule( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let mut request = body.into_inner(); request.rule = request.rule.trim().to_string(); request.validate().map_err(|error| { - ApiError::Request(eyre!(validation_errors_to_string(error, None))) + ApiError::Request(anyhow!(validation_errors_to_string(error, None))) })?; let rule = request.rule; @@ -210,10 +210,10 @@ pub async fn test_rule( let program = tokio::task::spawn_blocking(move || cel::Program::compile(&expression)) .await - .wrap_internal_err("failed to join cel compilation task")? + .internal_context("failed to join cel compilation task")? .map_err(|error| { ApiError::Request( - eyre!(error).wrap_err("invalid cel expression"), + anyhow!(error).context("invalid cel expression"), ) })?; let mut effects = Vec::with_capacity(request.inputs.len()); @@ -221,7 +221,7 @@ pub async fn test_rule( for (index, input) in request.inputs.iter().enumerate() { let evaluation = super::rules_scan::evaluate_rule(&program, &rule, input); - let effect = evaluation.wrap_request_err(format!( + let effect = evaluation.request_context(format!( "failed to evaluate test input {index}" ))?; effects.push(effect); @@ -253,7 +253,7 @@ pub async fn get_rules( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let rules = sqlx::query!( r#" @@ -342,7 +342,7 @@ pub async fn get_rules( ) .fetch_all(&***ro_pool) .await - .wrap_internal_err("failed to fetch delphi rules")?; + .internal_context("failed to fetch delphi rules")?; let mut response = Vec::::new(); for rule in rules { @@ -443,14 +443,14 @@ pub async fn get_rule_affected_details( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (rule_id,) = path.into_inner(); let limit = query.limit.clamp(1, 100); let offset = limit.saturating_mul(query.page); let limit = - i64::try_from(limit).wrap_request_err("limit cannot fit into `i64`")?; + i64::try_from(limit).request_context("limit cannot fit into `i64`")?; let offset = i64::try_from(offset) - .wrap_request_err("offset cannot fit into `i64`")?; + .request_context("offset cannot fit into `i64`")?; let total = sqlx::query_scalar!( r#" @@ -483,7 +483,7 @@ pub async fn get_rule_affected_details( ) .fetch_one(&***ro_pool) .await - .wrap_internal_err("failed to count details affected by delphi rule")?; + .internal_context("failed to count details affected by delphi rule")?; let details = sqlx::query!( r#" @@ -525,7 +525,7 @@ pub async fn get_rule_affected_details( ) .fetch_all(&***ro_pool) .await - .wrap_internal_err("failed to fetch details affected by delphi rule")?; + .internal_context("failed to fetch details affected by delphi rule")?; Ok(web::Json(GetRuleAffectedDetailsResponse { total, @@ -575,7 +575,7 @@ pub async fn create_rule( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let rule = body.into_inner().validate().await?; let user_id = user.id.0 as i64; @@ -620,7 +620,7 @@ pub async fn create_rule( ) .fetch_one(&**pool) .await - .wrap_internal_err("failed to create delphi rule")?; + .internal_context("failed to create delphi rule")?; Ok(web::Json(DelphiRule { id: rule.id, @@ -664,7 +664,7 @@ pub async fn update_rule( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let (id,) = path.into_inner(); let rule = body.into_inner().validate().await?; @@ -705,8 +705,8 @@ pub async fn update_rule( ) .fetch_optional(&**pool) .await - .wrap_internal_err("failed to update delphi rule")? - .wrap_not_found_err("delphi rule not found")?; + .internal_context("failed to update delphi rule")? + .not_found_context("delphi rule not found")?; Ok(web::Json(DelphiRule { id: rule.id, @@ -748,7 +748,7 @@ pub async fn delete_rule( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let (id,) = path.into_inner(); @@ -770,10 +770,10 @@ pub async fn delete_rule( ) .fetch_optional(&**pool) .await - .wrap_internal_err("failed to mark delphi rule for deletion")?; + .internal_context("failed to mark delphi rule for deletion")?; if deleted.is_none() { - return Err(ApiError::NotFound(eyre!("delphi rule not found"))); + return Err(ApiError::NotFound(anyhow!("delphi rule not found"))); } Ok(()) diff --git a/apps/labrinth/src/routes/internal/moderation/tech_review/rules_scan.rs b/apps/labrinth/src/routes/internal/moderation/tech_review/rules_scan.rs index 82846b3a982..436560eaa0d 100644 --- a/apps/labrinth/src/routes/internal/moderation/tech_review/rules_scan.rs +++ b/apps/labrinth/src/routes/internal/moderation/tech_review/rules_scan.rs @@ -6,9 +6,9 @@ use std::{ use actix_web::{ HttpRequest, HttpResponse, get, http::header::ContentEncoding, post, web, }; +use anyhow::{Result, anyhow}; use ariadne::ids::base62_impl::to_base62; use bytes::Bytes; -use eyre::{Result, eyre}; use futures_util::TryStreamExt; use serde::{Deserialize, Serialize}; use sqlx::types::Json; @@ -168,7 +168,7 @@ pub async fn get_rule_schema( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let mut schemas = Vec::new(); ::schemas(&mut schemas); @@ -213,7 +213,7 @@ pub async fn get_detail_rule_input( Scopes::MODERATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let (detail_id,) = path.into_inner(); let detail = sqlx::query!( @@ -294,8 +294,8 @@ pub async fn get_detail_rule_input( ) .fetch_optional(&***ro_pool) .await - .wrap_internal_err("failed to fetch delphi rule input")? - .wrap_not_found_err("delphi rule input not found")?; + .internal_context("failed to fetch delphi rule input")? + .not_found_context("delphi rule input not found")?; Ok(web::Json(RuleInput { schema_version: 1, @@ -334,7 +334,7 @@ fn schema_to_value( ) -> Result { serde_json::to_value(schema).map_err(|error| { ApiError::Internal( - eyre!(error).wrap_err("failed to serialize Delphi rule schema"), + anyhow!(error).context("failed to serialize Delphi rule schema"), ) }) } @@ -361,20 +361,20 @@ pub async fn scan_rules( Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let mut transaction = pool .begin() .await - .wrap_internal_err("failed to begin delphi rule scan")?; + .internal_context("failed to begin delphi rule scan")?; sqlx::query!("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ") .execute(&mut transaction) .await .map_err(|error| { ApiError::Internal( - eyre!(error) - .wrap_err("failed to set delphi rule scan isolation"), + anyhow!(error) + .context("failed to set delphi rule scan isolation"), ) })?; @@ -386,13 +386,13 @@ pub async fn scan_rules( .await .map_err(|error| { ApiError::Internal( - eyre!(error).wrap_err("failed to acquire delphi rule scan lock"), + anyhow!(error).context("failed to acquire delphi rule scan lock"), ) })? .unwrap_or(false); if !acquired { - return Err(ApiError::Conflict(eyre!( + return Err(ApiError::Conflict(anyhow!( "a delphi rule scan is already running" ))); } @@ -472,7 +472,7 @@ async fn run_scan( ) .fetch_all(&mut transaction) .await - .wrap_err("fetching projects affected by delphi rule scan")? + .context("fetching projects affected by delphi rule scan")? .into_iter() .map(|row| row.project_id) .collect::>(); @@ -481,21 +481,21 @@ async fn run_scan( sqlx::query!("LOCK TABLE delphi_rules IN SHARE MODE") .execute(&mut transaction) .await - .wrap_err("failed to lock delphi rules")?; + .context("failed to lock delphi rules")?; sqlx::query!("LOCK TABLE delphi_report_issue_details IN SHARE MODE") .execute(&mut transaction) .await - .wrap_err("failed to lock delphi issue details")?; + .context("failed to lock delphi issue details")?; let current_revision = sqlx::query_scalar!( "SELECT revision FROM delphi_rule_revisions LIMIT 1 FOR UPDATE", ) .fetch_one(&mut transaction) .await - .wrap_err("failed to fetch the current delphi rule revision")?; + .context("failed to fetch the current delphi rule revision")?; let revision = current_revision .checked_add(1) - .ok_or_else(|| eyre!("delphi rule revision overflowed"))?; + .ok_or_else(|| anyhow!("delphi rule revision overflowed"))?; let rules = fetch_compiled_rules(&mut transaction).await?; @@ -507,7 +507,7 @@ async fn run_scan( ) .fetch_one(&mut transaction) .await - .wrap_err("failed to count delphi issue details")? as usize; + .context("failed to count delphi issue details")? as usize; let mut details = sqlx::query!( r#" @@ -607,7 +607,7 @@ async fn run_scan( while let Some(detail) = details .try_next() .await - .wrap_err("failed to fetch a delphi issue detail")? + .context("failed to fetch a delphi issue detail")? { let detail_id = detail.id; let input = RuleInput { @@ -641,7 +641,7 @@ async fn run_scan( }, }; - let context = build_rule_context(&input).wrap_err_with(|| { + let context = build_rule_context(&input).with_context(|| { format!( "failed to build delphi rule context for detail {detail_id}" ) @@ -657,7 +657,7 @@ async fn run_scan( &context, &input, ) - .wrap_err_with(|| { + .with_context(|| { format!( "failed to evaluate delphi rule '{}' for detail {detail_id}", rule.name @@ -748,7 +748,7 @@ async fn run_scan( ) .fetch_all(&mut transaction) .await - .wrap_err("failed to fetch projects affected by delphi rule changes")?; + .context("failed to fetch projects affected by delphi rule changes")?; sqlx::query!( "UPDATE delphi_rules SET revision = $1 WHERE NOT delete_on_next_revision", @@ -756,11 +756,11 @@ async fn run_scan( ) .execute(&mut transaction) .await - .wrap_err("failed to update delphi rule revisions")?; + .context("failed to update delphi rule revisions")?; sqlx::query!("UPDATE delphi_rule_revisions SET revision = $1", revision) .execute(&mut transaction) .await - .wrap_err("failed to publish the delphi rule revision")?; + .context("failed to publish the delphi rule revision")?; tech_review_queue::add_projects( &affected_projects @@ -788,11 +788,11 @@ async fn run_scan( ) .execute(&mut transaction) .await - .wrap_err("failed to delete old delphi rule effects")?; + .context("failed to delete old delphi rule effects")?; sqlx::query!("DELETE FROM delphi_rules WHERE delete_on_next_revision") .execute(&mut transaction) .await - .wrap_err("failed to delete retired delphi rules")?; + .context("failed to delete retired delphi rules")?; let prepared = crate::routes::v3::projects::mutation::prepare_technical_review_exits( @@ -825,7 +825,7 @@ pub(crate) async fn materialize_current_rule_effects( ) .fetch_one(&mut *transaction) .await - .wrap_err("failed to fetch the current delphi rule revision")?; + .context("failed to fetch the current delphi rule revision")?; let rules = fetch_compiled_rules(transaction).await?; if rules.is_empty() { @@ -912,7 +912,7 @@ pub(crate) async fn materialize_current_rule_effects( ) .fetch_all(&mut *transaction) .await - .wrap_err("failed to fetch new delphi issue details")?; + .context("failed to fetch new delphi issue details")?; let mut effects = Vec::new(); for detail in details { @@ -947,7 +947,7 @@ pub(crate) async fn materialize_current_rule_effects( }, }; - let context = build_rule_context(&input).wrap_err_with(|| { + let context = build_rule_context(&input).with_context(|| { format!( "failed to build delphi rule context for detail {}", detail.id @@ -964,7 +964,7 @@ pub(crate) async fn materialize_current_rule_effects( &context, &input, ) - .wrap_err_with(|| { + .with_context(|| { format!( "failed to evaluate delphi rule '{}' for detail {}", rule.name, detail.id @@ -997,7 +997,7 @@ async fn fetch_compiled_rules( ) .fetch_all(&mut *transaction) .await - .wrap_err("failed to fetch delphi rules")?; + .context("failed to fetch delphi rules")?; tokio::task::spawn_blocking(move || { rules @@ -1005,7 +1005,7 @@ async fn fetch_compiled_rules( .map(|rule| { let program = cel::Program::compile(&rule.rule).map_err(|error| { - eyre!( + anyhow!( "failed to compile delphi rule '{}': {error}", rule.name ) @@ -1021,7 +1021,7 @@ async fn fetch_compiled_rules( .collect() }) .await - .wrap_err("failed to join cel compilation task")? + .context("failed to join cel compilation task")? } async fn insert_materialized_effects( @@ -1068,7 +1068,7 @@ async fn insert_materialized_effects( ) .execute(&mut *transaction) .await - .wrap_err("failed to insert delphi rule effects")?; + .context("failed to insert delphi rule effects")?; Ok(()) } @@ -1086,28 +1086,28 @@ fn build_rule_context(input: &RuleInput) -> Result> { let mut context = cel::Context::default(); context .add_variable("schema_version", input.schema_version) - .wrap_err("failed to add `schema_version` to cel context")?; + .context("failed to add `schema_version` to cel context")?; context .add_variable("trace", &input.trace) - .wrap_err("failed to add `trace` to cel context")?; + .context("failed to add `trace` to cel context")?; context .add_variable("file_traces", &input.file_traces) - .wrap_err("failed to add `file_traces` to cel context")?; + .context("failed to add `file_traces` to cel context")?; context .add_variable("scan", &input.scan) - .wrap_err("failed to add `scan` to cel context")?; + .context("failed to add `scan` to cel context")?; context .add_variable("artifact", &input.artifact) - .wrap_err("failed to add `artifact` to cel context")?; + .context("failed to add `artifact` to cel context")?; context .add_variable("project", &input.project) - .wrap_err("failed to add `project` to cel context")?; + .context("failed to add `project` to cel context")?; context .add_variable("version", &input.version) - .wrap_err("failed to add `version` to cel context")?; + .context("failed to add `version` to cel context")?; context .add_variable("file", &input.file) - .wrap_err("failed to add `file` to cel context")?; + .context("failed to add `file` to cel context")?; Ok(context) } @@ -1119,13 +1119,13 @@ fn evaluate_rule_with_context( input: &RuleInput, ) -> Result> { evaluate_rule_inner(program, context) - .wrap_err_with(|| { + .with_context(|| { let input = serde_json::to_string(input).unwrap_or_else(|error| { format!("") }); format!("CEL input: {input}") }) - .wrap_err_with(|| format!("CEL expression: {expression}")) + .with_context(|| format!("CEL expression: {expression}")) } fn evaluate_rule_inner( @@ -1134,9 +1134,9 @@ fn evaluate_rule_inner( ) -> Result> { let value = program .execute(context) - .wrap_err("failed to execute cel expression")?; + .context("failed to execute cel expression")?; let value = value.json().map_err(|error| { - eyre!("failed to convert cel result to json: {error}") + anyhow!("failed to convert cel result to json: {error}") })?; match value { @@ -1144,11 +1144,11 @@ fn evaluate_rule_inner( serde_json::Value::String(severity) => { let severity = serde_json::from_value(serde_json::Value::String(severity)) - .wrap_err("cel expression returned an invalid severity")?; + .context("cel expression returned an invalid severity")?; Ok(Some(DelphiRuleEffect { severity })) } value => serde_json::from_value(value) .map(Some) - .wrap_err("cel expression returned an invalid rule effect"), + .context("cel expression returned an invalid rule effect"), } } diff --git a/apps/labrinth/src/routes/internal/moderation/user_restrictions.rs b/apps/labrinth/src/routes/internal/moderation/user_restrictions.rs index ca68cc62db7..3852beec1b2 100644 --- a/apps/labrinth/src/routes/internal/moderation/user_restrictions.rs +++ b/apps/labrinth/src/routes/internal/moderation/user_restrictions.rs @@ -1,5 +1,5 @@ use actix_web::{HttpRequest, delete, put, web}; -use eyre::eyre; +use anyhow::anyhow; use serde::Deserialize; use xredis::RedisPool; @@ -40,10 +40,10 @@ async fn authenticate_moderator( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "only moderators can manage user restrictions" ))); } @@ -58,14 +58,14 @@ async fn get_target( ) -> Result { let target = DBUser::get(id, pool, redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("user not found")?; + .internal_context("fetching user from database")? + .not_found_context("user not found")?; if matches!( Role::from_string(&target.role), Role::Moderator | Role::Admin ) { - return Err(ApiError::Auth(eyre!("cannot restrict a staff account"))); + return Err(ApiError::Auth(anyhow!("cannot restrict a staff account"))); } Ok(target) @@ -99,7 +99,7 @@ pub async fn restrict_user( let target = get_target(&path.into_inner().0, &pool, &redis).await?; if !Scopes::removable().contains(body.removed_perms) { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "`removed_perms` contains scopes that cannot be removed" ))); } @@ -107,7 +107,7 @@ pub async fn restrict_user( if body.removed_perms.is_empty() { DBUserRestriction::delete(target.id, &**pool) .await - .wrap_internal_err("lifting user restriction")?; + .internal_context("lifting user restriction")?; } else { DBUserRestriction::upsert( target.id, @@ -118,12 +118,12 @@ pub async fn restrict_user( &**pool, ) .await - .wrap_internal_err("restricting user")?; + .internal_context("restricting user")?; } DBUser::clear_caches(&[(target.id, Some(target.username))], &redis) .await - .wrap_internal_err("clearing user cache")?; + .internal_context("clearing user cache")?; Ok(()) } @@ -147,14 +147,14 @@ pub async fn unrestrict_user( if !DBUserRestriction::delete(target.id, &**pool) .await - .wrap_internal_err("lifting user restriction")? + .internal_context("lifting user restriction")? { - return Err(ApiError::NotFound(eyre!("user is not restricted"))); + return Err(ApiError::NotFound(anyhow!("user is not restricted"))); } DBUser::clear_caches(&[(target.id, Some(target.username))], &redis) .await - .wrap_internal_err("clearing user cache")?; + .internal_context("clearing user cache")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/mural.rs b/apps/labrinth/src/routes/internal/mural.rs index ea29c29e38d..8671adc24d9 100644 --- a/apps/labrinth/src/routes/internal/mural.rs +++ b/apps/labrinth/src/routes/internal/mural.rs @@ -22,12 +22,12 @@ pub async fn get_bank_details( let mural = payouts_queue.muralpay.load(); let mural = mural .as_ref() - .wrap_internal_err("required Mural API is not available")?; + .internal_context("required Mural API is not available")?; let fiat_and_rail_codes = FiatAndRailCode::iter().collect::>(); let details = mural .client .get_bank_details(&fiat_and_rail_codes) .await - .wrap_internal_err("failed to fetch bank details")?; + .internal_context("failed to fetch bank details")?; Ok(web::Json(details)) } diff --git a/apps/labrinth/src/routes/internal/pats.rs b/apps/labrinth/src/routes/internal/pats.rs index c2876be93ea..3366947c148 100644 --- a/apps/labrinth/src/routes/internal/pats.rs +++ b/apps/labrinth/src/routes/internal/pats.rs @@ -1,6 +1,7 @@ use crate::database; use crate::database::models::generate_pat_id; use crate::util::error::Context as _; +use anyhow::anyhow; use crate::auth::get_user_from_headers; use crate::routes::ApiError; @@ -55,7 +56,7 @@ pub async fn get_pats( Scopes::PAT_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let pat_ids = @@ -65,12 +66,12 @@ pub async fn get_pats( &redis, ) .await - .wrap_internal_err("fetching personal access tokens from database")?; + .internal_context("fetching personal access tokens from database")?; let pats = database::models::pat_item::DBPersonalAccessToken::get_many_ids( &pat_ids, &**pool, &redis, ) .await - .wrap_internal_err("fetching personal access tokens from database")?; + .internal_context("fetching personal access tokens from database")?; Ok(HttpResponse::Ok().json( pats.into_iter() @@ -109,16 +110,14 @@ pub async fn create_pat( ) -> Result { info.0 .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; if info.scopes.is_restricted() { - return Err(ApiError::Request(eyre::eyre!( - "Invalid scopes requested!", - ))); + return Err(ApiError::Request(anyhow!("Invalid scopes requested!",))); } if info.expires < Utc::now() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Expire date must be in the future!", ))); } @@ -131,10 +130,10 @@ pub async fn create_pat( Scopes::PAT_CREATE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(info.scopes & Scopes::staff()) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "cannot grant staff scopes which you do not hold" ))); } @@ -143,11 +142,11 @@ pub async fn create_pat( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let id = generate_pat_id(&mut transaction) .await - .wrap_internal_err("generating pat ID")?; + .internal_context("generating pat ID")?; let token = ChaCha20Rng::from_rng(&mut rand::rng()) .sample_iter(&Alphanumeric) @@ -169,7 +168,7 @@ pub async fn create_pat( } .insert(&mut transaction) .await - .wrap_internal_err("inserting database records for `create_pat`")?; + .internal_context("inserting database records for `create_pat`")?; NotificationBuilder { body: NotificationBody::PatCreated { @@ -178,18 +177,18 @@ pub async fn create_pat( } .insert(user.id.into(), &mut transaction, &redis) .await - .wrap_internal_err("inserting database records for `create_pat`")?; + .internal_context("inserting database records for `create_pat`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::pat_item::DBPersonalAccessToken::clear_cache( vec![(None, None, Some(user.id.into()))], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::Ok().json(PersonalAccessToken { id: id.into(), @@ -237,8 +236,8 @@ pub async fn edit_pat( ) -> Result { info.0 .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let user = get_user_from_headers( &req, @@ -248,12 +247,12 @@ pub async fn edit_pat( Scopes::PAT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if let Some(scopes) = info.scopes && !user.scopes.contains(scopes & Scopes::staff()) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "cannot grant staff scopes which you do not hold" ))); } @@ -264,7 +263,7 @@ pub async fn edit_pat( &id, &**pool, &redis, ) .await - .wrap_internal_err("fetching personal access token from database")?; + .internal_context("fetching personal access token from database")?; if let Some(pat) = pat && pat.user_id == user.id.into() @@ -272,11 +271,11 @@ pub async fn edit_pat( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(scopes) = &info.scopes { if scopes.is_restricted() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Invalid scopes requested!", ))); } @@ -292,7 +291,7 @@ pub async fn edit_pat( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `edit_pat`")?; + .internal_context("querying database for `edit_pat`")?; } if let Some(name) = &info.name { sqlx::query!( @@ -306,11 +305,11 @@ pub async fn edit_pat( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `edit_pat`")?; + .internal_context("querying database for `edit_pat`")?; } if let Some(expires) = &info.expires { if expires < &Utc::now() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Expire date must be in the future!", ))); } @@ -326,19 +325,19 @@ pub async fn edit_pat( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `edit_pat`")?; + .internal_context("querying database for `edit_pat`")?; } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::pat_item::DBPersonalAccessToken::clear_cache( vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } Ok(HttpResponse::NoContent().finish()) @@ -374,14 +373,14 @@ pub async fn delete_pat( Scopes::PAT_DELETE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let id = id.into_inner().0; let pat = database::models::pat_item::DBPersonalAccessToken::get( &id, &**pool, &redis, ) .await - .wrap_internal_err("fetching personal access token from database")?; + .internal_context("fetching personal access token from database")?; if let Some(pat) = pat && pat.user_id == user.id.into() @@ -389,23 +388,23 @@ pub async fn delete_pat( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; database::models::pat_item::DBPersonalAccessToken::remove( pat.id, &mut transaction, ) .await - .wrap_internal_err("deleting personal access token from database")?; + .internal_context("deleting personal access token from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::pat_item::DBPersonalAccessToken::clear_cache( vec![(Some(pat.id), Some(pat.access_token), Some(pat.user_id))], &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } Ok(HttpResponse::NoContent().finish()) diff --git a/apps/labrinth/src/routes/internal/privacy.rs b/apps/labrinth/src/routes/internal/privacy.rs index 27a2cbd9846..d1430b23329 100644 --- a/apps/labrinth/src/routes/internal/privacy.rs +++ b/apps/labrinth/src/routes/internal/privacy.rs @@ -42,26 +42,26 @@ pub async fn invite_privacy_status( let invite_type = invite_type .parse::() - .wrap_request_err("invalid invite_type")?; + .request_context("invalid invite_type")?; let (user, target) = futures::try_join!( DBUser::get(&user_id, &**pool, &redis), DBUser::get(&target_id, &**pool, &redis), ) - .wrap_internal_err("resolving user ids")?; + .internal_context("resolving user ids")?; - let user_id = user.wrap_not_found_err("user not found")?.id; - let target_id = target.wrap_not_found_err("target not found")?.id; + let user_id = user.not_found_context("user not found")?.id; + let target_id = target.not_found_context("target not found")?.id; let blocked = DBBlockedUser::is_blocked(target_id, user_id, &**pool) .await - .wrap_internal_err("checking whether user is blocked")?; + .internal_context("checking whether user is blocked")?; let allowed = if blocked { false } else { let overrides = DBUserPreferences::get(target_id, &**pool) .await - .wrap_internal_err("fetching user preferences")?; + .internal_context("fetching user preferences")?; let preferences = UserPreferences::resolve(overrides); let privacy = match invite_type { @@ -79,7 +79,7 @@ pub async fn invite_privacy_status( InvitePrivacy::Friends => { DBFriend::get_friend(user_id, target_id, &**pool) .await - .wrap_internal_err("checking friendship status")? + .internal_context("checking friendship status")? .is_some_and(|friend| friend.accepted) } } diff --git a/apps/labrinth/src/routes/internal/search.rs b/apps/labrinth/src/routes/internal/search.rs index 04063ebfccb..70f23363cf4 100644 --- a/apps/labrinth/src/routes/internal/search.rs +++ b/apps/labrinth/src/routes/internal/search.rs @@ -24,7 +24,7 @@ pub async fn tasks( search .tasks() .await - .wrap_internal_err("fetching search tasks")?, + .internal_context("fetching search tasks")?, )) } @@ -42,6 +42,6 @@ pub async fn tasks_cancel( search .tasks_cancel(&body) .await - .wrap_internal_err("cancelling search tasks")?; + .internal_context("cancelling search tasks")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/server_ping.rs b/apps/labrinth/src/routes/internal/server_ping.rs index e4ca56f835f..ccd2986c840 100644 --- a/apps/labrinth/src/routes/internal/server_ping.rs +++ b/apps/labrinth/src/routes/internal/server_ping.rs @@ -45,12 +45,12 @@ pub async fn ping_minecraft_java( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let timeout = request.timeout_ms.map(Duration::from_millis); server_ping::ping_server(&request.address, timeout) .await - .wrap_request_err("failed to ping server")?; + .request_context("failed to ping server")?; Ok(()) } diff --git a/apps/labrinth/src/routes/internal/session.rs b/apps/labrinth/src/routes/internal/session.rs index 5e1f7e81c08..b695269f504 100644 --- a/apps/labrinth/src/routes/internal/session.rs +++ b/apps/labrinth/src/routes/internal/session.rs @@ -16,6 +16,7 @@ use crate::util::error::Context as _; use actix_web::http::header::AUTHORIZATION; use actix_web::web::Data; use actix_web::{HttpRequest, HttpResponse, delete, get, post, web}; +use anyhow::anyhow; use chrono::{DateTime, Utc}; use rand::distr::Alphanumeric; use rand::{RngExt, SeedableRng}; @@ -202,19 +203,19 @@ pub async fn list( Scopes::SESSION_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let session = extract_authorization_header(&req) - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let session_ids = DBSession::get_user_sessions(current_user.id.into(), &**pool, &redis) .await - .wrap_internal_err("fetching sessions from database")?; + .internal_context("fetching sessions from database")?; let sessions = DBSession::get_many_ids(&session_ids, &**pool, &redis) .await - .wrap_internal_err("fetching sessions from database")? + .internal_context("fetching sessions from database")? .into_iter() .filter(|x| x.expires > Utc::now()) .map(|x| Session::from(x, false, Some(session))) @@ -254,12 +255,12 @@ pub async fn delete( Scopes::SESSION_DELETE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let session = DBSession::get(info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching session from database")?; + .internal_context("fetching session from database")?; if let Some(session) = session && session.user_id == current_user.id.into() @@ -267,14 +268,14 @@ pub async fn delete( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; DBSession::remove(session.id, &mut transaction) .await - .wrap_internal_err("deleting session from database")?; + .internal_context("deleting session from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBSession::clear_cache( vec![( Some(session.id), @@ -284,7 +285,7 @@ pub async fn delete( &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } Ok(HttpResponse::NoContent().body("")) @@ -312,12 +313,12 @@ pub async fn refresh( .headers() .get(AUTHORIZATION) .and_then(|x| x.to_str().ok()) - .wrap_auth_err_with(|| AuthenticationError::InvalidCredentials)?; + .auth_context_with(|| AuthenticationError::InvalidCredentials)?; // We should ensure that the authorization given is a session token, and not some other type of token (like a PAT), since this endpoint is only for refreshing sessions. // This is done by checking the prefix of the token, which should be "mra_" for session tokens. if !session.starts_with("mra_") { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } @@ -331,18 +332,18 @@ pub async fn refresh( true, // Allow expired sessions, since we want to allow refreshing expired sessions ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let session = DBSession::get(session, &**pool, &redis) .await - .wrap_internal_err("fetching session from database")?; + .internal_context("fetching session from database")?; if let Some(session) = session { if current_user.id != session.user_id.into() || session.refresh_expires < Utc::now() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } @@ -350,11 +351,11 @@ pub async fn refresh( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; DBSession::remove(session.id, &mut transaction) .await - .wrap_internal_err("deleting session from database")?; + .internal_context("deleting session from database")?; let new_session = issue_session( req, session.user_id, @@ -363,11 +364,11 @@ pub async fn refresh( Some(session.refresh_expires), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBSession::clear_cache( vec![( Some(session.id), @@ -377,11 +378,11 @@ pub async fn refresh( &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::Ok().json(Session::from(new_session, true, None))) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))) } diff --git a/apps/labrinth/src/routes/internal/statuses.rs b/apps/labrinth/src/routes/internal/statuses.rs index 1ded2d65bc2..8ef84cbdb26 100644 --- a/apps/labrinth/src/routes/internal/statuses.rs +++ b/apps/labrinth/src/routes/internal/statuses.rs @@ -19,6 +19,8 @@ use crate::util::error::Context as _; use actix_web::web::{Data, Payload}; use actix_web::{HttpRequest, HttpResponse, get, web}; use actix_ws::Message; +use anyhow::Result; +use anyhow::anyhow; use ariadne::ids::UserId; use ariadne::networking::message::{ ClientToServerMessage, ServerToClientMessage, @@ -26,7 +28,6 @@ use ariadne::networking::message::{ use ariadne::users::UserStatus; use chrono::Utc; use either::Either; -use eyre::Result; use futures_util::future::select; use futures_util::{StreamExt, TryStreamExt}; use serde::Deserialize; @@ -71,11 +72,11 @@ pub async fn ws_init( false, ) .await - .wrap_auth_err("authenticating API request")? - .wrap_auth_err_with(|| AuthenticationError::InvalidCredentials)?; + .auth_context("authenticating API request")? + .auth_context_with(|| AuthenticationError::InvalidCredentials)?; if !scopes.contains(Scopes::SESSION_ACCESS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } @@ -97,7 +98,7 @@ pub async fn ws_init( let friends = DBFriend::get_user_friends(user.id.into(), Some(true), &***ro_pool) .await - .wrap_internal_err("fetching friends from database")?; + .internal_context("fetching friends from database")?; let friend_statuses = if !friends.is_empty() { let db = db.clone(); @@ -135,7 +136,7 @@ pub async fn ws_init( serde_json::to_string(&ServerToClientMessage::FriendStatuses { statuses: friend_statuses, }) - .wrap_request_err("serializing friend statuses")?, + .request_context("serializing friend statuses")?, ) .await; @@ -146,7 +147,7 @@ pub async fn ws_init( &redis, ) .await - .wrap_internal_err("fetching notifications from database")? + .internal_context("fetching notifications from database")? .into_iter() .filter(|notification| { !notification.read @@ -163,7 +164,7 @@ pub async fn ws_init( let _ = session .text( serde_json::to_string(¬ification) - .wrap_request_err("serializing launcher notification")?, + .request_context("serializing launcher notification")?, ) .await; } @@ -182,13 +183,13 @@ pub async fn ws_init( replace_user_status(None, Some(&status), &redis) .await - .wrap_internal_err("reading HTTP response body")?; + .internal_context("reading HTTP response body")?; broadcast_friends_message( &redis, RedisFriendsMessage::StatusUpdate { status }, ) .await - .wrap_internal_err("reading HTTP response body")?; + .internal_context("reading HTTP response body")?; let (shutdown_sender, mut shutdown_receiver) = tokio::sync::oneshot::channel::<()>(); @@ -410,7 +411,7 @@ pub async fn broadcast_friends_message( redis .publish(FRIENDS_CHANNEL_NAME, message) .await - .wrap_err("publishing friends message to redis")?; + .context("publishing friends message to redis")?; Ok(()) } @@ -424,11 +425,11 @@ pub async fn broadcast_to_local_friends( let friends = DBFriend::get_user_friends(user_id.into(), Some(true), &**ro_pool) .await - .wrap_err("fetching user friends from database")?; + .context("fetching user friends from database")?; broadcast_to_known_local_friends(user_id, message, sockets, friends) .await - .wrap_err("broadcasting message to local friends") + .context("broadcasting message to local friends") } async fn broadcast_to_known_local_friends( @@ -485,7 +486,7 @@ pub async fn send_message_to_user( if let Some(socket) = db.sockets.get(&socket_id) { send_message(&socket, message) .await - .wrap_err("sending websocket message to user")?; + .context("sending websocket message to user")?; } } } @@ -499,7 +500,7 @@ pub async fn send_notification_to_user( notification: &Notification, ) -> Result<()> { let message = serde_json::to_string(notification) - .wrap_err("serializing websocket notification")?; + .context("serializing websocket notification")?; if let Some(socket_ids) = db.sockets_by_user_id.get(&user) { for socket_id in socket_ids.iter() { @@ -530,13 +531,13 @@ pub async fn close_socket( replace_user_status(Some(&socket.status), None, redis) .await - .wrap_err("removing user status from redis")?; + .context("removing user status from redis")?; broadcast_friends_message( redis, RedisFriendsMessage::UserOffline { user: user_id }, ) .await - .wrap_err("broadcasting user offline status")?; + .context("broadcasting user offline status")?; for owned_socket in socket.owned_tunnel_sockets { let Some((_, tunnel_socket)) = diff --git a/apps/labrinth/src/routes/maven.rs b/apps/labrinth/src/routes/maven.rs index 1b89336a2ae..32c3e1e6b5b 100644 --- a/apps/labrinth/src/routes/maven.rs +++ b/apps/labrinth/src/routes/maven.rs @@ -15,6 +15,7 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context; use crate::{auth::get_user_from_headers, database}; use actix_web::{HttpRequest, HttpResponse, get, route, web}; +use anyhow::anyhow; use quick_xml::escape::escape; use std::collections::HashSet; use xredis::RedisPool; @@ -175,9 +176,9 @@ pub async fn maven_metadata( let Some(project) = database::models::DBProject::get(&project_id, &**pool, &redis) .await - .wrap_internal_err("fetching Maven project")? + .internal_context("fetching Maven project")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; let user_option = get_user_from_headers( @@ -192,9 +193,9 @@ pub async fn maven_metadata( if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let version_names = sqlx::query!( @@ -212,7 +213,7 @@ pub async fn maven_metadata( ) .fetch_all(&**pool) .await - .wrap_internal_err("fetching version names from database")?; + .internal_context("fetching version names from database")?; let mut new_versions = Vec::new(); let mut vals = HashSet::new(); @@ -257,8 +258,8 @@ pub async fn maven_metadata( Ok(HttpResponse::Ok().content_type("text/xml").body( yaserde::ser::to_string(&respdata) - .map_err(eyre::Report::msg) - .wrap_internal_err("serializing Maven metadata as XML")?, + .map_err(anyhow::Error::msg) + .internal_context("serializing Maven metadata as XML")?, )) } @@ -275,7 +276,7 @@ async fn find_version( let all_versions = database::models::DBVersion::get_many(&project.versions, pool, redis) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let exact_matches = all_versions .iter() @@ -296,7 +297,7 @@ async fn find_version( let db_loaders: HashSet = Loader::list(pool, redis) .await - .wrap_internal_err("fetching loader from Redis")? + .internal_context("fetching loader from Redis")? .into_iter() .map(|x| x.loader) .collect(); @@ -418,9 +419,9 @@ pub async fn version_file( let Some(project) = database::models::DBProject::get(&project_id, &***pool, &redis) .await - .wrap_internal_err("fetching Maven project")? + .internal_context("fetching Maven project")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; let user_option = get_user_from_headers( @@ -435,23 +436,23 @@ pub async fn version_file( if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let Some(version) = find_version(&project, &vnum, &pool, &redis) .await - .wrap_api_err("fetching Maven version")? + .api_context("fetching Maven version")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; if !is_visible_version(&version.inner, &user_option, &pool, &redis) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } if file.eq_ignore_ascii_case(&format!("{}-{}.pom", &project_id, &vnum)) { @@ -469,8 +470,8 @@ pub async fn version_file( }; return Ok(HttpResponse::Ok().content_type("text/xml").body( yaserde::ser::to_string(&respdata) - .map_err(eyre::Report::msg) - .wrap_internal_err("serializing Maven project as XML")?, + .map_err(anyhow::Error::msg) + .internal_context("serializing Maven project as XML")?, )); } else if let Some(selected_file) = find_file(&project_id, &vnum, &version, &file) @@ -480,7 +481,7 @@ pub async fn version_file( .body("")); } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } #[utoipa::path( @@ -510,9 +511,9 @@ pub async fn version_file_sha1( let Some(project) = database::models::DBProject::get(&project_id, &***pool, &redis) .await - .wrap_internal_err("fetching Maven project")? + .internal_context("fetching Maven project")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; let user_option = get_user_from_headers( @@ -527,23 +528,23 @@ pub async fn version_file_sha1( if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let Some(version) = find_version(&project, &vnum, &pool, &redis) .await - .wrap_api_err("fetching Maven version")? + .api_context("fetching Maven version")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; if !is_visible_version(&version.inner, &user_option, &pool, &redis) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } Ok(find_file(&project_id, &vnum, &version, &file) @@ -581,9 +582,9 @@ pub async fn version_file_sha512( let Some(project) = database::models::DBProject::get(&project_id, &***pool, &redis) .await - .wrap_internal_err("fetching Maven project")? + .internal_context("fetching Maven project")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; let user_option = get_user_from_headers( @@ -598,23 +599,23 @@ pub async fn version_file_sha512( if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let Some(version) = find_version(&project, &vnum, &pool, &redis) .await - .wrap_api_err("fetching Maven version")? + .api_context("fetching Maven version")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; if !is_visible_version(&version.inner, &user_option, &pool, &redis) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } Ok(find_file(&project_id, &vnum, &version, &file) diff --git a/apps/labrinth/src/routes/mod.rs b/apps/labrinth/src/routes/mod.rs index cdab98ca305..cf812102d36 100644 --- a/apps/labrinth/src/routes/mod.rs +++ b/apps/labrinth/src/routes/mod.rs @@ -12,6 +12,7 @@ use crate::util::error::{ApiContext, Context}; use actix_files::Files; use actix_web::http::{StatusCode, header}; use actix_web::{FromRequest, HttpRequest, HttpResponse, web}; +use anyhow::anyhow; use ariadne::ids::base62_impl::parse_base62; use futures::FutureExt; use std::collections::{HashMap, HashSet}; @@ -60,7 +61,7 @@ pub async fn resolve_refs( let mut redis = redis .connect() .await - .wrap_internal_err("connecting to Redis for project redirects")?; + .internal_context("connecting to Redis for project redirects")?; let keys = project_refs .iter() .map(|project_ref| { @@ -70,7 +71,7 @@ pub async fn resolve_refs( let cached_targets = redis .get_many_deserialized::>(&keys) .await - .wrap_internal_err("reading cached project redirects")?; + .internal_context("reading cached project redirects")?; let missing_refs = project_refs .iter() @@ -112,7 +113,7 @@ pub async fn resolve_refs( ) .fetch_all(pool) .await - .wrap_internal_err("looking up project redirects")? + .internal_context("looking up project redirects")? .into_iter() .map(|redirect| (redirect.project_ref, redirect.target_project_id)) .collect::>() @@ -133,7 +134,7 @@ pub async fn resolve_refs( Some(PROJECT_REDIRECT_CACHE_TTL_SECONDS), ) .await - .wrap_internal_err("caching project redirect")?; + .internal_context("caching project redirect")?; target_project_id }; resolved.push(target_project_id.map(ProjectId::from)); @@ -174,7 +175,7 @@ pub async fn clear_project_redirect_cache( let mut redis = redis .connect() .await - .wrap_internal_err("connecting to Redis to clear project redirects")?; + .internal_context("connecting to Redis to clear project redirects")?; let keys = project_refs .iter() .map(|project_ref| { @@ -184,7 +185,7 @@ pub async fn clear_project_redirect_cache( redis .delete_many(&keys) .await - .wrap_internal_err("clearing cached project redirects")?; + .internal_context("clearing cached project redirects")?; Ok(()) } @@ -223,7 +224,7 @@ async fn resolve_visible_refs_for_user( .collect::>(); let projects = DBProject::get_many(&target_refs, pool, redis) .await - .wrap_internal_err("fetching project redirect targets")?; + .internal_context("fetching project redirect targets")?; let visible_ids = filter_visible_project_ids( projects.iter().map(|project| &project.inner).collect(), user, @@ -231,7 +232,7 @@ async fn resolve_visible_refs_for_user( false, ) .await - .wrap_api_err("checking project redirect visibility")? + .api_context("checking project redirect visibility")? .into_iter() .map(ProjectId::from) .collect::>(); @@ -276,7 +277,7 @@ pub async fn redirect_query_refs( }) .collect::>(); let canonical_refs = serde_json::to_string(&canonical_refs) - .wrap_internal_err("serializing redirected project references")?; + .internal_context("serializing redirected project references")?; let mut query = url::form_urlencoded::Serializer::new(String::new()); for (name, value) in url::form_urlencoded::parse(req.query_string().as_bytes()) @@ -362,7 +363,7 @@ pub async fn redirect_ref( web::Path::>::extract(req) .await .map_err(|err| { - ApiError::Request(eyre::eyre!( + ApiError::Request(anyhow!( "decoding project redirect path: {err}" )) })?; @@ -556,55 +557,55 @@ pub fn public_config(cfg: &mut web::ServiceConfig) { pub enum ApiError { /// Error occurred on the server side, which the caller has no fault in. #[error(transparent)] - Internal(eyre::Report), + Internal(anyhow::Error), /// Caller made an invalid or malformed request. #[error(transparent)] - Request(eyre::Report), + Request(anyhow::Error), /// Caller attempted a request which they are not allowed to make. #[error(transparent)] - Auth(eyre::Report), + Auth(anyhow::Error), /// The requested resource does not exist. #[error(transparent)] - NotFound(eyre::Report), + NotFound(anyhow::Error), /// The request conflicts with the current state of the resource. #[error(transparent)] - Conflict(eyre::Report), + Conflict(anyhow::Error), /// A service dependency failed to complete the request. #[error(transparent)] - FailedDependency(eyre::Report), + FailedDependency(anyhow::Error), /// The request requires a precondition. #[error(transparent)] - PreconditionRequired(eyre::Report), + PreconditionRequired(anyhow::Error), /// A request precondition was not met. #[error(transparent)] - PreconditionFailed(eyre::Report), + PreconditionFailed(anyhow::Error), /// The caller exceeded a request rate limit. #[error(transparent)] - RateLimit(eyre::Report), + RateLimit(anyhow::Error), } impl ApiError { /// Adds context to the contained report while preserving the HTTP status. - pub(crate) fn wrap_err(self, msg: D) -> Self + pub(crate) fn context(self, msg: D) -> Self where D: Send + Sync + std::fmt::Debug + std::fmt::Display + 'static, { match self { - Self::Internal(report) => Self::Internal(report.wrap_err(msg)), - Self::Request(report) => Self::Request(report.wrap_err(msg)), - Self::Auth(report) => Self::Auth(report.wrap_err(msg)), - Self::NotFound(report) => Self::NotFound(report.wrap_err(msg)), - Self::Conflict(report) => Self::Conflict(report.wrap_err(msg)), + Self::Internal(report) => Self::Internal(report.context(msg)), + Self::Request(report) => Self::Request(report.context(msg)), + Self::Auth(report) => Self::Auth(report.context(msg)), + Self::NotFound(report) => Self::NotFound(report.context(msg)), + Self::Conflict(report) => Self::Conflict(report.context(msg)), Self::FailedDependency(report) => { - Self::FailedDependency(report.wrap_err(msg)) + Self::FailedDependency(report.context(msg)) } Self::PreconditionRequired(report) => { - Self::PreconditionRequired(report.wrap_err(msg)) + Self::PreconditionRequired(report.context(msg)) } Self::PreconditionFailed(report) => { - Self::PreconditionFailed(report.wrap_err(msg)) + Self::PreconditionFailed(report.context(msg)) } - Self::RateLimit(report) => Self::RateLimit(report.wrap_err(msg)), + Self::RateLimit(report) => Self::RateLimit(report.context(msg)), } } @@ -700,12 +701,13 @@ mod tests { use crate::auth::AuthenticationError; use actix_web::ResponseError; use actix_web::http::StatusCode; + use anyhow::anyhow; #[test] fn api_error_reports_locked_account_as_forbidden() { let error = ApiError::Auth( - eyre::Report::new(AuthenticationError::AccountLocked) - .wrap_err("authenticating API request"), + anyhow::Error::new(AuthenticationError::AccountLocked) + .context("authenticating API request"), ); assert_eq!(error.status_code(), StatusCode::FORBIDDEN); @@ -715,9 +717,9 @@ mod tests { #[test] fn api_error_serializes_source_chain_as_details() { let error = ApiError::Request( - eyre::eyre!("root cause") - .wrap_err("intermediate context") - .wrap_err("request failed"), + anyhow!("root cause") + .context("intermediate context") + .context("request failed"), ); let response = error.as_api_error(); diff --git a/apps/labrinth/src/routes/updates.rs b/apps/labrinth/src/routes/updates.rs index 0329e3d3fe3..70d07866134 100644 --- a/apps/labrinth/src/routes/updates.rs +++ b/apps/labrinth/src/routes/updates.rs @@ -1,5 +1,6 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context as _; +use anyhow::anyhow; use std::cmp::Reverse; use std::collections::HashMap; @@ -58,8 +59,8 @@ pub async fn forge_updates( let project = database::models::DBProject::get(&id, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| ERROR.to_string())?; + .internal_context("fetching project from database")? + .request_context_with(|| ERROR.to_string())?; let user_option = get_user_from_headers( &req, @@ -73,9 +74,9 @@ pub async fn forge_updates( if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::Request(eyre::eyre!("{ERROR}"))); + return Err(ApiError::Request(anyhow!("{ERROR}"))); } let versions = database::models::DBVersion::get_many( @@ -84,7 +85,7 @@ pub async fn forge_updates( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let loaders = match &*neo.neoforge { "only" => |x: &String| *x == "neoforge", @@ -102,7 +103,7 @@ pub async fn forge_updates( &redis, ) .await - .wrap_api_err("fetching compatible update versions")?; + .api_context("fetching compatible update versions")?; versions.sort_by_key(|b| Reverse(b.date_published)); diff --git a/apps/labrinth/src/routes/v2/notifications.rs b/apps/labrinth/src/routes/v2/notifications.rs index 52f279fa6c4..1960b9f1266 100644 --- a/apps/labrinth/src/routes/v2/notifications.rs +++ b/apps/labrinth/src/routes/v2/notifications.rs @@ -67,7 +67,7 @@ pub async fn notifications_get( .await .or_else(v2_reroute::flatten_404_error); match v2_reroute::extract_ok_json::>( - resp.wrap_api_err("extracting v2 response body")?, + resp.api_context("extracting v2 response body")?, ) .await { @@ -121,7 +121,7 @@ pub async fn notification_get( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; match v2_reroute::extract_ok_json::(response).await { Ok(notification) => { let notification = LegacyNotification::from(notification); diff --git a/apps/labrinth/src/routes/v2/projects.rs b/apps/labrinth/src/routes/v2/projects.rs index e91fcc468da..ac2a76384b5 100644 --- a/apps/labrinth/src/routes/v2/projects.rs +++ b/apps/labrinth/src/routes/v2/projects.rs @@ -86,7 +86,7 @@ pub async fn project_search( // in the API calls except that 'versions:x' is now 'game_versions:x' let facets: Option>> = if let Some(facets) = info.facets { let facets = serde_json::from_str::>>(&facets) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; Some( facets @@ -129,7 +129,7 @@ pub async fn project_search( let results = search_backend .search_for_project(&info, &redis) .await - .wrap_api_err("searching projects")?; + .api_context("searching projects")?; let results = LegacySearchResults::from(results); @@ -208,16 +208,14 @@ pub async fn random_projects_get( .await .or_else(v2_reroute::flatten_404_error) .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { Ok(project) => { let legacy_projects = LegacyProject::from_many(project, &ro_pool, &redis) .await - .wrap_internal_err( - "executing `LegacyProject::from_many`", - )?; + .internal_context("executing `LegacyProject::from_many`")?; Ok(HttpResponse::Ok().json(legacy_projects)) } Err(response) => Ok(response), @@ -243,7 +241,7 @@ pub async fn projects_get( session_queue: web::Data, ) -> Result { let project_refs = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing project references")?; + .request_context("deserializing project references")?; if let Some(response) = crate::routes::redirect_query_refs( &req, "ids", @@ -269,7 +267,7 @@ pub async fn projects_get( .await .or_else(v2_reroute::flatten_404_error) .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { @@ -277,9 +275,7 @@ pub async fn projects_get( let legacy_projects = LegacyProject::from_many(project, &ro_pool, &redis) .await - .wrap_internal_err( - "executing `LegacyProject::from_many`", - )?; + .internal_context("executing `LegacyProject::from_many`")?; Ok(HttpResponse::Ok().json(legacy_projects)) } Err(response) => Ok(response), @@ -347,7 +343,7 @@ pub async fn project_get( Some(vid) => { version_item::DBVersion::get((*vid).into(), &***ro_pool, &redis) .await - .wrap_internal_err("fetching version from database")? + .internal_context("fetching version from database")? } None => None, }; @@ -358,7 +354,7 @@ pub async fn project_get( &***ro_pool, ) .await - .wrap_internal_err("fetching archival disclosure status")? + .internal_context("fetching archival disclosure status")? .contains(&project.id.into()); let mut project = LegacyProject::from(project, version_item); if has_archived_disclosure && project.status == ProjectStatus::Approved { @@ -468,7 +464,7 @@ pub async fn dependency_list( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; match v2_reroute::extract_ok_json::< crate::routes::v3::projects::DependencyInfo, @@ -482,7 +478,7 @@ pub async fn dependency_list( &redis, ) .await - .wrap_internal_err( + .internal_context( "converting dependency projects to legacy responses", )?; let converted_versions = dependency_info @@ -704,7 +700,7 @@ pub async fn project_edit( let fetched_example_project = project_item::DBProject::get(&info.0, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; let donation_links = fetched_example_project .map(|x| { x.urls @@ -781,12 +777,12 @@ pub async fn project_edit( &redis, ) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; let version_ids = project_item.map(|x| x.versions).unwrap_or_default(); let versions = version_item::DBVersion::get_many(&version_ids, &**pool, &redis) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; for version in versions { let environment = version .inner @@ -825,7 +821,7 @@ pub async fn project_edit( search_state.clone(), ) .await - .wrap_api_err("editing project")?; + .api_context("editing project")?; } } Ok(response) @@ -924,7 +920,7 @@ pub async fn projects_edit( search_state: web::Data, ) -> Result { let project_refs = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing project references")?; + .request_context("deserializing project references")?; if let Some(response) = crate::routes::redirect_query_refs( &req, "ids", diff --git a/apps/labrinth/src/routes/v2/reports.rs b/apps/labrinth/src/routes/v2/reports.rs index c43cce0fd61..9bd38459722 100644 --- a/apps/labrinth/src/routes/v2/reports.rs +++ b/apps/labrinth/src/routes/v2/reports.rs @@ -46,7 +46,7 @@ pub async fn report_create( v3::reports::report_create(req, pool, body, redis, session_queue) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { @@ -113,7 +113,7 @@ pub async fn reports( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { @@ -169,7 +169,7 @@ pub async fn reports_get( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { @@ -215,7 +215,7 @@ pub async fn report_get( v3::reports::report_get(req, pool, redis, info, session_queue) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { diff --git a/apps/labrinth/src/routes/v2/statistics.rs b/apps/labrinth/src/routes/v2/statistics.rs index a44a908705d..90fa394f439 100644 --- a/apps/labrinth/src/routes/v2/statistics.rs +++ b/apps/labrinth/src/routes/v2/statistics.rs @@ -38,7 +38,7 @@ pub async fn get_stats( let response = v3::statistics::get_stats(ro_pool) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; match v2_reroute::extract_ok_json::(response).await { Ok(stats) => { diff --git a/apps/labrinth/src/routes/v2/tags.rs b/apps/labrinth/src/routes/v2/tags.rs index 164e98c0837..5ba77478a8b 100644 --- a/apps/labrinth/src/routes/v2/tags.rs +++ b/apps/labrinth/src/routes/v2/tags.rs @@ -60,7 +60,7 @@ pub async fn category_list( ) -> Result { let response = v3::tags::category_list(pool, redis) .await - .wrap_api_err("executing `tags::category_list`")?; + .api_context("executing `tags::category_list`")?; // Convert to V2 format match v2_reroute::extract_ok_json::>(response) @@ -110,7 +110,7 @@ pub async fn loader_list( ) -> Result { let response = v3::tags::loader_list(pool, redis) .await - .wrap_api_err("executing `tags::loader_list`")?; + .api_context("executing `tags::loader_list`")?; // Convert to V2 format match v2_reroute::extract_ok_json::>(response) @@ -295,7 +295,7 @@ pub async fn license_text( let license = v3::tags::license_text(params) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert to V2 format Ok( @@ -343,7 +343,7 @@ pub async fn donation_platform_list( ) -> Result { let response = v3::tags::link_platform_list(pool, redis) .await - .wrap_api_err("executing `tags::link_platform_list`")?; + .api_context("executing `tags::link_platform_list`")?; // Convert to V2 format Ok( diff --git a/apps/labrinth/src/routes/v2/teams.rs b/apps/labrinth/src/routes/v2/teams.rs index 1378214e3a7..1275b555e20 100644 --- a/apps/labrinth/src/routes/v2/teams.rs +++ b/apps/labrinth/src/routes/v2/teams.rs @@ -79,7 +79,7 @@ pub async fn team_members_get_project( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { Ok(members) => { @@ -118,7 +118,7 @@ pub async fn team_members_get( v3::teams::team_members_get(req, info, pool, redis, session_queue) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { Ok(members) => { @@ -166,7 +166,7 @@ pub async fn teams_get( .or_else(v2_reroute::flatten_404_error); // Convert response to V2 format match v2_reroute::extract_ok_json::>>( - response.wrap_api_err("extracting v2 response body")?, + response.api_context("extracting v2 response body")?, ) .await { diff --git a/apps/labrinth/src/routes/v2/threads.rs b/apps/labrinth/src/routes/v2/threads.rs index e110ef5b987..83a1d050d47 100644 --- a/apps/labrinth/src/routes/v2/threads.rs +++ b/apps/labrinth/src/routes/v2/threads.rs @@ -90,7 +90,7 @@ pub async fn threads_get( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { diff --git a/apps/labrinth/src/routes/v2/users.rs b/apps/labrinth/src/routes/v2/users.rs index 860159d638b..b8ccb9b10d0 100644 --- a/apps/labrinth/src/routes/v2/users.rs +++ b/apps/labrinth/src/routes/v2/users.rs @@ -56,7 +56,7 @@ pub async fn user_auth_get( let response = v3::users::user_auth_get(req, pool, redis, session_queue) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { @@ -100,7 +100,7 @@ pub async fn users_get( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { @@ -141,7 +141,7 @@ pub async fn user_get( let response = v3::users::user_get(req, info, pool, redis, session_queue) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { @@ -187,7 +187,7 @@ pub async fn projects_list( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert to V2 projects match v2_reroute::extract_ok_json::>(response).await { @@ -195,9 +195,7 @@ pub async fn projects_list( let legacy_projects = LegacyProject::from_many(project, &pool, &redis) .await - .wrap_internal_err( - "executing `LegacyProject::from_many`", - )?; + .internal_context("executing `LegacyProject::from_many`")?; Ok(HttpResponse::Ok().json(legacy_projects)) } Err(response) => Ok(response), @@ -459,7 +457,7 @@ pub async fn user_follows( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert to V2 projects match v2_reroute::extract_ok_json::>(response).await { @@ -467,9 +465,7 @@ pub async fn user_follows( let legacy_projects = LegacyProject::from_many(project, &pool, &redis) .await - .wrap_internal_err( - "executing `LegacyProject::from_many`", - )?; + .internal_context("executing `LegacyProject::from_many`")?; Ok(HttpResponse::Ok().json(legacy_projects)) } Err(response) => Ok(response), @@ -510,7 +506,7 @@ pub async fn user_notifications( v3::users::user_notifications(req, info, pool, redis, session_queue) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { Ok(notifications) => { diff --git a/apps/labrinth/src/routes/v2/version_creation.rs b/apps/labrinth/src/routes/v2/version_creation.rs index ad5fa5d50f8..ac268a608a8 100644 --- a/apps/labrinth/src/routes/v2/version_creation.rs +++ b/apps/labrinth/src/routes/v2/version_creation.rs @@ -78,7 +78,7 @@ pub struct InitialVersionData { pub(super) fn parse_mrpack_loaders( loaders: &[Loader], -) -> Result, eyre::Report> { +) -> Result, anyhow::Error> { loaders.iter().map(|loader| loader.0.parse()).collect() } diff --git a/apps/labrinth/src/routes/v2/version_file.rs b/apps/labrinth/src/routes/v2/version_file.rs index d4f7d477d99..6bf848f4ccc 100644 --- a/apps/labrinth/src/routes/v2/version_file.rs +++ b/apps/labrinth/src/routes/v2/version_file.rs @@ -72,7 +72,7 @@ pub async fn get_version_from_hash( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { @@ -237,7 +237,7 @@ pub async fn get_update_from_hash( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { @@ -294,7 +294,7 @@ pub async fn get_versions_from_hashes( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert to V2 match v2_reroute::extract_ok_json::>(response) @@ -348,7 +348,7 @@ pub async fn get_projects_from_hashes( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert to V2 match v2_reroute::extract_ok_json::>(response) @@ -368,7 +368,7 @@ pub async fn get_projects_from_hashes( &redis, ) .await - .wrap_internal_err("converting projects to legacy responses")?; + .internal_context("converting projects to legacy responses")?; let legacy_projects_hashes = hash_to_project_id .into_iter() .filter_map(|(hash, project_id)| { @@ -585,7 +585,7 @@ pub async fn update_individual_files( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response) diff --git a/apps/labrinth/src/routes/v2/versions.rs b/apps/labrinth/src/routes/v2/versions.rs index 36c46a485db..25d1b226b53 100644 --- a/apps/labrinth/src/routes/v2/versions.rs +++ b/apps/labrinth/src/routes/v2/versions.rs @@ -1,6 +1,7 @@ use crate::util::MinecraftMeta; use crate::util::error::ApiContext as _; use crate::util::error::Context as _; +use anyhow::anyhow; use std::collections::HashMap; use super::ApiError; @@ -167,7 +168,7 @@ pub async fn version_list( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { @@ -234,7 +235,7 @@ pub async fn version_project_get( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { Ok(version) => { @@ -300,7 +301,7 @@ pub async fn versions_get( .featured .map(|value| value.parse::()) .transpose() - .wrap_request_err("deserializing `featured`")?, + .request_context("deserializing `featured`")?, version_type: query .version_type .map(|value| match value.as_str() { @@ -313,26 +314,26 @@ pub async fn versions_get( "alpha" => { Ok(crate::models::projects::VersionType::Alpha) } - _ => Err(eyre::eyre!("invalid version type `{value}`")), + _ => Err(anyhow!("invalid version type `{value}`")), }) .transpose() - .wrap_request_err("deserializing `version_type`")?, + .request_context("deserializing `version_type`")?, limit: query .limit .map(|value| value.parse::()) .transpose() - .wrap_request_err("deserializing `limit`")?, + .request_context("deserializing `limit`")?, offset: query .offset .map(|value| value.parse::()) .transpose() - .wrap_request_err("deserializing `offset`")?, + .request_context("deserializing `offset`")?, include_changelog: query.include_changelog, }; let project_ids = serde_json::from_str::>(&project_ids) - .wrap_request_err("deserializing `project_ids`")?; + .request_context("deserializing `project_ids`")?; if project_ids.len() > 100 { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "`project_ids` must contain at most 100 projects" ))); } @@ -342,7 +343,7 @@ pub async fn versions_get( ] { if let Some(value) = value { serde_json::from_str::>(value) - .wrap_request_err_with(|| { + .request_context_with(|| { format!("deserializing `{name}`") })?; } @@ -352,7 +353,7 @@ pub async fn versions_get( .as_deref() .map(serde_json::from_str::>) .transpose() - .wrap_request_err("deserializing `loaders`")?; + .request_context("deserializing `loaders`")?; let user_option = crate::auth::get_user_from_headers( &req, &**pool, @@ -368,7 +369,7 @@ pub async fn versions_get( &redis, ) .await - .wrap_internal_err("fetching projects from database")?; + .internal_context("fetching projects from database")?; let visible = crate::auth::checks::filter_visible_project_ids( projects.iter().map(|p| &p.inner).collect(), &user_option, @@ -376,7 +377,7 @@ pub async fn versions_get( false, ) .await - .wrap_api_err("filtering visible projects")?; + .api_context("filtering visible projects")?; projects.retain(|p| visible.contains(&p.inner.id)); let project_ids = projects .iter() @@ -388,7 +389,7 @@ pub async fn versions_get( ) .fetch_all(&***ro_pool) .await - .wrap_internal_err("fetching project version ids from database")? + .internal_context("fetching project version ids from database")? .into_iter() .map(|version| crate::database::models::ids::DBVersionId(version.id)) .collect::>(); @@ -398,7 +399,7 @@ pub async fn versions_get( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let mut grouped = HashMap::new(); for version in versions { if let Some(loaders) = &requested_loaders { @@ -472,7 +473,7 @@ pub async fn versions_get( &redis, ) .await - .wrap_api_err("filtering visible versions")?; + .api_context("filtering visible versions")?; response.sort_by(|a, b| { b.date_published .cmp(&a.date_published) @@ -492,7 +493,7 @@ pub async fn versions_get( return Ok(HttpResponse::Ok().json(response)); } _ => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "exactly one of `ids` and `project_ids` is required" ))); } @@ -507,7 +508,7 @@ pub async fn versions_get( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::>(response).await { @@ -560,7 +561,7 @@ pub async fn version_get( .await .map(|b| HttpResponse::Ok().json(b)) .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("flattening v2 not-found response")?; + .api_context("flattening v2 not-found response")?; // Convert response to V2 format match v2_reroute::extract_ok_json::(response).await { Ok(version) => { @@ -707,7 +708,7 @@ pub async fn version_edit( { component.mrpack_loaders = Some( super::version_creation::parse_mrpack_loaders(&values) - .wrap_request_err("parsing mrpack loaders")?, + .request_context("parsing mrpack loaders")?, ); } @@ -747,7 +748,7 @@ pub async fn version_edit( ) .await .or_else(v2_reroute::flatten_404_error) - .wrap_api_err("editing version through v3 route")?; + .api_context("editing version through v3 route")?; Ok(response) } diff --git a/apps/labrinth/src/routes/v3/analytics_event.rs b/apps/labrinth/src/routes/v3/analytics_event.rs index 53142b411e9..91ba896ca29 100644 --- a/apps/labrinth/src/routes/v3/analytics_event.rs +++ b/apps/labrinth/src/routes/v3/analytics_event.rs @@ -23,7 +23,7 @@ pub async fn analytics_events_get( ) -> Result>, ApiError> { let events = DBAnalyticsEvent::get_all(&**pool, &redis) .await - .wrap_internal_err("failed to fetch analytics events")? + .internal_context("failed to fetch analytics events")? .into_iter() .map(AnalyticsEvent::from) .collect(); diff --git a/apps/labrinth/src/routes/v3/analytics_get/facets/fixed.rs b/apps/labrinth/src/routes/v3/analytics_get/facets/fixed.rs index dc45d3828f4..10a1517a91f 100644 --- a/apps/labrinth/src/routes/v3/analytics_get/facets/fixed.rs +++ b/apps/labrinth/src/routes/v3/analytics_get/facets/fixed.rs @@ -18,7 +18,7 @@ pub async fn fetch( ) -> Result { let tags = valid_download_tags(pool, redis, minecraft_meta) .await - .wrap_api_err("executing `valid_download_tags`")?; + .api_context("executing `valid_download_tags`")?; let mut loaders = tags.loaders.iter().cloned().collect::>(); loaders.sort(); let mut game_versions = diff --git a/apps/labrinth/src/routes/v3/analytics_get/facets/mod.rs b/apps/labrinth/src/routes/v3/analytics_get/facets/mod.rs index 8e15f93cc12..4e1494a3d2d 100644 --- a/apps/labrinth/src/routes/v3/analytics_get/facets/mod.rs +++ b/apps/labrinth/src/routes/v3/analytics_get/facets/mod.rs @@ -83,11 +83,11 @@ pub async fn fetch_facets( Scopes::ANALYTICS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let facets = fixed::fetch(&pool, &redis, &minecraft_meta) .await - .wrap_api_err("executing `fixed::fetch`")?; + .api_context("executing `fixed::fetch`")?; Ok(web::Json(FacetsResponse { facets })) } diff --git a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_downloads.rs b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_downloads.rs index 8f3845fcdf5..a9c942197ba 100644 --- a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_downloads.rs +++ b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_downloads.rs @@ -303,7 +303,7 @@ async fn fetch_dependent_on_version_filter( ) .fetch_all(pool) .await - .wrap_internal_err("failed to fetch dependent project versions")?; + .internal_context("failed to fetch dependent project versions")?; Ok(versions .into_iter() @@ -344,7 +344,7 @@ async fn fetch_dependent_version_projects( ) .fetch_all(cx.pool) .await - .wrap_internal_err("failed to fetch dependent version projects")?; + .internal_context("failed to fetch dependent version projects")?; Ok(versions .into_iter() @@ -361,7 +361,7 @@ pub(crate) async fn fetch( let dependent_on_version_filter = fetch_dependent_on_version_filter(metrics, cx.pool) .await - .wrap_api_err("fetching dependent on version filter")?; + .api_context("fetching dependent on version filter")?; if !metrics.filter_by.dependent_project_id.is_empty() && dependent_on_version_filter.is_empty() { @@ -438,13 +438,13 @@ pub(crate) async fn fetch( }; let mut cursor = query .fetch::() - .wrap_internal_err("fetching project-download pagination cursor")?; + .internal_context("fetching project-download pagination cursor")?; let mut rows = Vec::new(); while let Some(row) = cursor .next() .await - .wrap_internal_err("fetching project downloads")? + .internal_context("fetching project downloads")? { rows.push(row); } @@ -452,7 +452,7 @@ pub(crate) async fn fetch( let dependent_version_projects = fetch_dependent_version_projects(&rows, cx) .await - .wrap_api_err("fetching dependent version projects")?; + .api_context("fetching dependent version projects")?; let mut buckets = HashMap::::new(); for row in rows { @@ -579,7 +579,7 @@ pub(crate) async fn fetch( }), }), ) - .wrap_api_err("executing `ProjectMetrics::Downloads`")?; + .api_context("executing `ProjectMetrics::Downloads`")?; } Ok(()) diff --git a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_playtime.rs b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_playtime.rs index f5ce8767b0e..9b4ab1405f0 100644 --- a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_playtime.rs +++ b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_playtime.rs @@ -231,13 +231,13 @@ pub(crate) async fn fetch( let mut cursor = query .fetch::() - .wrap_internal_err("fetching project-playtime pagination cursor")?; + .internal_context("fetching project-playtime pagination cursor")?; let mut buckets = HashMap::::new(); while let Some(row) = cursor .next() .await - .wrap_internal_err("fetching project playtime")? + .internal_context("fetching project playtime")? { let project_id = if uses_column("use_project_id") && row.project_id.0 == 0 { @@ -317,7 +317,7 @@ pub(crate) async fn fetch( }), }), ) - .wrap_api_err("executing `ProjectMetrics::Playtime`")?; + .api_context("executing `ProjectMetrics::Playtime`")?; } Ok(()) diff --git a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_revenue.rs b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_revenue.rs index c03de3cf8c3..ca1671037de 100644 --- a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_revenue.rs +++ b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_revenue.rs @@ -1,4 +1,5 @@ use crate::util::error::ApiContext as _; +use anyhow::anyhow; use futures::StreamExt; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; @@ -100,13 +101,13 @@ pub(crate) async fn fetch( .next() .await .transpose() - .wrap_internal_err("fetching project revenue")? + .internal_context("fetching project revenue")? { let bucket = row .bucket - .wrap_internal_err("bucket should be non-null - query bug!")?; - let bucket = usize::try_from(bucket).wrap_internal_err_with(|| { - eyre::eyre!( + .internal_context("bucket should be non-null - query bug!")?; + let bucket = usize::try_from(bucket).internal_context_with(|| { + anyhow!( "bucket value {bucket} does not fit into `usize` - query bug!" ) })?; @@ -130,7 +131,7 @@ pub(crate) async fn fetch( }), }), ) - .wrap_api_err("adding project revenue to time slice")?; + .api_context("adding project revenue to time slice")?; } } diff --git a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_views.rs b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_views.rs index a1b276e99cd..5cc02d29b42 100644 --- a/apps/labrinth/src/routes/v3/analytics_get/metrics/project_views.rs +++ b/apps/labrinth/src/routes/v3/analytics_get/metrics/project_views.rs @@ -192,13 +192,13 @@ pub(crate) async fn fetch( let mut cursor = query .fetch::() - .wrap_internal_err("fetching project-view pagination cursor")?; + .internal_context("fetching project-view pagination cursor")?; let mut buckets = HashMap::::new(); while let Some(row) = cursor .next() .await - .wrap_internal_err("fetching project views")? + .internal_context("fetching project views")? { let key = ViewBucket { bucket: row.bucket, @@ -261,7 +261,7 @@ pub(crate) async fn fetch( }), }), ) - .wrap_api_err("executing `ProjectMetrics::Views`")?; + .api_context("executing `ProjectMetrics::Views`")?; } Ok(()) diff --git a/apps/labrinth/src/routes/v3/analytics_get/mod.rs b/apps/labrinth/src/routes/v3/analytics_get/mod.rs index 69eb0640db2..e4afc76d58b 100644 --- a/apps/labrinth/src/routes/v3/analytics_get/mod.rs +++ b/apps/labrinth/src/routes/v3/analytics_get/mod.rs @@ -22,9 +22,9 @@ use std::{ use crate::database::{PgPool, models::DBUserId}; use actix_web::{HttpRequest, post, web}; +use anyhow::anyhow; use ariadne::ids::UserId; use chrono::{DateTime, TimeDelta, Utc}; -use eyre::eyre; use serde::{Deserialize, Serialize}; use crate::{ @@ -193,11 +193,11 @@ pub async fn fetch_analytics( Scopes::ANALYTICS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let full_time_range = req.time_range.end - req.time_range.start; if full_time_range < TimeDelta::zero() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "End date must be after start date", ))); } @@ -205,17 +205,17 @@ pub async fn fetch_analytics( let (num_time_slices, resolution) = match req.time_range.resolution { TimeRangeResolution::Slices(slices) => { let slices = i32::try_from(slices.get()) - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("number of slices must fit into an `i32`")?; + .map_err(|err| anyhow!(err)) + .request_context("number of slices must fit into an `i32`")?; let resolution = full_time_range / slices; (slices as usize, resolution) } TimeRangeResolution::Minutes(resolution_minutes) => { let resolution_minutes = i64::try_from(resolution_minutes.get()) - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("resolution must fit into a `i64`")?; + .map_err(|err| anyhow!(err)) + .request_context("resolution must fit into a `i64`")?; let resolution = TimeDelta::try_minutes(resolution_minutes) - .wrap_request_err_with(|| "resolution overflow")?; + .request_context_with(|| "resolution overflow")?; let num_slices = full_time_range.as_seconds_f64() / resolution.as_seconds_f64(); @@ -225,12 +225,12 @@ pub async fn fetch_analytics( }; if num_time_slices > MAX_TIME_SLICES { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "Resolution is too fine or range is too large - maximum of {MAX_TIME_SLICES} time slices, was {num_time_slices}" ))); } if resolution < MIN_RESOLUTION { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "Resolution must be at least {MIN_RESOLUTION}, was {resolution}", ))); } @@ -241,7 +241,7 @@ pub async fn fetch_analytics( if req.project_ids.is_empty() { DBUser::get_projects(user.user.id.into(), &**pool, &redis) .await - .wrap_internal_err("fetching users from database")? + .internal_context("fetching users from database")? } else { req.project_ids .iter() @@ -253,7 +253,7 @@ pub async fn fetch_analytics( let project_ids = filter_allowed_project_ids(&project_ids, &user, &pool, &redis) .await - .wrap_api_err("filtering allowed project ids")?; + .api_context("filtering allowed project ids")?; let project_id_values = project_ids.iter().map(|id| id.0).collect::>(); @@ -267,7 +267,7 @@ pub async fn fetch_analytics( ) .fetch_all(&**pool) .await - .wrap_internal_err("fetching parent versions from database")?; + .internal_context("fetching parent versions from database")?; let parent_version_ids = parent_versions .iter() .map(|version| DBVersionId(version.id)) @@ -279,7 +279,7 @@ pub async fn fetch_analytics( let parent_version_data = DBVersion::get_many(&parent_version_ids, &**pool, &redis) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let visible_version_ids = filter_visible_version_ids( parent_version_data .iter() @@ -290,7 +290,7 @@ pub async fn fetch_analytics( &redis, ) .await - .wrap_api_err("filtering visible version ids")?; + .api_context("filtering visible version ids")?; let mut project_events = parent_version_data .iter() .filter(|version| { @@ -315,7 +315,7 @@ pub async fn fetch_analytics( &pool, ) .await - .wrap_api_err("fetching project status change events")?, + .api_context("fetching project status change events")?, ); project_events.sort_by_key(|event| event.timestamp); @@ -334,13 +334,13 @@ pub async fn fetch_analytics( if let Some(metrics) = &req.return_metrics.project_views { metrics::fetch_project_views(&mut query_clickhouse_cx, metrics) .await - .wrap_api_err("fetching project views")?; + .api_context("fetching project views")?; } if let Some(metrics) = &req.return_metrics.project_downloads { metrics::fetch_project_downloads(&mut query_clickhouse_cx, metrics) .await - .wrap_api_err("fetching project downloads")?; + .api_context("fetching project downloads")?; } if let Some(metrics) = &req.return_metrics.project_playtime { @@ -350,12 +350,12 @@ pub async fn fetch_analytics( metrics, ) .await - .wrap_api_err("fetching project playtime")?; + .api_context("fetching project playtime")?; } if let Some(metrics) = &req.return_metrics.project_revenue { if !user.scopes.contains(Scopes::PAYOUTS_READ) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials ))); } @@ -375,7 +375,7 @@ pub async fn fetch_analytics( ) .fetch_all(&**pool) .await - .wrap_internal_err("fetching user IDs from database")? + .internal_context("fetching user IDs from database")? .into_iter() .map(|row| row.id) .collect::>(); @@ -391,16 +391,16 @@ pub async fn fetch_analytics( metrics, ) .await - .wrap_api_err("checking mod")?; + .api_context("checking mod")?; } let projects = fetch_response_projects(&mut time_slices, &user, &pool, &redis) .await - .wrap_api_err("fetching response projects")?; + .api_context("fetching response projects")?; let users = fetch_response_users(&time_slices, &pool, &redis) .await - .wrap_api_err("fetching response users")?; + .api_context("fetching response users")?; Ok(web::Json(GetResponse { metrics: time_slices, @@ -502,7 +502,7 @@ async fn fetch_response_projects( let project_ids = project_ids.into_iter().collect::>(); let projects = DBProject::get_many_ids(&project_ids, pool, redis) .await - .wrap_internal_err("fetching analytics projects")?; + .internal_context("fetching analytics projects")?; let visible_project_ids = filter_visible_project_ids( projects.iter().map(|project| &project.inner).collect(), &Some(user.clone()), @@ -510,7 +510,7 @@ async fn fetch_response_projects( false, ) .await - .wrap_api_err("filtering visible project ids")? + .api_context("filtering visible project ids")? .into_iter() .collect::>(); @@ -552,7 +552,7 @@ async fn fetch_response_users( let users = DBUser::get_many_ids(&user_ids, pool, redis) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; Ok(users .into_iter() @@ -620,7 +620,7 @@ async fn fetch_project_status_change_events( ) .fetch_all(&**pool) .await - .wrap_internal_err( + .internal_context( "querying database for `fetch_project_status_change_events`", )?; @@ -711,7 +711,7 @@ pub(crate) fn add_to_time_slice( }; let num_time_slices = time_slices.len(); - let slice = time_slices.get_mut(bucket).wrap_request_err_with(|| format!("bucket {bucket} returned by query out of range for {num_time_slices} - query bug!"))?; + let slice = time_slices.get_mut(bucket).request_context_with(|| format!("bucket {bucket} returned by query out of range for {num_time_slices} - query bug!"))?; slice.0.push(data); Ok(()) @@ -725,7 +725,7 @@ async fn filter_allowed_project_ids( ) -> Result, ApiError> { let projects = DBProject::get_many_ids(project_ids, pool, redis) .await - .wrap_internal_err("fetching projects for analytics authorization")?; + .internal_context("fetching projects for analytics authorization")?; if user.scopes.contains(Scopes::ADMIN_READ) { return Ok(projects.into_iter().map(|x| x.inner.id).collect()); @@ -739,7 +739,7 @@ async fn filter_allowed_project_ids( &team_ids, pool, redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let organization_ids = projects .iter() @@ -751,7 +751,7 @@ async fn filter_allowed_project_ids( redis, ) .await - .wrap_internal_err("fetching organizations from database")?; + .internal_context("fetching organizations from database")?; let organization_team_ids = organizations .iter() @@ -764,7 +764,7 @@ async fn filter_allowed_project_ids( redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; Ok(projects .into_iter() diff --git a/apps/labrinth/src/routes/v3/blocked_users.rs b/apps/labrinth/src/routes/v3/blocked_users.rs index 093517207f8..65badec604d 100644 --- a/apps/labrinth/src/routes/v3/blocked_users.rs +++ b/apps/labrinth/src/routes/v3/blocked_users.rs @@ -8,8 +8,8 @@ use crate::queue::session::AuthQueue; use crate::routes::ApiError; use crate::util::error::Context as _; use actix_web::{HttpRequest, delete, get, post, web}; +use anyhow::anyhow; use ariadne::ids::UserId; -use eyre::eyre; use xredis::RedisPool; pub fn config(cfg: &mut actix_web::web::ServiceConfig) { @@ -36,29 +36,29 @@ pub async fn block_user( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let user_id = info.into_inner().0; let Some(blocked) = DBUser::get(&user_id, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; if blocked.id == user.id.into() { - return Err(ApiError::Request(eyre!("you cannot block yourself"))); + return Err(ApiError::Request(anyhow!("you cannot block yourself"))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; DBFriend::remove(user.id.into(), blocked.id, &mut transaction) .await - .wrap_internal_err("deleting friend from database")?; + .internal_context("deleting friend from database")?; DBBlockedUser { user_id: user.id.into(), @@ -66,12 +66,12 @@ pub async fn block_user( } .insert(&mut transaction) .await - .wrap_internal_err("inserting database records for `block_user`")?; + .internal_context("inserting database records for `block_user`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(()) } @@ -94,20 +94,20 @@ pub async fn unblock_user( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let user_id = info.into_inner().0; let Some(blocked) = DBUser::get(&user_id, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; DBBlockedUser::remove(user.id.into(), blocked.id, &**pool) .await - .wrap_internal_err("deleting blocked user from database")?; + .internal_context("deleting blocked user from database")?; Ok(()) } @@ -129,12 +129,12 @@ pub async fn get_blocked_users( Scopes::USER_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let blocked = DBBlockedUser::get_blocked_for_user(user.id.into(), &**pool) .await - .wrap_internal_err("fetching blocked user from database")? + .internal_context("fetching blocked user from database")? .into_iter() .map(UserId::from) .collect(); diff --git a/apps/labrinth/src/routes/v3/collections.rs b/apps/labrinth/src/routes/v3/collections.rs index 6a22b330cee..c87ff0b091b 100644 --- a/apps/labrinth/src/routes/v3/collections.rs +++ b/apps/labrinth/src/routes/v3/collections.rs @@ -23,9 +23,9 @@ use crate::util::routes::read_limited_from_payload; use crate::util::validate::validation_errors_to_string; use actix_web::web::Data; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, post, web}; +use anyhow::anyhow; use ariadne::ids::base62_impl::parse_base62; use chrono::Utc; -use eyre::eyre; use itertools::Itertools; use serde::{Deserialize, Serialize}; use validator::Validate; @@ -110,7 +110,7 @@ pub async fn collection_create( &redis, ) .await - .wrap_internal_err("failed to fetch created projects")? + .internal_context("failed to fetch created projects")? .into_iter() .map(|x| x.inner.id.into()) .collect::>(); @@ -168,19 +168,19 @@ pub async fn collections_get( session_queue: web::Data, ) -> Result { let ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; let ids = ids .into_iter() .map(|x| { parse_base62(x).map(|x| database::models::DBCollectionId(x as i64)) }) .collect::, _>>() - .wrap_request_err("parsing collection IDs")?; + .request_context("parsing collection IDs")?; let collections_data = database::models::DBCollection::get_many(&ids, &**pool, &redis) .await - .wrap_internal_err("fetching collections from database")?; + .internal_context("fetching collections from database")?; let user_option = get_user_from_headers( &req, @@ -195,7 +195,7 @@ pub async fn collections_get( let collections = filter_visible_collections(collections_data, &user_option, false) .await - .wrap_api_err("filtering visible collections")?; + .api_context("filtering visible collections")?; Ok(HttpResponse::Ok().json(collections)) } @@ -212,12 +212,12 @@ pub async fn collection_get( let string = info.into_inner().0; let id = database::models::DBCollectionId( - parse_base62(&string).wrap_request_err("parsing collection ID")? as i64, + parse_base62(&string).request_context("parsing collection ID")? as i64, ); let collection_data = database::models::DBCollection::get(id, &**pool, &redis) .await - .wrap_internal_err("fetching collection from database")?; + .internal_context("fetching collection from database")?; let user_option = get_user_from_headers( &req, &**pool, @@ -231,11 +231,11 @@ pub async fn collection_get( if let Some(data) = collection_data && is_visible_collection(&data, &user_option, false) .await - .wrap_api_err("checking collection visibility")? + .api_context("checking collection visibility")? { return Ok(HttpResponse::Ok().json(Collection::from(data))); } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } #[derive(Deserialize, Validate, utoipa::ToSchema)] @@ -277,12 +277,12 @@ pub async fn collection_edit( Scopes::COLLECTION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; new_collection .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; if let Some(projects) = &mut new_collection.new_projects { crate::routes::resolve_body_refs( @@ -296,11 +296,11 @@ pub async fn collection_edit( let string = info.into_inner().0; let id = database::models::DBCollectionId( - parse_base62(&string).wrap_request_err("parsing collection ID")? as i64, + parse_base62(&string).request_context("parsing collection ID")? as i64, ); let result = database::models::DBCollection::get(id, &**pool, &redis) .await - .wrap_internal_err("fetching collection from database")?; + .internal_context("fetching collection from database")?; if let Some(collection_item) = result { if !can_modify_collection(&collection_item, &user) { @@ -312,7 +312,7 @@ pub async fn collection_edit( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(name) = &new_collection.name { sqlx::query!( @@ -326,7 +326,7 @@ pub async fn collection_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `collection_edit`")?; + .internal_context("querying database for `collection_edit`")?; } if let Some(description) = &new_collection.description { @@ -341,7 +341,7 @@ pub async fn collection_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `collection_edit`")?; + .internal_context("querying database for `collection_edit`")?; } if let Some(status) = &new_collection.status { @@ -349,7 +349,7 @@ pub async fn collection_edit( || collection_item.status.is_approved() && status.can_be_requested()) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to set this status!", ))); } @@ -365,7 +365,7 @@ pub async fn collection_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `collection_edit`")?; + .internal_context("querying database for `collection_edit`")?; } if let Some(new_project_ids) = &new_collection.new_projects { @@ -379,7 +379,7 @@ pub async fn collection_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("fetching new project IDs from database")?; + .internal_context("fetching new project IDs from database")?; let collection_item_ids = new_project_ids .iter() @@ -391,9 +391,11 @@ pub async fn collection_edit( project_id, &**pool, &redis, ) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { - eyre!("the specified project `{project_id}` does not exist") + .internal_context("fetching project from database")? + .request_context_with(|| { + anyhow!( + "the specified project `{project_id}` does not exist" + ) })?; validated_project_ids.push(project.inner.id.0); } @@ -409,7 +411,7 @@ pub async fn collection_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `collection_edit`")?; + .internal_context("querying database for `collection_edit`")?; sqlx::query!( " @@ -421,20 +423,20 @@ pub async fn collection_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `collection_edit`")?; + .internal_context("querying database for `collection_edit`")?; } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::DBCollection::clear_cache(collection_item.id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -469,17 +471,17 @@ pub async fn collection_icon_edit( Scopes::COLLECTION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let id = database::models::DBCollectionId( - parse_base62(&string).wrap_request_err("parsing collection ID")? as i64, + parse_base62(&string).request_context("parsing collection ID")? as i64, ); let collection_item = database::models::DBCollection::get(id, &**pool, &redis) .await - .wrap_internal_err("fetching collection from database")? - .wrap_request_err_with(|| { + .internal_context("fetching collection from database")? + .request_context_with(|| { "the specified collection does not exist!".to_string() })?; @@ -494,7 +496,7 @@ pub async fn collection_icon_edit( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; let bytes = read_limited_from_payload( &mut payload, @@ -520,12 +522,12 @@ pub async fn collection_icon_edit( &**file_host, ) .await - .wrap_api_err("uploading image")?; + .api_context("uploading image")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -540,15 +542,15 @@ pub async fn collection_icon_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `collection_icon_edit`")?; + .internal_context("querying database for `collection_icon_edit`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::DBCollection::clear_cache(collection_item.id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } @@ -571,17 +573,17 @@ pub async fn delete_collection_icon( Scopes::COLLECTION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let id = database::models::DBCollectionId( - parse_base62(&string).wrap_request_err("parsing collection ID")? as i64, + parse_base62(&string).request_context("parsing collection ID")? as i64, ); let collection_item = database::models::DBCollection::get(id, &**pool, &redis) .await - .wrap_internal_err("fetching collection from database")? - .wrap_request_err_with(|| { + .internal_context("fetching collection from database")? + .request_context_with(|| { "the specified collection does not exist!".to_string() })?; if !can_modify_collection(&collection_item, &user) { @@ -595,11 +597,11 @@ pub async fn delete_collection_icon( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -611,15 +613,15 @@ pub async fn delete_collection_icon( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `delete_collection_icon`")?; + .internal_context("querying database for `delete_collection_icon`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::DBCollection::clear_cache(collection_item.id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } @@ -641,16 +643,16 @@ pub async fn collection_delete( Scopes::COLLECTION_DELETE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let id = database::models::DBCollectionId( - parse_base62(&string).wrap_request_err("parsing collection ID")? as i64, + parse_base62(&string).request_context("parsing collection ID")? as i64, ); let collection = database::models::DBCollection::get(id, &**pool, &redis) .await - .wrap_internal_err("fetching collection from database")? - .wrap_request_err_with(|| { + .internal_context("fetching collection from database")? + .request_context_with(|| { "the specified collection does not exist!".to_string() })?; if !can_modify_collection(&collection, &user) { @@ -659,7 +661,7 @@ pub async fn collection_delete( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let result = database::models::DBCollection::remove( collection.id, @@ -667,20 +669,20 @@ pub async fn collection_delete( &redis, ) .await - .wrap_internal_err("deleting collection from database")?; + .internal_context("deleting collection from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::DBCollection::clear_cache(collection.id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; if result.is_some() { Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/routes/v3/content/mod.rs b/apps/labrinth/src/routes/v3/content/mod.rs index f99ca47476b..0b900a78fe5 100644 --- a/apps/labrinth/src/routes/v3/content/mod.rs +++ b/apps/labrinth/src/routes/v3/content/mod.rs @@ -13,6 +13,7 @@ use crate::models::projects::{DependencyType, Version, VersionType}; use crate::queue::session::AuthQueue; use crate::util::error::ApiContext as _; use actix_web::{HttpRequest, post, web}; +use anyhow::anyhow; use ariadne::ids::base62_impl::parse_base62; use async_trait::async_trait; use modrinth_content_management::{ @@ -80,7 +81,7 @@ pub async fn resolve_content( .await } .map_err(resolve_error_to_api) - .wrap_api_err("executing `modrinth_content_management::resolve_content`")?; + .api_context("executing `modrinth_content_management::resolve_content`")?; Ok(web::Json(plan)) } @@ -651,33 +652,31 @@ fn resolve_provider_error(error: impl std::fmt::Display) -> ResolveError { fn resolve_error_to_api(error: ResolveError) -> ApiError { match error { - ResolveError::UnknownContentType(content_type) => ApiError::Request( - eyre::eyre!("unknown content type `{content_type}`"), - ), + ResolveError::UnknownContentType(content_type) => { + ApiError::Request(anyhow!("unknown content type `{content_type}`")) + } ResolveError::ConflictingProjectVersions { project_id, before, after, - } => ApiError::Request(eyre::eyre!( + } => ApiError::Request(anyhow!( "project `{project_id}` has conflicting versions `{before}` and `{after}`" )), - ResolveError::Provider(message) => { - ApiError::Internal(eyre::eyre!(message)) + ResolveError::Provider(message) => ApiError::Internal(anyhow!(message)), + ResolveError::ProjectNotFound(project_id) => { + ApiError::Request(anyhow!("project `{project_id}` was not found")) + } + ResolveError::VersionNotFound(version_id) => { + ApiError::Request(anyhow!("version `{version_id}` was not found")) } - ResolveError::ProjectNotFound(project_id) => ApiError::Request( - eyre::eyre!("project `{project_id}` was not found"), - ), - ResolveError::VersionNotFound(version_id) => ApiError::Request( - eyre::eyre!("version `{version_id}` was not found"), - ), ResolveError::VersionProjectMismatch { version_id, project_id, - } => ApiError::Request(eyre::eyre!( + } => ApiError::Request(anyhow!( "version `{version_id}` does not belong to project `{project_id}`" )), ResolveError::NoCompatibleVersion(project_id) => { - ApiError::Request(eyre::eyre!( + ApiError::Request(anyhow!( "no compatible version was found for project `{project_id}`" )) } diff --git a/apps/labrinth/src/routes/v3/disclosures.rs b/apps/labrinth/src/routes/v3/disclosures.rs index dac969108f5..5724aa8009c 100644 --- a/apps/labrinth/src/routes/v3/disclosures.rs +++ b/apps/labrinth/src/routes/v3/disclosures.rs @@ -1,6 +1,6 @@ use actix_web::{HttpRequest, HttpResponse, get, patch, web}; +use anyhow::anyhow; use chrono::Utc; -use eyre::eyre; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use xredis::RedisPool; @@ -63,8 +63,8 @@ pub async fn get_project_disclosures( let project = db_models::DBProject::get(&string, &***ro_pool, &redis) .await - .wrap_internal_err("failed to fetch project")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch project")? + .not_found_context("resource not found")?; let user_option = get_user_from_headers( &req, @@ -78,9 +78,9 @@ pub async fn get_project_disclosures( if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_internal_err("failed to check project visibility")? + .internal_context("failed to check project visibility")? { - return Err(ApiError::NotFound(eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let viewer_is_moderator = user_option @@ -91,7 +91,7 @@ pub async fn get_project_disclosures( let viewer_is_member = viewer_is_moderator || is_team_member_project(&project.inner, &user_option, &pool) .await - .wrap_internal_err("failed to check project team membership")?; + .internal_context("failed to check project team membership")?; let disclosures = db_models::DBProjectDisclosure::get_many_for_project( project.inner.id, @@ -99,7 +99,7 @@ pub async fn get_project_disclosures( &***ro_pool, ) .await - .wrap_internal_err("failed to fetch project disclosures")?; + .internal_context("failed to fetch project disclosures")?; Ok(HttpResponse::Ok().json(GetProjectDisclosures { disclosures: disclosures @@ -156,7 +156,7 @@ pub async fn modify_project_disclosures( let body = body.into_inner(); if body.set.is_empty() && body.remove.is_empty() { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "must provide at least one disclosure to set or remove" ))); } @@ -169,12 +169,12 @@ pub async fn modify_project_disclosures( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let project = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("failed to fetch project")? - .wrap_not_found_err("resource not found")?; + .internal_context("failed to fetch project")? + .not_found_context("resource not found")?; let (team_member, organization_team_member) = db_models::DBTeamMember::get_for_project_permissions( @@ -183,7 +183,7 @@ pub async fn modify_project_disclosures( &**pool, ) .await - .wrap_internal_err("failed to fetch project permissions")?; + .internal_context("failed to fetch project permissions")?; let can_edit_details = ProjectPermissions::get_permissions_by_scopes( user.scopes, @@ -193,7 +193,7 @@ pub async fn modify_project_disclosures( .is_some_and(|perms| perms.contains(ProjectPermissions::EDIT_DETAILS)); if !can_edit_details { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to edit this project's disclosures" ))); } @@ -203,7 +203,7 @@ pub async fn modify_project_disclosures( team_member.is_some() || organization_team_member.is_some(); if body.lock_status.is_some() && !is_moderator { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "only moderators can set the lock status of a disclosure" ))); } @@ -225,7 +225,7 @@ pub async fn modify_project_disclosures( &**pool, ) .await - .wrap_internal_err("failed to fetch disclosure lock statuses")?; + .internal_context("failed to fetch disclosure lock statuses")?; let lock_status_of = |disclosure_type: &str| { lock_statuses @@ -239,7 +239,7 @@ pub async fn modify_project_disclosures( let disclosure_type = <&'static str>::from(ProjectDisclosureType::from(disclosure)); if !lock_status_of(disclosure_type).allows_edit() { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you cannot modify the `{disclosure_type}` disclosure, it is locked by a moderator" ))); } @@ -247,7 +247,7 @@ pub async fn modify_project_disclosures( for disclosure_type in &body.remove { if !lock_status_of(disclosure_type).allows_removal() { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you cannot remove the `{disclosure_type}` disclosure, it is locked by a moderator" ))); } @@ -257,7 +257,7 @@ pub async fn modify_project_disclosures( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; for disclosure in body.set { let disclosure_type = @@ -280,7 +280,7 @@ pub async fn modify_project_disclosures( } .upsert(&mut transaction) .await - .wrap_internal_err("failed to upsert project disclosure")?; + .internal_context("failed to upsert project disclosure")?; } for disclosure_type in &body.remove { @@ -290,7 +290,7 @@ pub async fn modify_project_disclosures( let disclosure_type = ProjectDisclosureType::from_str(disclosure_type) .map_err(|_| { - ApiError::Request(eyre!( + ApiError::Request(anyhow!( "unknown disclosure type `{disclosure_type}`" )) })?; @@ -302,7 +302,7 @@ pub async fn modify_project_disclosures( &mut transaction, ) .await - .wrap_internal_err("failed to remove project disclosure")?; + .internal_context("failed to remove project disclosure")?; } super::projects::mutation::finalize_mutation( diff --git a/apps/labrinth/src/routes/v3/friends.rs b/apps/labrinth/src/routes/v3/friends.rs index 526bcddee9d..14295e7db54 100644 --- a/apps/labrinth/src/routes/v3/friends.rs +++ b/apps/labrinth/src/routes/v3/friends.rs @@ -16,6 +16,7 @@ use crate::sync::status::get_user_status; use crate::util::error::ApiContext as _; use crate::util::error::Context as _; use actix_web::{HttpRequest, HttpResponse, delete, get, post, web}; +use anyhow::anyhow; use ariadne::networking::message::ServerToClientMessage; use chrono::Utc; use xredis::RedisPool; @@ -45,29 +46,29 @@ pub async fn add_friend( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let string = info.into_inner().0; let Some(friend) = DBUser::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? + .internal_context("fetching user from database")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; if DBBlockedUser::is_blocked(friend.id, user.id.into(), &**pool) .await - .wrap_internal_err("checking whether target user blocked requester")? + .internal_context("checking whether target user blocked requester")? { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You've been blocked the other user!", ))); } else if DBBlockedUser::is_blocked(user.id.into(), friend.id, &**pool) .await - .wrap_internal_err("checking whether requester blocked target user")? + .internal_context("checking whether requester blocked target user")? { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You've blocked the other user!", ))); } @@ -75,21 +76,21 @@ pub async fn add_friend( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(friend) = DBFriend::get_friend(user.id.into(), friend.id, &**pool) .await - .wrap_internal_err("fetching friend from database")? + .internal_context("fetching friend from database")? { if friend.accepted { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You are already friends with this user!", ))); } if !friend.accepted && user.id != friend.friend_id.into() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot accept your own friend request!", ))); } @@ -101,7 +102,7 @@ pub async fn add_friend( &mut transaction, ) .await - .wrap_internal_err("updating friend in database")?; + .internal_context("updating friend in database")?; async fn send_friend_status( user_id: DBUserId, @@ -120,7 +121,7 @@ pub async fn add_friend( }, ) .await - .wrap_internal_err("updating friend in database")?; + .internal_context("updating friend in database")?; } Ok(()) @@ -128,19 +129,19 @@ pub async fn add_friend( send_friend_status(friend.user_id, friend.friend_id, &db, &redis) .await - .wrap_api_err("executing `send_friend_status`")?; + .api_context("executing `send_friend_status`")?; send_friend_status(friend.friend_id, friend.user_id, &db, &redis) .await - .wrap_api_err("executing `send_friend_status`")?; + .api_context("executing `send_friend_status`")?; } else { if friend.id == user.id.into() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot add yourself as a friend!", ))); } if !friend.allow_friend_requests { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Friend requests are disabled for this user!", ))); } @@ -153,7 +154,7 @@ pub async fn add_friend( } .insert(&mut transaction) .await - .wrap_internal_err( + .internal_context( "inserting database records for `send_friend_status`", )?; @@ -163,7 +164,7 @@ pub async fn add_friend( &ServerToClientMessage::FriendRequest { from: user.id }, ) .await - .wrap_internal_err( + .internal_context( "inserting database records for `send_friend_status`", )?; } @@ -171,7 +172,7 @@ pub async fn add_friend( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } @@ -195,23 +196,23 @@ pub async fn remove_friend( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let string = info.into_inner().0; let friend = DBUser::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(friend) = friend { let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; DBFriend::remove(user.id.into(), friend.id, &mut transaction) .await - .wrap_internal_err("deleting friend from database")?; + .internal_context("deleting friend from database")?; send_message_to_user( &db, @@ -219,16 +220,16 @@ pub async fn remove_friend( &ServerToClientMessage::FriendRequestRejected { from: user.id }, ) .await - .wrap_internal_err("deleting friend from database")?; + .internal_context("deleting friend from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -249,12 +250,12 @@ pub async fn friends( Scopes::USER_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let friends = DBFriend::get_user_friends(user.id.into(), None, &***pool) .await - .wrap_internal_err("fetching friends from database")? + .internal_context("fetching friends from database")? .into_iter() .map(UserFriend::from) .collect::>(); diff --git a/apps/labrinth/src/routes/v3/images.rs b/apps/labrinth/src/routes/v3/images.rs index 8b5fb65f712..30a242c8fb6 100644 --- a/apps/labrinth/src/routes/v3/images.rs +++ b/apps/labrinth/src/routes/v3/images.rs @@ -17,6 +17,7 @@ use crate::util::error::Context as _; use crate::util::img::upload_image_optimized; use crate::util::routes::read_limited_from_payload; use actix_web::{HttpRequest, HttpResponse, post, web}; +use anyhow::anyhow; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -88,7 +89,7 @@ pub async fn images_add( context.relevant_scope(), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; // Attempt to associated a supplied id with the context // If the context cannot be found, or the user is not authorized to upload images for the context, return an error @@ -98,7 +99,7 @@ pub async fn images_add( let project = project_item::DBProject::get(&id, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; if let Some(project) = project { if is_team_member_project( &project.inner, @@ -106,16 +107,16 @@ pub async fn images_add( &pool, ) .await - .wrap_api_err("checking team member project")? + .api_context("checking team member project")? { *project_id = Some(project.inner.id.into()); } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You are not authorized to upload images for this project", ))); } } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The project could not be found.", ))); } @@ -126,7 +127,7 @@ pub async fn images_add( let version = version_item::DBVersion::get(id.into(), &**pool, &redis) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(version) = version { if is_team_member_version( &version.inner, @@ -136,16 +137,16 @@ pub async fn images_add( &redis, ) .await - .wrap_api_err("checking team member version")? + .api_context("checking team member version")? { *version_id = Some(version.inner.id.into()); } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You are not authorized to upload images for this version", ))); } } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The version could not be found.", ))); } @@ -156,15 +157,15 @@ pub async fn images_add( let thread_message = thread_item::DBThreadMessage::get(id.into(), &**pool) .await - .wrap_internal_err( + .internal_context( "fetching thread message from database", )? - .wrap_request_err_with(|| { + .request_context_with(|| { "the thread message could not found.".to_string() })?; let thread = thread_item::DBThread::get(thread_message.thread_id, &**pool) - .await.wrap_internal_err("fetching thread from database")? - .wrap_request_err_with(|| "the thread associated with the thread message could not be found" + .await.internal_context("fetching thread from database")? + .request_context_with(|| "the thread associated with the thread message could not be found" .to_string())?; if is_authorized_thread( &thread, @@ -173,11 +174,11 @@ pub async fn images_add( &pool, ) .await - .wrap_api_err("checking thread authorization")? + .api_context("checking thread authorization")? { *thread_message_id = Some(thread_message.id.into()); } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You are not authorized to upload images for this thread message", ))); } @@ -187,8 +188,8 @@ pub async fn images_add( if let Some(id) = data.report_id { let report = report_item::DBReport::get(id.into(), &**pool) .await - .wrap_internal_err("fetching report from database")? - .wrap_request_err_with(|| { + .internal_context("fetching report from database")? + .request_context_with(|| { "the report could not be found.".to_string() })?; let thread = thread_item::DBThread::get( @@ -196,8 +197,8 @@ pub async fn images_add( &**pool, ) .await - .wrap_internal_err("fetching thread from database")? - .wrap_request_err_with(|| { + .internal_context("fetching thread from database")? + .request_context_with(|| { "the thread associated with the report could not be found." .to_string() })?; @@ -208,18 +209,18 @@ pub async fn images_add( &pool, ) .await - .wrap_api_err("checking thread authorization")? + .api_context("checking thread authorization")? { *report_id = Some(report.id.into()); } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You are not authorized to upload images for this report", ))); } } } ImageContext::Unknown => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Context must be one of: project, version, thread_message, report", ))); } @@ -244,17 +245,17 @@ pub async fn images_add( &**file_host, ) .await - .wrap_api_err("uploading image")?; + .api_context("uploading image")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let db_image: database::models::DBImage = database::models::DBImage { id: database::models::generate_image_id(&mut transaction) .await - .wrap_internal_err("generating image ID")?, + .internal_context("generating image ID")?, url: upload_result.url, raw_url: upload_result.raw_url, size: content_length as u64, @@ -299,7 +300,7 @@ pub async fn images_add( db_image .insert(&mut transaction) .await - .wrap_internal_err("inserting database records for `images_add`")?; + .internal_context("inserting database records for `images_add`")?; let image = Image { id: db_image.id.into(), @@ -313,7 +314,7 @@ pub async fn images_add( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().json(image)) } diff --git a/apps/labrinth/src/routes/v3/limits.rs b/apps/labrinth/src/routes/v3/limits.rs index 74b7222ae1a..aff900325d1 100644 --- a/apps/labrinth/src/routes/v3/limits.rs +++ b/apps/labrinth/src/routes/v3/limits.rs @@ -31,11 +31,11 @@ pub async fn get_project_limits( Scopes::empty(), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let limits = UserLimits::get_for_projects(&user, &pool) .await - .wrap_internal_err("fetching user limits from Redis")?; + .internal_context("fetching user limits from Redis")?; Ok(web::Json(limits)) } @@ -55,11 +55,11 @@ pub async fn get_organization_limits( Scopes::empty(), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let limits = UserLimits::get_for_organizations(&user, &pool) .await - .wrap_internal_err("fetching user limits from Redis")?; + .internal_context("fetching user limits from Redis")?; Ok(web::Json(limits)) } @@ -79,10 +79,10 @@ pub async fn get_collection_limits( Scopes::empty(), ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let limits = UserLimits::get_for_collections(&user, &pool) .await - .wrap_internal_err("fetching user limits from Redis")?; + .internal_context("fetching user limits from Redis")?; Ok(web::Json(limits)) } diff --git a/apps/labrinth/src/routes/v3/notifications.rs b/apps/labrinth/src/routes/v3/notifications.rs index e532f38a2f1..48c1cf0875f 100644 --- a/apps/labrinth/src/routes/v3/notifications.rs +++ b/apps/labrinth/src/routes/v3/notifications.rs @@ -8,6 +8,7 @@ use crate::queue::session::AuthQueue; use crate::routes::ApiError; use crate::util::error::Context as _; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, web}; +use anyhow::anyhow; use serde::{Deserialize, Serialize}; use xredis::RedisPool; @@ -56,14 +57,14 @@ pub async fn notifications_get( Scopes::NOTIFICATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; use database::models::DBNotificationId; use database::models::notification_item::DBNotification; let notification_ids: Vec = serde_json::from_str::>(ids.ids.as_str()) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(DBNotificationId::from) .collect(); @@ -74,7 +75,7 @@ pub async fn notifications_get( &**pool, ) .await - .wrap_internal_err("fetching notifications from database")?; + .internal_context("fetching notifications from database")?; let notifications: Vec = notifications_data .into_iter() @@ -114,7 +115,7 @@ pub async fn notification_get( Scopes::NOTIFICATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id = info.into_inner().0; @@ -124,17 +125,17 @@ pub async fn notification_get( &**pool, ) .await - .wrap_internal_err("fetching notification from database")?; + .internal_context("fetching notification from database")?; if let Some(data) = notification_data { if user.id == data.user_id.into() || scopes.contains(Scopes::ADMIN_READ) { Ok(HttpResponse::Ok().json(Notification::from(data))) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -165,7 +166,7 @@ pub async fn notification_read( Scopes::NOTIFICATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id = info.into_inner().0; @@ -175,7 +176,7 @@ pub async fn notification_read( &**pool, ) .await - .wrap_internal_err("fetching notification from database")?; + .internal_context("fetching notification from database")?; if let Some(data) = notification_data { if data.user_id == user.id.into() @@ -184,7 +185,7 @@ pub async fn notification_read( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; database::models::notification_item::DBNotification::read( id.into(), @@ -192,21 +193,21 @@ pub async fn notification_read( &redis, ) .await - .wrap_internal_err("executing `DBNotification::read`")?; + .internal_context("executing `DBNotification::read`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( "You are not authorized to read this notification!", ))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -237,7 +238,7 @@ pub async fn notification_delete( Scopes::NOTIFICATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id = info.into_inner().0; @@ -247,7 +248,7 @@ pub async fn notification_delete( &**pool, ) .await - .wrap_internal_err("fetching notification from database")?; + .internal_context("fetching notification from database")?; if let Some(data) = notification_data { if data.user_id == user.id.into() @@ -256,7 +257,7 @@ pub async fn notification_delete( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; database::models::notification_item::DBNotification::remove( id.into(), @@ -264,21 +265,21 @@ pub async fn notification_delete( &redis, ) .await - .wrap_internal_err("deleting notification from database")?; + .internal_context("deleting notification from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( "You are not authorized to delete this notification!", ))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -313,11 +314,11 @@ pub async fn notifications_read( Scopes::NOTIFICATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let notification_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(|x| x.into()) .collect::>(); @@ -325,7 +326,7 @@ pub async fn notifications_read( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let notifications_data = database::models::notification_item::DBNotification::get_many( @@ -333,7 +334,7 @@ pub async fn notifications_read( &**pool, ) .await - .wrap_internal_err("fetching notifications from database")?; + .internal_context("fetching notifications from database")?; let mut notifications: Vec = Vec::new(); @@ -352,12 +353,12 @@ pub async fn notifications_read( &redis, ) .await - .wrap_internal_err("marking notifications as read")?; + .internal_context("marking notifications as read")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } @@ -393,11 +394,11 @@ pub async fn notifications_delete( Scopes::NOTIFICATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let notification_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(|x| x.into()) .collect::>(); @@ -405,7 +406,7 @@ pub async fn notifications_delete( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let notifications_data = database::models::notification_item::DBNotification::get_many( @@ -413,7 +414,7 @@ pub async fn notifications_delete( &**pool, ) .await - .wrap_internal_err("fetching notifications from database")?; + .internal_context("fetching notifications from database")?; let mut notifications: Vec = Vec::new(); @@ -432,12 +433,12 @@ pub async fn notifications_delete( &redis, ) .await - .wrap_internal_err("deleting notifications from database")?; + .internal_context("deleting notifications from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } diff --git a/apps/labrinth/src/routes/v3/oauth_clients.rs b/apps/labrinth/src/routes/v3/oauth_clients.rs index c5816eb8c31..d39d061e766 100644 --- a/apps/labrinth/src/routes/v3/oauth_clients.rs +++ b/apps/labrinth/src/routes/v3/oauth_clients.rs @@ -1,6 +1,7 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context as _; -use eyre::Result; +use anyhow::Result; +use anyhow::anyhow; use std::{collections::HashSet, fmt::Display}; use xredis::RedisPool; @@ -76,17 +77,17 @@ pub async fn get_user_clients( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let target_user = DBUser::get(&info.into_inner(), &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(target_user) = target_user { if target_user.id != current_user.user.id.into() && !current_user.scopes.contains(Scopes::ADMIN_READ) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to see the OAuth clients of this user!", ))); } @@ -94,7 +95,7 @@ pub async fn get_user_clients( let clients = DBOAuthClient::get_all_user_clients(target_user.id, &**pool) .await - .wrap_internal_err("fetching OAuth clients from database")?; + .internal_context("fetching OAuth clients from database")?; let response = clients .into_iter() @@ -103,7 +104,7 @@ pub async fn get_user_clients( Ok(HttpResponse::Ok().json(response)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -121,11 +122,11 @@ pub async fn get_client( ) -> Result { let clients = get_clients_inner(&[id.into_inner()], pool) .await - .wrap_api_err("fetching OAuth client")?; + .api_context("fetching OAuth client")?; if let Some(client) = clients.into_iter().next() { Ok(HttpResponse::Ok().json(client)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -146,11 +147,11 @@ pub async fn get_clients( .iter() .map(|id| parse_base62(id).map(OAuthClientId)) .collect::>() - .wrap_request_err("parsing OAuth client IDs")?; + .request_context("parsing OAuth client IDs")?; let clients = get_clients_inner(&ids, pool) .await - .wrap_api_err("fetching clients inner")?; + .api_context("fetching clients inner")?; Ok(HttpResponse::Ok().json(clients)) } @@ -269,22 +270,22 @@ pub async fn oauth_client_delete( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let client = DBOAuthClient::get(client_id.into_inner().into(), &**pool) .await - .wrap_internal_err("fetching OAuth client from database")?; + .internal_context("fetching OAuth client from database")?; if let Some(client) = client { client .validate_authorized(Some(¤t_user)) - .wrap_api_err("validating authorized")?; + .api_context("validating authorized")?; DBOAuthClient::remove(client.id, &**pool) .await - .wrap_internal_err("validating oauth client")?; + .internal_context("validating oauth client")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -338,21 +339,21 @@ pub async fn oauth_client_edit( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; client_updates .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; if let Some(existing_client) = DBOAuthClient::get(client_id.into_inner().into(), &**pool) .await - .wrap_internal_err("fetching OAuth client from database")? + .internal_context("fetching OAuth client from database")? { existing_client .validate_authorized(Some(¤t_user)) - .wrap_api_err("authorizing OAuth client update")?; + .api_context("authorizing OAuth client update")?; let mut updated_client = existing_client.clone(); let OAuthClientEdit { @@ -381,28 +382,28 @@ pub async fn oauth_client_edit( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; updated_client .update_editable_fields(&mut transaction) .await - .wrap_internal_err( + .internal_context( "updating database records for `oauth_client_edit`", )?; if let Some(redirects) = redirect_uris { edit_redirects(redirects, &existing_client, &mut transaction) .await - .wrap_internal_err("updating redirects in database")?; + .internal_context("updating redirects in database")?; } transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -442,18 +443,18 @@ pub async fn oauth_client_icon_edit( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let client = DBOAuthClient::get((*client_id).into(), &**pool) .await - .wrap_internal_err("fetching OAuth client from database")? - .wrap_request_err_with(|| { + .internal_context("fetching OAuth client from database")? + .request_context_with(|| { "the specified client does not exist!".to_string() })?; client .validate_authorized(Some(&user)) - .wrap_api_err("validating authorized")?; + .api_context("validating authorized")?; delete_old_images( client.icon_url.clone(), @@ -462,7 +463,7 @@ pub async fn oauth_client_icon_edit( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; let bytes = read_limited_from_payload( &mut payload, @@ -486,12 +487,12 @@ pub async fn oauth_client_icon_edit( &**file_host, ) .await - .wrap_api_err("uploading image")?; + .api_context("uploading image")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut editable_client = client.clone(); editable_client.icon_url = Some(upload_result.url); @@ -500,14 +501,14 @@ pub async fn oauth_client_icon_edit( editable_client .update_editable_fields(&mut transaction) .await - .wrap_internal_err( + .internal_context( "updating database records for `oauth_client_icon_edit`", )?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } @@ -536,17 +537,17 @@ pub async fn oauth_client_icon_delete( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let client = DBOAuthClient::get((*client_id).into(), &**pool) .await - .wrap_internal_err("fetching OAuth client from database")? - .wrap_request_err_with(|| { + .internal_context("fetching OAuth client from database")? + .request_context_with(|| { "the specified client does not exist!".to_string() })?; client .validate_authorized(Some(&user)) - .wrap_api_err("validating authorized")?; + .api_context("validating authorized")?; delete_old_images( client.icon_url.clone(), @@ -555,12 +556,12 @@ pub async fn oauth_client_icon_delete( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut editable_client = client.clone(); editable_client.icon_url = None; @@ -569,13 +570,13 @@ pub async fn oauth_client_icon_delete( editable_client .update_editable_fields(&mut transaction) .await - .wrap_internal_err( + .internal_context( "updating database records for `oauth_client_icon_delete`", )?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } @@ -601,14 +602,14 @@ pub async fn get_user_oauth_authorizations( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let authorizations = DBOAuthClientAuthorization::get_all_for_user( current_user.user.id.into(), &**pool, ) .await - .wrap_internal_err("fetching OAuth client authorizations from database")?; + .internal_context("fetching OAuth client authorizations from database")?; let mapped: Vec = authorizations.into_iter().map(|a| a.into()).collect_vec(); @@ -639,7 +640,7 @@ pub async fn revoke_oauth_authorization( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; DBOAuthClientAuthorization::remove( info.client_id.into(), @@ -647,7 +648,7 @@ pub async fn revoke_oauth_authorization( &**pool, ) .await - .wrap_internal_err("deleting oauth client authorization from database")?; + .internal_context("deleting oauth client authorization from database")?; Ok(HttpResponse::Ok().body("")) } @@ -669,7 +670,7 @@ async fn create_redirect_uris( for uri in uri_strings.into_iter() { let id = generate_oauth_redirect_id(transaction) .await - .wrap_err("generating OAuth redirect URI ID")?; + .context("generating OAuth redirect URI ID")?; redirect_uris.push(DBOAuthRedirectUri { id, client_id, @@ -698,10 +699,10 @@ async fn edit_redirects( &mut *transaction, ) .await - .wrap_err("creating OAuth redirect URIs")?; + .context("creating OAuth redirect URIs")?; DBOAuthClient::insert_redirect_uris(&redirects_to_add, &mut *transaction) .await - .wrap_err("inserting OAuth redirect URIs")?; + .context("inserting OAuth redirect URIs")?; let mut redirects_to_remove = existing_client.redirect_uris.clone(); redirects_to_remove.retain(|r| !updated_redirects.contains(&r.uri)); @@ -710,7 +711,7 @@ async fn edit_redirects( &mut *transaction, ) .await - .wrap_err("removing OAuth redirect URIs")?; + .context("removing OAuth redirect URIs")?; Ok(()) } @@ -722,7 +723,7 @@ pub async fn get_clients_inner( let ids: Vec = ids.iter().map(|i| (*i).into()).collect(); let clients = DBOAuthClient::get_many(&ids, &**pool) .await - .wrap_internal_err("fetching OAuth clients from database")?; + .internal_context("fetching OAuth clients from database")?; Ok(clients.into_iter().map(|c| c.into()).collect_vec()) } diff --git a/apps/labrinth/src/routes/v3/organizations.rs b/apps/labrinth/src/routes/v3/organizations.rs index 381fc99c813..8dfe74d301c 100644 --- a/apps/labrinth/src/routes/v3/organizations.rs +++ b/apps/labrinth/src/routes/v3/organizations.rs @@ -1,4 +1,5 @@ use crate::util::error::ApiContext as _; +use anyhow::anyhow; use std::collections::HashMap; use super::ApiError; @@ -69,11 +70,11 @@ pub async fn organization_projects_get( let organization_data = DBOrganization::get(&id, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; if let Some(organization) = organization_data && is_visible_organization(&organization, ¤t_user, &pool, &redis) .await - .wrap_api_err("checking organization visibility")? + .api_context("checking organization visibility")? { let project_ids = sqlx::query!( " @@ -87,7 +88,7 @@ pub async fn organization_projects_get( .map_ok(|m| database::models::DBProjectId(m.id)) .try_collect::>() .await - .wrap_internal_err("fetching project IDs from database")?; + .internal_context("fetching project IDs from database")?; let projects_data = crate::database::models::DBProject::get_many_ids( &project_ids, @@ -95,16 +96,16 @@ pub async fn organization_projects_get( &redis, ) .await - .wrap_internal_err("fetching organization projects")?; + .internal_context("fetching organization projects")?; let projects = filter_visible_projects(projects_data, ¤t_user, &pool, true) .await - .wrap_api_err("filtering visible projects")?; + .api_context("filtering visible projects")?; Ok(HttpResponse::Ok().json(projects)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -250,16 +251,16 @@ pub async fn organization_get( let organization_data = DBOrganization::get(&id, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; if let Some(data) = organization_data && is_visible_organization(&data, ¤t_user, &pool, &redis) .await - .wrap_api_err("checking organization visibility")? + .api_context("checking organization visibility")? { let members_data = DBTeamMember::get_from_team_full(data.team_id, &**pool, &redis) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = crate::database::models::DBUser::get_many_ids( &members_data.iter().map(|x| x.user_id).collect::>(), @@ -267,7 +268,7 @@ pub async fn organization_get( &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let logged_in = current_user .as_ref() .and_then(|user| { @@ -308,12 +309,12 @@ pub async fn organization_get( &redis, ) .await - .wrap_internal_err("fetching moderation note from database")?; + .internal_context("fetching moderation note from database")?; organization.moderation_notes = Some(note.map(Into::into)); } return Ok(HttpResponse::Ok().json(organization)); } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } #[utoipa::path(tag = "organizations", responses((status = NO_CONTENT)))] @@ -334,33 +335,33 @@ pub async fn organization_notes_edit( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to edit moderation notes", ))); } new_note .validate_not_empty() - .wrap_api_err("validating not empty")?; + .api_context("validating not empty")?; let expected_version = crate::models::moderation_notes::parse_if_match_header(&req) - .wrap_api_err( + .api_context( "executing `moderation_notes::parse_if_match_header`", )?; let organization = DBOrganization::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching organization from database")? + .not_found_context("resource not found")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(expected) = expected_version { let updated = DBModerationNote::update( None, @@ -372,10 +373,10 @@ pub async fn organization_notes_edit( &mut transaction, ) .await - .wrap_internal_err("updating moderation note in database")?; + .internal_context("updating moderation note in database")?; if updated.is_none() { - return Err(ApiError::PreconditionFailed(eyre::eyre!( + return Err(ApiError::PreconditionFailed(anyhow!( "moderation note version does not match", ))); } @@ -389,10 +390,10 @@ pub async fn organization_notes_edit( &mut transaction, ) .await - .wrap_internal_err("inserting moderation note into database")?; + .internal_context("inserting moderation note into database")?; if updated.is_none() { - return Err(ApiError::PreconditionRequired(eyre::eyre!( + return Err(ApiError::PreconditionRequired(anyhow!( "moderation note version does not match", ))); } @@ -401,10 +402,10 @@ pub async fn organization_notes_edit( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBModerationNote::clear_organization_cache(organization.id, &redis) .await - .wrap_internal_err("clearing cached moderation note in Redis")?; + .internal_context("clearing cached moderation note in Redis")?; Ok(HttpResponse::NoContent().finish()) } @@ -428,10 +429,10 @@ pub async fn organizations_get( session_queue: web::Data, ) -> Result { let ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; let organizations_data = DBOrganization::get_many(&ids, &**pool, &redis) .await - .wrap_internal_err("fetching organizations from database")?; + .internal_context("fetching organizations from database")?; let team_ids = organizations_data .iter() .map(|x| x.team_id) @@ -440,14 +441,14 @@ pub async fn organizations_get( let teams_data = DBTeamMember::get_from_team_full_many(&team_ids, &**pool, &redis) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = crate::database::models::DBUser::get_many_ids( &teams_data.iter().map(|x| x.user_id).collect::>(), &**pool, &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let current_user = get_user_from_headers( &req, @@ -469,7 +470,7 @@ pub async fn organizations_get( &redis, ) .await - .wrap_internal_err("fetching moderation notes from database")? + .internal_context("fetching moderation notes from database")? } else { HashMap::new() }; @@ -484,7 +485,7 @@ pub async fn organizations_get( for data in organizations_data { if !is_visible_organization(&data, ¤t_user, &pool, &redis) .await - .wrap_api_err("checking organization visibility")? + .api_context("checking organization visibility")? { continue; } @@ -563,18 +564,18 @@ pub async fn organizations_edit( Scopes::ORGANIZATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; new_organization .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let string = info.into_inner().0; let result = database::models::DBOrganization::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; if let Some(organization_item) = result { let id = organization_item.id; @@ -584,7 +585,7 @@ pub async fn organizations_edit( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; let permissions = OrganizationPermissions::get_permissions_by_scopes( user.scopes, @@ -595,10 +596,10 @@ pub async fn organizations_edit( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(description) = &new_organization.description { if !perms.contains(OrganizationPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the description of this organization!", ))); } @@ -613,14 +614,14 @@ pub async fn organizations_edit( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organizations_edit`", )?; } if let Some(name) = &new_organization.name { if !perms.contains(OrganizationPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the name of this organization!", ))); } @@ -635,14 +636,14 @@ pub async fn organizations_edit( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organizations_edit`", )?; } if let Some(slug) = &new_organization.slug { if !perms.contains(OrganizationPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit this organization's URL!", ))); } @@ -653,9 +654,9 @@ pub async fn organizations_edit( &redis, ) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; if existing.is_some() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Your URL is already being used by another organization!", ))); } @@ -676,12 +677,12 @@ pub async fn organizations_edit( ) .fetch_one(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organizations_edit`", )?; if results.exists.unwrap_or(true) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Your URL is already being used by another organization!", ))); } @@ -698,7 +699,7 @@ pub async fn organizations_edit( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organizations_edit`", )?; } @@ -706,23 +707,23 @@ pub async fn organizations_edit( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::DBOrganization::clear_cache( organization_item.id, Some(organization_item.slug), &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( "You do not have permission to edit this organization!", ))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -744,14 +745,14 @@ pub async fn organization_delete( Scopes::ORGANIZATION_DELETE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let organization = database::models::DBOrganization::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")? - .wrap_request_err_with(|| { + .internal_context("fetching organization from database")? + .request_context_with(|| { "the specified organization does not exist!".to_string() })?; @@ -764,8 +765,8 @@ pub async fn organization_delete( &**pool, ) .await - .wrap_internal_err("fetching organization team member")? - .wrap_request_err_with(|| { + .internal_context("fetching organization team member")? + .request_context_with(|| { "the specified organization does not exist!".to_string() })?; @@ -776,7 +777,7 @@ pub async fn organization_delete( .unwrap_or_default(); if !permissions.contains(OrganizationPermissions::DELETE_ORGANIZATION) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to delete this organization!", ))); } @@ -791,14 +792,14 @@ pub async fn organization_delete( ) .fetch_one(&**pool) .await - .wrap_internal_err("fetching owner ID from database")? + .internal_context("fetching owner ID from database")? .user_id; let owner_id = database::models::ids::DBUserId(owner_id); let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; // Handle projects- every project that is in this organization needs to have its owner changed the organization owner // Now, no project should have an owner if it is in an organization, and also @@ -821,7 +822,7 @@ pub async fn organization_delete( }) .try_collect::>() .await - .wrap_internal_err("querying database for `organization_delete`")?; + .internal_context("querying database for `organization_delete`")?; let organization_project_teams = organization_projects .iter() .map(|(team_id, _)| *team_id) @@ -836,7 +837,7 @@ pub async fn organization_delete( &mut transaction, ) .await - .wrap_internal_err("fetching query results from database")?; + .internal_context("fetching query results from database")?; let member = DBTeamMember { id: new_id, team_id: *organization_project_team, @@ -849,7 +850,7 @@ pub async fn organization_delete( payouts_split: Decimal::ZERO, ordering: 0, }; - member.insert(&mut transaction).await.wrap_internal_err( + member.insert(&mut transaction).await.internal_context( "inserting database records for `organization_delete`", )?; } @@ -860,7 +861,7 @@ pub async fn organization_delete( &redis, ) .await - .wrap_internal_err("fetching query results from database")?; + .internal_context("fetching query results from database")?; super::projects::mutation::finalize_mutations( &organization_project_ids, @@ -877,12 +878,12 @@ pub async fn organization_delete( &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; for team_id in &organization_project_teams { database::models::DBTeamMember::clear_cache(*team_id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } for project_id in organization_project_ids { @@ -895,13 +896,13 @@ pub async fn organization_delete( if !organization_project_teams.is_empty() { database::models::DBUser::clear_project_cache(&[owner_id], &redis) .await - .wrap_internal_err("clearing cached user in Redis")?; + .internal_context("clearing cached user in Redis")?; } if result.is_some() { Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -929,13 +930,13 @@ pub async fn organization_projects_add( Scopes::PROJECT_WRITE | Scopes::ORGANIZATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let organization = database::models::DBOrganization::get(&info, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")? - .wrap_request_err_with(|| { + .internal_context("fetching organization from database")? + .request_context_with(|| { "the specified organization does not exist!".to_string() })?; @@ -953,12 +954,12 @@ pub async fn organization_projects_add( &redis, ) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; if project_item.inner.organization_id.is_some() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The specified project is already owned by an organization!", ))); } @@ -971,8 +972,8 @@ pub async fn organization_projects_add( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? - .wrap_request_err_with(|| { + .internal_context("fetching team member from database")? + .request_context_with(|| { "you are not a member of this project!".to_string() })?; let organization_team_member = @@ -983,8 +984,8 @@ pub async fn organization_projects_add( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? - .wrap_request_err_with(|| { + .internal_context("fetching team member from database")? + .request_context_with(|| { "you are not a member of this organization!".to_string() })?; @@ -992,7 +993,7 @@ pub async fn organization_projects_add( if !current_user.scopes.contains(Scopes::ADMIN_WRITE) && !project_team_member.is_owner { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You need to be an owner of a project to add it to an organization!", ))); } @@ -1006,7 +1007,7 @@ pub async fn organization_projects_add( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " UPDATE mods @@ -1018,7 +1019,7 @@ pub async fn organization_projects_add( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organization_projects_add`", )?; @@ -1037,7 +1038,7 @@ pub async fn organization_projects_add( ) .fetch_one(&mut transaction) .await - .wrap_internal_err( + .internal_context( "fetching organization owner user ID from database", )?; let organization_owner_user_id = @@ -1053,7 +1054,7 @@ pub async fn organization_projects_add( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organization_projects_add`", )?; @@ -1071,19 +1072,19 @@ pub async fn organization_projects_add( &redis, ) .await - .wrap_internal_err("clearing cached user in Redis")?; + .internal_context("clearing cached user in Redis")?; database::models::DBTeamMember::clear_cache( project_item.inner.team_id, &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; search_state .queue .push_project_change(project_item.inner.id.into()) .await; } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to add projects to this organization!", ))); } @@ -1130,7 +1131,7 @@ pub async fn organization_projects_remove( Scopes::PROJECT_WRITE | Scopes::ORGANIZATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let organization = database::models::DBOrganization::get( &organization_id, @@ -1138,16 +1139,16 @@ pub async fn organization_projects_remove( &redis, ) .await - .wrap_internal_err("fetching organization from database")? - .wrap_request_err_with(|| { + .internal_context("fetching organization from database")? + .request_context_with(|| { "the specified organization does not exist!".to_string() })?; let project_item = database::models::DBProject::get(&project_id, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; @@ -1156,7 +1157,7 @@ pub async fn organization_projects_remove( .organization_id .eq(&Some(organization.id)) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The specified project is not owned by this organization!", ))); } @@ -1169,8 +1170,8 @@ pub async fn organization_projects_remove( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? - .wrap_request_err_with(|| { + .internal_context("fetching team member from database")? + .request_context_with(|| { "you are not a member of this organization!".to_string() })?; @@ -1188,8 +1189,8 @@ pub async fn organization_projects_remove( &**pool, ) .await - .wrap_internal_err("deleting team member from database")? - .wrap_request_err_with(|| { + .internal_context("deleting team member from database")? + .request_context_with(|| { "the specified user is not a member of this organization!" .to_string() })?; @@ -1204,12 +1205,12 @@ pub async fn organization_projects_remove( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; // If the user is not a member of the project, we add them let new_owner = match new_owner { @@ -1220,7 +1221,7 @@ pub async fn organization_projects_remove( &mut transaction, ) .await - .wrap_internal_err("generating team member ID")?; + .internal_context("generating team member ID")?; let member = DBTeamMember { id: new_id, team_id: project_item.inner.team_id, @@ -1236,7 +1237,7 @@ pub async fn organization_projects_remove( member .insert(&mut transaction) .await - .wrap_internal_err("inserting database records for `organization_projects_remove`")?; + .internal_context("inserting database records for `organization_projects_remove`")?; member } }; @@ -1258,7 +1259,7 @@ pub async fn organization_projects_remove( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organization_projects_remove`", )?; @@ -1272,7 +1273,7 @@ pub async fn organization_projects_remove( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `organization_projects_remove`", )?; @@ -1289,19 +1290,19 @@ pub async fn organization_projects_remove( &redis, ) .await - .wrap_internal_err("clearing cached user in Redis")?; + .internal_context("clearing cached user in Redis")?; database::models::DBTeamMember::clear_cache( project_item.inner.team_id, &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; search_state .queue .push_project_change(project_item.inner.id.into()) .await; } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to add projects to this organization!", ))); } @@ -1339,14 +1340,14 @@ pub async fn organization_icon_edit( Scopes::ORGANIZATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let organization_item = database::models::DBOrganization::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")? - .wrap_request_err_with(|| { + .internal_context("fetching organization from database")? + .request_context_with(|| { "the specified organization does not exist!".to_string() })?; @@ -1357,7 +1358,7 @@ pub async fn organization_icon_edit( &**pool, ) .await - .wrap_internal_err("fetching organization team member")?; + .internal_context("fetching organization team member")?; let permissions = OrganizationPermissions::get_permissions_by_scopes( user.scopes, @@ -1366,7 +1367,7 @@ pub async fn organization_icon_edit( .unwrap_or_default(); if !permissions.contains(OrganizationPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this organization's icon.", ))); } @@ -1379,7 +1380,7 @@ pub async fn organization_icon_edit( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; let bytes = read_limited_from_payload( &mut payload, @@ -1405,12 +1406,12 @@ pub async fn organization_icon_edit( &**file_host, ) .await - .wrap_api_err("uploading image")?; + .api_context("uploading image")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -1425,19 +1426,19 @@ pub async fn organization_icon_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `organization_icon_edit`")?; + .internal_context("querying database for `organization_icon_edit`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::DBOrganization::clear_cache( organization_item.id, Some(organization_item.slug), &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } @@ -1460,14 +1461,14 @@ pub async fn delete_organization_icon( Scopes::ORGANIZATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let organization_item = database::models::DBOrganization::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")? - .wrap_request_err_with(|| { + .internal_context("fetching organization from database")? + .request_context_with(|| { "the specified organization does not exist!".to_string() })?; @@ -1478,7 +1479,7 @@ pub async fn delete_organization_icon( &**pool, ) .await - .wrap_internal_err("fetching organization team member")?; + .internal_context("fetching organization team member")?; let permissions = OrganizationPermissions::get_permissions_by_scopes( user.scopes, @@ -1487,7 +1488,7 @@ pub async fn delete_organization_icon( .unwrap_or_default(); if !permissions.contains(OrganizationPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this organization's icon.", ))); } @@ -1500,12 +1501,12 @@ pub async fn delete_organization_icon( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -1517,12 +1518,12 @@ pub async fn delete_organization_icon( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `delete_organization_icon`")?; + .internal_context("querying database for `delete_organization_icon`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; database::models::DBOrganization::clear_cache( organization_item.id, @@ -1530,7 +1531,7 @@ pub async fn delete_organization_icon( &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } diff --git a/apps/labrinth/src/routes/v3/payouts.rs b/apps/labrinth/src/routes/v3/payouts.rs index 57ab1b93028..4a867258711 100644 --- a/apps/labrinth/src/routes/v3/payouts.rs +++ b/apps/labrinth/src/routes/v3/payouts.rs @@ -18,6 +18,7 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context; use crate::util::gotenberg::GotenbergClient; use actix_web::{HttpRequest, HttpResponse, delete, get, post, web}; +use anyhow::anyhow; use chrono::{DateTime, Duration, Utc}; use hex::ToHex; use hmac::{Hmac, KeyInit, Mac}; @@ -72,7 +73,7 @@ pub async fn post_compliance_form( Scopes::PAYOUTS_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let user_id = DBUserId(user.id.0 as i64); @@ -80,12 +81,12 @@ pub async fn post_compliance_form( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let maybe_compliance = users_compliance::UserCompliance::get_by_user_id(&mut txn, user_id) .await - .wrap_internal_err("fetching user compliance from Redis")?; + .internal_context("fetching user compliance from Redis")?; let mut compliance = match maybe_compliance { Some(c) => { @@ -93,7 +94,7 @@ pub async fn post_compliance_form( && c.form_type.is_some_and(|f| f.requires_domestic_tin_match()) && !c.tin_matched { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Your TIN/SSN did not match the IRS records. Please contact support https://support.modrinth.com".to_owned(), ))); } @@ -117,7 +118,7 @@ pub async fn post_compliance_form( let result = avalara1099::request_form(user_id, body.0.form_type) .await - .wrap_api_err("executing `avalara1099::request_form`")?; + .api_context("executing `avalara1099::request_form`")?; match result { Ok( @@ -143,17 +144,17 @@ pub async fn post_compliance_form( compliance .upsert_partial(&mut txn) .await - .wrap_internal_err("updating user compliance request")?; + .internal_context("updating user compliance request")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().json(toplevel)) } Ok(_) => { error!("Missing form request ID in Avalara response"); - Err(ApiError::Internal(eyre::eyre!("tax compliance API failed"))) + Err(ApiError::Internal(anyhow!("tax compliance API failed"))) } Err(json_error) => { @@ -161,7 +162,7 @@ pub async fn post_compliance_form( "Error sending request to Avalara: {}", serde_json::to_string_pretty(&json_error).unwrap() ); - Err(ApiError::Internal(eyre::eyre!("tax compliance API failed"))) + Err(ApiError::Internal(anyhow!("tax compliance API failed"))) } } } @@ -184,27 +185,27 @@ pub async fn paypal_webhook( .headers() .get("PAYPAL-AUTH-ALGO") .and_then(|x| x.to_str().ok()) - .wrap_request_err_with(|| "missing auth algo".to_string())?; + .request_context_with(|| "missing auth algo".to_string())?; let cert_url = req .headers() .get("PAYPAL-CERT-URL") .and_then(|x| x.to_str().ok()) - .wrap_request_err_with(|| "missing cert url".to_string())?; + .request_context_with(|| "missing cert url".to_string())?; let transmission_id = req .headers() .get("PAYPAL-TRANSMISSION-ID") .and_then(|x| x.to_str().ok()) - .wrap_request_err_with(|| "missing transmission ID".to_string())?; + .request_context_with(|| "missing transmission ID".to_string())?; let transmission_sig = req .headers() .get("PAYPAL-TRANSMISSION-SIG") .and_then(|x| x.to_str().ok()) - .wrap_request_err_with(|| "missing transmission sig".to_string())?; + .request_context_with(|| "missing transmission sig".to_string())?; let transmission_time = req .headers() .get("PAYPAL-TRANSMISSION-TIME") .and_then(|x| x.to_str().ok()) - .wrap_request_err_with(|| "missing transmission time".to_string())?; + .request_context_with(|| "missing transmission time".to_string())?; #[derive(Deserialize)] struct WebHookResponse { @@ -239,12 +240,10 @@ pub async fn paypal_webhook( ApiError::Request(report) => ApiError::Internal(report), error => error, }) - .wrap_api_err("verifying PayPal webhook signature")?; + .api_context("verifying PayPal webhook signature")?; if &webhook_res.verification_status != "SUCCESS" { - return Err(ApiError::Request(eyre::eyre!( - "Invalid webhook signature", - ))); + return Err(ApiError::Request(anyhow!("Invalid webhook signature",))); } #[derive(Deserialize)] @@ -259,7 +258,7 @@ pub async fn paypal_webhook( } let webhook = serde_json::from_str::(&body) - .wrap_internal_err("deserializing PayPal webhook JSON data")?; + .internal_context("deserializing PayPal webhook JSON data")?; match &*webhook.event_type { "PAYMENT.PAYOUTS-ITEM.BLOCKED" @@ -271,13 +270,13 @@ pub async fn paypal_webhook( .resource .payout_item_id .as_deref() - .wrap_internal_err( + .internal_context( "PayPal payout item webhook is missing `payout_item_id`", )?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let result = sqlx::query!( "SELECT user_id, amount, fee FROM payouts WHERE platform_id = $1 AND status = $2", @@ -285,7 +284,7 @@ pub async fn paypal_webhook( PayoutStatus::InTransit.as_str() ) .fetch_optional(&mut transaction) - .await.wrap_internal_err("querying database for `paypal_webhook`")?; + .await.internal_context("querying database for `paypal_webhook`")?; if let Some(result) = result { sqlx::query!( @@ -304,12 +303,12 @@ pub async fn paypal_webhook( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `paypal_webhook`")?; + .internal_context("querying database for `paypal_webhook`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::user_item::DBUser::clear_caches( &[( @@ -319,7 +318,7 @@ pub async fn paypal_webhook( &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } } "PAYMENT.PAYOUTS-ITEM.SUCCEEDED" => { @@ -327,13 +326,13 @@ pub async fn paypal_webhook( .resource .payout_item_id .as_deref() - .wrap_internal_err( + .internal_context( "PayPal payout item webhook is missing `payout_item_id`", )?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " UPDATE payouts @@ -345,11 +344,11 @@ pub async fn paypal_webhook( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `paypal_webhook`")?; + .internal_context("querying database for `paypal_webhook`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } _ => {} } @@ -375,21 +374,17 @@ pub async fn tremendous_webhook( .get("Tremendous-Webhook-Signature") .and_then(|x| x.to_str().ok()) .and_then(|x| x.split('=').next_back()) - .wrap_request_err_with(|| "missing webhook signature".to_string())?; + .request_context_with(|| "missing webhook signature".to_string())?; let mut mac: Hmac = Hmac::new_from_slice(ENV.TREMENDOUS_PRIVATE_KEY.as_bytes()) - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( - "error initializing HMAC".to_string(), - )?; + .map_err(|err| anyhow!(err)) + .failed_dependency_context("error initializing HMAC".to_string())?; mac.update(body.as_bytes()); let request_signature = mac.finalize().into_bytes().encode_hex::(); if &*request_signature != signature { - return Err(ApiError::Request(eyre::eyre!( - "Invalid webhook signature", - ))); + return Err(ApiError::Request(anyhow!("Invalid webhook signature",))); } #[derive(Deserialize)] @@ -409,14 +404,14 @@ pub async fn tremendous_webhook( } let webhook = serde_json::from_str::(&body) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; match &*webhook.event { "REWARDS.CANCELED" | "REWARDS.DELIVERY.FAILED" => { let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let result = sqlx::query!( "SELECT user_id, amount, fee FROM payouts WHERE platform_id = $1 AND status = $2", @@ -424,7 +419,7 @@ pub async fn tremendous_webhook( PayoutStatus::InTransit.as_str() ) .fetch_optional(&mut transaction) - .await.wrap_internal_err("querying database for `tremendous_webhook`")?; + .await.internal_context("querying database for `tremendous_webhook`")?; if let Some(result) = result { sqlx::query!( @@ -443,14 +438,14 @@ pub async fn tremendous_webhook( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `tremendous_webhook`", )?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; crate::database::models::user_item::DBUser::clear_caches( &[( @@ -460,14 +455,14 @@ pub async fn tremendous_webhook( &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } } "REWARDS.DELIVERY.SUCCEEDED" => { let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " UPDATE payouts @@ -479,11 +474,11 @@ pub async fn tremendous_webhook( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `tremendous_webhook`")?; + .internal_context("querying database for `tremendous_webhook`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } _ => {} } @@ -523,13 +518,13 @@ pub async fn calculate_fees( false, ) .await - .wrap_auth_err("authenticating API request")? - .wrap_auth_err_with(|| AuthenticationError::InvalidCredentials)?; + .auth_context("authenticating API request")? + .auth_context_with(|| AuthenticationError::InvalidCredentials)?; let payout_flow = payouts_queue .create_payout_flow(body.0) .await - .wrap_api_err("creating payout flow")?; + .api_context("creating payout flow")?; Ok(web::Json(WithdrawalFees { net_usd: payout_flow.net_usd, @@ -562,11 +557,11 @@ pub async fn create_payout( false, ) .await - .wrap_auth_err("authenticating API request")? - .wrap_auth_err_with(|| AuthenticationError::InvalidCredentials)?; + .auth_context("authenticating API request")? + .auth_context_with(|| AuthenticationError::InvalidCredentials)?; if !scopes.contains(Scopes::PAYOUTS_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials, ))); } @@ -574,7 +569,7 @@ pub async fn create_payout( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -584,16 +579,14 @@ pub async fn create_payout( ) .fetch_optional(&mut transaction) .await - .wrap_internal_err("failed to fetch user balance")?; + .internal_context("failed to fetch user balance")?; let balance = get_user_balance(user.id, &pool) .await - .wrap_internal_err("failed to calculate user balance")?; + .internal_context("failed to calculate user balance")?; if body.amount < Decimal::ZERO { - return Err(ApiError::Request( - eyre::eyre!("Amount must be positive!",), - )); + return Err(ApiError::Request(anyhow!("Amount must be positive!",))); } // Create the payout flow first so we can use the resolved USD amount @@ -603,7 +596,7 @@ pub async fn create_payout( let payout_flow = payouts_queue .create_payout_flow(body.0) .await - .wrap_api_err("creating payout flow")?; + .api_context("creating payout flow")?; let amount_usd = payout_flow.net_usd.get(); let requires_manual_review; @@ -611,7 +604,7 @@ pub async fn create_payout( if let Some(threshold) = tax_compliance_payout_threshold() { let maybe_compliance = update_compliance_status(&pool, user.id) .await - .wrap_api_err("updating compliance status")?; + .api_context("updating compliance status")?; let (tin_matched, signed, requested, api_check_failed) = match maybe_compliance { @@ -643,12 +636,12 @@ pub async fn create_payout( // error with the API, as this is more accurate than saying the form wasn't completed // properly as this might be wrong! if api_check_failed { - return Err(ApiError::Internal(eyre::eyre!( + return Err(ApiError::Internal(anyhow!( "tax compliance API failed" ))); } - return Err(ApiError::Request(eyre::eyre!(match (tin_matched, signed, requested) { + return Err(ApiError::Request(anyhow!(match (tin_matched, signed, requested) { (_, false, true) => "Tax form isn't signed yet!", (false, true, true) => "Tax form is signed, but the Tax Identification Number/SSN didn't match the IRS records. Withdrawals are blocked until the TIN/SSN matches.", _ => "Tax compliance form is required to withdraw more!", @@ -663,12 +656,12 @@ pub async fn create_payout( } else { users_compliance::UserCompliance::get_by_user_id(&**pool, user.id) .await - .wrap_internal_err("fetching user compliance from database")? + .internal_context("fetching user compliance from database")? .is_some_and(|x| x.requires_manual_review) }; if requires_manual_review { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "More information is required to proceed. Please contact support (https://support.modrinth.com, support@modrinth.com)", ))); } @@ -676,22 +669,22 @@ pub async fn create_payout( let payout_flow = match payout_flow.validate(balance.available) { Ok(flow) => flow, Err(err) => { - return Err(ApiError::Request(eyre::eyre!("{err}"))); + return Err(ApiError::Request(anyhow!("{err}"))); } }; let payout_id = generate_payout_id(&mut transaction) .await - .wrap_internal_err("failed to generate payout ID")?; + .internal_context("failed to generate payout ID")?; payout_flow .execute(&payouts_queue, &user, payout_id, transaction, &gotenberg) .await - .wrap_api_err("executing `execute`")?; + .api_context("executing `execute`")?; crate::database::models::DBUser::clear_caches(&[(user.id, None)], &redis) .await - .wrap_internal_err("failed to clear user caches")?; + .internal_context("failed to clear user caches")?; Ok(()) } @@ -789,7 +782,7 @@ pub async fn transaction_history( Scopes::PAYOUTS_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let payout_ids = @@ -798,13 +791,13 @@ pub async fn transaction_history( &**pool, ) .await - .wrap_internal_err("fetching payouts from database")?; + .internal_context("fetching payouts from database")?; let payouts = crate::database::models::payout_item::DBPayout::get_many( &payout_ids, &**pool, ) .await - .wrap_internal_err("fetching payouts from database")?; + .internal_context("fetching payouts from database")?; let withdrawals = payouts .into_iter() @@ -832,7 +825,7 @@ pub async fn transaction_history( .fetch(&**pool) .map(|record| { let record = record - .wrap_internal_err("failed to fetch available payout record")?; + .internal_context("failed to fetch available payout record")?; let amount = record.amount.unwrap_or_default(); if amount > Decimal::ZERO { Ok(Some(TransactionItem::PayoutAvailable { @@ -846,7 +839,7 @@ pub async fn transaction_history( }) .collect::, ApiError>>() .await - .wrap_internal_err("failed to fetch available payouts")? + .internal_context("failed to fetch available payouts")? .into_iter() .flatten() .collect::>(); @@ -881,13 +874,13 @@ pub async fn cancel_payout( Scopes::PAYOUTS_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id = info.into_inner().0; let payout = crate::database::models::payout_item::DBPayout::get(id.into(), &**pool) .await - .wrap_internal_err("fetching payout from database")?; + .internal_context("fetching payout from database")?; if let Some(payout) = payout { if payout.user_id != user.user.id.into() @@ -899,7 +892,7 @@ pub async fn cancel_payout( if let Some(platform_id) = payout.platform_id { if let Some(method) = payout.method { if payout.status != PayoutStatus::InTransit { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Payout cannot be cancelled!", ))); } @@ -917,7 +910,7 @@ pub async fn cancel_payout( None, ) .await - .wrap_api_err("cancelling PayPal payout")?; + .api_context("cancelling PayPal payout")?; } PayoutMethodType::Tremendous => { payouts @@ -927,16 +920,16 @@ pub async fn cancel_payout( None, ) .await - .wrap_api_err("cancelling Tremendous payout")?; + .api_context("cancelling Tremendous payout")?; } PayoutMethodType::MuralPay => { let payout_request_id = platform_id .parse::() - .wrap_request_err("invalid payout request ID")?; + .request_context("invalid payout request ID")?; payouts .cancel_mural_payout_request(payout_request_id) .await - .wrap_internal_err( + .internal_context( "failed to cancel payout request", )?; } @@ -945,7 +938,7 @@ pub async fn cancel_payout( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " UPDATE payouts @@ -957,22 +950,18 @@ pub async fn cancel_payout( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `cancel_payout`")?; + .internal_context("querying database for `cancel_payout`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().finish()) } else { - Err(ApiError::Request(eyre::eyre!( - "Payout cannot be cancelled!", - ))) + Err(ApiError::Request(anyhow!("Payout cannot be cancelled!",))) } } else { - Err(ApiError::Request(eyre::eyre!( - "Payout cannot be cancelled!", - ))) + Err(ApiError::Request(anyhow!("Payout cannot be cancelled!",))) } } else { Ok(HttpResponse::NotFound().finish()) @@ -1011,7 +1000,7 @@ pub async fn payment_methods( let methods = payouts_queue .get_payout_methods() .await - .wrap_api_err("fetching payout methods")? + .api_context("fetching payout methods")? .into_iter() .filter(|x| { let mut val = true; @@ -1065,12 +1054,12 @@ pub async fn get_balance( Scopes::PAYOUTS_READ, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let balance = get_user_balance(user.id.into(), &pool) .await - .wrap_api_err("fetching user balance")?; + .api_context("fetching user balance")?; let mut requested_form_type = None; let mut form_completion_status = None; @@ -1080,7 +1069,7 @@ pub async fn get_balance( form_completion_status = Some( update_compliance_status(&pool, user.id.into()) .await - .wrap_api_err("updating compliance status")? + .api_context("updating compliance status")? .filter(|x| x.model.form_type.is_some()) .map_or(FormCompletionStatus::Unrequested, |compliance| { requested_form_type = compliance.model.form_type; @@ -1127,7 +1116,7 @@ async fn get_user_balance( ) .fetch_all(pool) .await - .wrap_internal_err("fetching payouts from database")?; + .internal_context("fetching payouts from database")?; let available = payouts .iter() @@ -1150,7 +1139,7 @@ async fn get_user_balance( user_id.0 ) .fetch_optional(pool) - .await.wrap_internal_err("fetching withdrawn from database")?; + .await.internal_context("fetching withdrawn from database")?; let (withdrawn, fees, withdrawn_this_year) = withdrawn.map_or((Decimal::ZERO, Decimal::ZERO, Decimal::ZERO), |x| { @@ -1187,7 +1176,7 @@ async fn update_compliance_status( let maybe_compliance = users_compliance::UserCompliance::get_by_user_id(pg, user_id) .await - .wrap_internal_err("failed to fetch user tax compliance")?; + .internal_context("failed to fetch user tax compliance")?; let Some(mut compliance) = maybe_compliance else { return Ok(None); @@ -1205,7 +1194,7 @@ async fn update_compliance_status( } else { let result = avalara1099::check_form(&compliance.reference_id) .await - .wrap_internal_err("failed to check form using Track1099")?; + .internal_context("failed to check form using Track1099")?; let mut compliance_api_check_failed = false; compliance.last_checked = Utc::now(); @@ -1248,7 +1237,7 @@ async fn update_compliance_status( } } - compliance.update(pg).await.wrap_internal_err( + compliance.update(pg).await.internal_context( "updating database records for `update_compliance_status`", )?; @@ -1301,7 +1290,7 @@ pub async fn platform_revenue( ) .fetch_optional(&**pool) .await - .wrap_internal_err("fetching all time payouts from database")? + .internal_context("fetching all time payouts from database")? .and_then(|x| x.sum) .unwrap_or(Decimal::ZERO); @@ -1312,7 +1301,7 @@ pub async fn platform_revenue( ) .fetch_optional(&**pool) .await - .wrap_internal_err("fetching all available from database")? + .internal_context("fetching all available from database")? .and_then(|x| x.sum) .unwrap_or(Decimal::ZERO); @@ -1333,7 +1322,7 @@ pub async fn platform_revenue( ) .fetch_all(&**pool) .await - .wrap_internal_err("fetching revenue from database")? + .internal_context("fetching revenue from database")? .into_iter() .map(|x| RevenueData { time: x.created.timestamp() as u64, diff --git a/apps/labrinth/src/routes/v3/project_creation.rs b/apps/labrinth/src/routes/v3/project_creation.rs index e880286f595..f18dbc1ab2e 100644 --- a/apps/labrinth/src/routes/v3/project_creation.rs +++ b/apps/labrinth/src/routes/v3/project_creation.rs @@ -35,6 +35,7 @@ use actix_multipart::{Field, Multipart}; use actix_web::http::StatusCode; use actix_web::web::{self, Data}; use actix_web::{HttpRequest, HttpResponse, post}; +use anyhow::anyhow; use ariadne::ids::UserId; use ariadne::ids::base62_impl::to_base62; use chrono::Utc; @@ -61,7 +62,7 @@ pub enum CreateError { #[error(transparent)] Request(crate::routes::ApiError), #[error(transparent)] - InternalError(#[from] eyre::Report), + InternalError(#[from] anyhow::Error), #[error("An unknown database error occurred")] SqlxDatabaseError(#[from] sqlx::Error), #[error("Error while parsing multipart payload: {0}")] @@ -123,7 +124,7 @@ impl From for CreateError { Self::InvalidInput(format!("{err:#}")) } } - err => Self::InternalError(eyre::eyre!("{err:#}")), + err => Self::InternalError(anyhow!("{err:#}")), } } } diff --git a/apps/labrinth/src/routes/v3/project_creation/new.rs b/apps/labrinth/src/routes/v3/project_creation/new.rs index 9bedeed806f..a7d02ce6a8e 100644 --- a/apps/labrinth/src/routes/v3/project_creation/new.rs +++ b/apps/labrinth/src/routes/v3/project_creation/new.rs @@ -1,7 +1,7 @@ use actix_http::StatusCode; use actix_web::{HttpRequest, HttpResponse, ResponseError, put, web}; +use anyhow::anyhow; use chrono::Utc; -use eyre::eyre; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; use validator::Validate; @@ -150,13 +150,13 @@ pub async fn create( Scopes::PROJECT_CREATE, ) .await - .wrap_auth_err("authenticating project creator")?; + .auth_context("authenticating project creator")?; require_verified_email(&user.user)?; let limits = UserLimits::get_for_projects(&user, &db) .await - .wrap_internal_err("fetching project limits")?; + .internal_context("fetching project limits")?; if limits.current >= limits.max { return Err(CreateError::LimitReached); } @@ -164,7 +164,7 @@ pub async fn create( let daily_limits = UserLimits::get_for_projects_per_day(&user, Utc::now(), &db) .await - .wrap_internal_err("fetching daily project limits")?; + .internal_context("fetching daily project limits")?; if daily_limits.current >= daily_limits.max { return Err(CreateError::DailyProjectLimitReached); } @@ -200,7 +200,7 @@ pub async fn create( let mut txn = db .begin() .await - .wrap_internal_err("failed to begin transaction")?; + .internal_context("failed to begin transaction")?; let same_slug_record = sqlx::query!( "SELECT EXISTS( @@ -210,7 +210,7 @@ pub async fn create( ) .fetch_one(&mut txn) .await - .wrap_internal_err("failed to query if slug already exists")?; + .internal_context("failed to query if slug already exists")?; if same_slug_record.exists.unwrap_or(false) { return Err(CreateError::SlugCollision); @@ -221,8 +221,8 @@ pub async fn create( let team = if let Some(organization_id) = organization_id { let org = DBOrganization::get_id(organization_id.into(), &**db, &redis) .await - .wrap_internal_err("failed to get organization")? - .wrap_request_err("invalid organization ID")?; + .internal_context("failed to get organization")? + .request_context("invalid organization ID")?; let team_member = DBTeamMember::get_from_user_id( org.team_id, @@ -230,7 +230,7 @@ pub async fn create( &**db, ) .await - .wrap_internal_err( + .internal_context( "failed to get team member of user for organization", )?; @@ -242,7 +242,7 @@ pub async fn create( if !perms .is_some_and(|p| p.contains(OrganizationPermissions::ADD_PROJECT)) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "no permission to create projects in this organization" )) .into()); @@ -268,11 +268,11 @@ pub async fn create( let team_id = team .insert(&mut txn) .await - .wrap_internal_err("failed to insert team")?; + .internal_context("failed to insert team")?; let project_id: ProjectId = models::generate_project_id(&mut txn) .await - .wrap_internal_err("failed to generate project ID")? + .internal_context("failed to generate project ID")? .into(); // TODO: special casing certain components @@ -286,7 +286,7 @@ pub async fn create( &db, ) .await - .wrap_internal_err("fetching project version limits")?; + .internal_context("fetching project version limits")?; if version_limits.current >= version_limits.max { return Err(CreateError::ProjectVersionLimitReached); } @@ -301,7 +301,7 @@ pub async fn create( // so we generate a synthetic initial version. let version_id = models::generate_version_id(&mut txn) .await - .wrap_internal_err("failed to generate project ID")?; + .internal_context("failed to generate project ID")?; version_builder = Some(VersionBuilder { version_id, project_id: project_id.into(), @@ -344,25 +344,25 @@ pub async fn create( monetization_status, components: components .create() - .wrap_request_err("failed to create components")?, + .request_context("failed to create components")?, }; let mut delphi_scan_files = Vec::new(); project_builder .insert(&mut txn, &redis, &**file_host, &mut delphi_scan_files) .await - .wrap_internal_err("failed to insert project")?; + .internal_context("failed to insert project")?; if let Some(version_builder) = version_builder { version_builder .insert(&mut txn, &redis, &**file_host, &mut delphi_scan_files) .await - .wrap_internal_err("failed to insert initial version")?; + .internal_context("failed to insert initial version")?; } DBUser::clear_project_cache(&[user.user.id.into()], &redis) .await - .wrap_internal_err("failed to clear user project cache")?; + .internal_context("failed to clear user project cache")?; ThreadBuilder { type_: ThreadType::Project, @@ -372,7 +372,7 @@ pub async fn create( } .insert(&mut txn) .await - .wrap_internal_err("failed to insert thread")?; + .internal_context("failed to insert thread")?; super::super::projects::mutation::finalize_mutation( project_id.into(), diff --git a/apps/labrinth/src/routes/v3/projects/mod.rs b/apps/labrinth/src/routes/v3/projects/mod.rs index 763b8e2add6..f4060d77cf7 100644 --- a/apps/labrinth/src/routes/v3/projects/mod.rs +++ b/apps/labrinth/src/routes/v3/projects/mod.rs @@ -45,8 +45,8 @@ use crate::util::img; use crate::util::img::{delete_old_images, upload_image_optimized}; use crate::util::routes::read_limited_from_payload; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, post, web}; +use anyhow::anyhow; use chrono::Utc; -use eyre::eyre; use futures::TryStreamExt; use itertools::Itertools; use rand::seq::SliceRandom; @@ -106,7 +106,7 @@ pub async fn clear_project_cache_and_queue_search( redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; search_state .queue @@ -151,8 +151,8 @@ pub async fn random_projects_get( ) -> Result { params .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let statuses = crate::models::projects::ProjectStatus::iterator() .filter(|x| x.is_searchable()) @@ -191,7 +191,7 @@ pub async fn random_projects_get( .map_ok(|m| db_ids::DBProjectId(m.id)) .try_collect::>() .await - .wrap_internal_err("querying random project IDs")? + .internal_context("querying random project IDs")? } else { sqlx::query!( // IDs are randomly generated (see the `generate_ids` macro), so fetching a @@ -211,7 +211,7 @@ pub async fn random_projects_get( .map_ok(|m| db_ids::DBProjectId(m.id)) .try_collect::>() .await - .wrap_internal_err("querying random project IDs")? + .internal_context("querying random project IDs")? }; if params.project_type.is_some() { @@ -222,7 +222,7 @@ pub async fn random_projects_get( let projects_data = db_models::DBProject::get_many_ids(&project_ids, &***ro_pool, &redis) .await - .wrap_internal_err("fetching projects by ID")? + .internal_context("fetching projects by ID")? .into_iter() .map(Project::from) .collect::>(); @@ -254,7 +254,7 @@ pub async fn projects_get_route( session_queue: web::Data, ) -> Result { let project_refs = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing project references")?; + .request_context("deserializing project references")?; if let Some(response) = crate::routes::redirect_query_refs( &req, "ids", @@ -280,11 +280,11 @@ pub async fn projects_get( session_queue: web::Data, ) -> Result { let ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; let projects_data = db_models::DBProject::get_many(&ids, &***ro_pool, &redis) .await - .wrap_internal_err("fetching requested projects")?; + .internal_context("fetching requested projects")?; let user_option = get_user_from_headers( &req, @@ -299,7 +299,7 @@ pub async fn projects_get( let projects = filter_visible_projects(projects_data, &user_option, &ro_pool, false) .await - .wrap_api_err("filtering visible projects")?; + .api_context("filtering visible projects")?; Ok(HttpResponse::Ok().json(projects)) } @@ -346,7 +346,7 @@ pub async fn project_get_internal( let project_data = db_models::DBProject::get(&string, &***ro_pool, &redis) .await - .wrap_internal_err("failed to fetch project")?; + .internal_context("failed to fetch project")?; let user_option = get_user_from_headers( &req, &***ro_pool, @@ -360,11 +360,11 @@ pub async fn project_get_internal( if let Some(data) = project_data && is_visible_project(&data.inner, &user_option, &ro_pool, false) .await - .wrap_internal_err("failed to check project visibility")? + .internal_context("failed to check project visibility")? { return Ok(web::Json(Project::from(data))); } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } #[derive(Debug, Serialize, Deserialize, Validate, utoipa::ToSchema)] @@ -515,21 +515,21 @@ pub async fn project_edit_internal( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; new_project.validate().map_err(|err| { let message = crate::util::validate::validation_errors_to_string(err, None) .replacen("Field ", "field ", 1); - ApiError::Request(eyre!(message)) + ApiError::Request(anyhow!(message)) })?; let Some(mut project_item) = db_models::DBProject::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching project")? + .internal_context("fetching project")? else { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); }; let id = project_item.inner.id; @@ -541,14 +541,14 @@ pub async fn project_edit_internal( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; let Some(perms) = ProjectPermissions::get_permissions_by_scopes( user.scopes, &team_member, &organization_team_member, ) else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to edit this project!", ))); }; @@ -558,7 +558,7 @@ pub async fn project_edit_internal( && !user.scopes.contains(Scopes::MODERATION_WRITE); if submit_for_review && !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to submit this project for review" ))); } @@ -566,7 +566,7 @@ pub async fn project_edit_internal( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let locked_project = sqlx::query!( r#" SELECT status, slug @@ -578,13 +578,13 @@ pub async fn project_edit_internal( ) .fetch_one(&mut transaction) .await - .wrap_internal_err("locking project for editing")?; + .internal_context("locking project for editing")?; project_item.inner.status = ProjectStatus::from_string(&locked_project.status); project_item.inner.slug = locked_project.slug; if submit_for_review && project_item.inner.status.is_approved() { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to submit this project for review" ))); } @@ -593,7 +593,7 @@ pub async fn project_edit_internal( if let Some(name) = &new_project.name { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the name of this project!", ))); } @@ -609,12 +609,12 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(summary) = &new_project.summary { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the summary of this project!", ))); } @@ -630,14 +630,14 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(status) = &new_project.status && !submit_for_review { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the status of this project!", ))); } @@ -649,7 +649,7 @@ pub async fn project_edit_internal( &mut transaction, ) .await - .wrap_internal_err("failed to fetch project disclosures")? + .internal_context("failed to fetch project disclosures")? .into_iter() .find(|disclosure| { matches!( @@ -674,7 +674,7 @@ pub async fn project_edit_internal( } .upsert(&mut transaction) .await - .wrap_internal_err("failed to upsert archival disclosure")?; + .internal_context("failed to upsert archival disclosure")?; } } else { if !(user.scopes.contains(Scopes::MODERATION_WRITE) @@ -683,7 +683,7 @@ pub async fn project_edit_internal( || project_item.inner.status.is_approved() && status.can_be_requested()) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to set this status!", ))); } @@ -699,11 +699,11 @@ pub async fn project_edit_internal( &pool, ) .await - .wrap_internal_err("fetching moderation lock from database")? + .internal_context("fetching moderation lock from database")? && lock.moderator_id != db_ids::DBUserId::from(user.user.id) && !lock.expired { - return Err(ApiError::Auth(eyre::eyre!(format!( + return Err(ApiError::Auth(anyhow!(format!( "This project is currently being moderated by @{}. Please wait for them to finish or for the lock to expire.", lock.moderator_username )))); @@ -724,7 +724,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `project_edit_internal`", )?; } @@ -741,7 +741,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `project_edit_internal`", )?; } @@ -772,7 +772,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `project_edit_internal`", )?; } @@ -815,7 +815,7 @@ pub async fn project_edit_internal( .map_ok(|c| db_models::DBUserId(c.id)) .try_collect::>() .await - .wrap_internal_err("fetching notified members from database")?; + .internal_context("fetching notified members from database")?; NotificationBuilder { body: NotificationBody::StatusChange { @@ -826,7 +826,7 @@ pub async fn project_edit_internal( } .insert_many(notified_members.clone(), &mut transaction, &redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `project_edit_internal`", )?; @@ -845,7 +845,7 @@ pub async fn project_edit_internal( } .insert_many(notified_members, &mut transaction, &redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `project_edit_internal`", )?; } @@ -861,7 +861,7 @@ pub async fn project_edit_internal( } .insert(&mut transaction) .await - .wrap_internal_err( + .internal_context( "inserting database records for `project_edit_internal`", )?; @@ -876,7 +876,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `project_edit_internal`", )?; @@ -894,14 +894,14 @@ pub async fn project_edit_internal( &mut transaction, ) .await - .wrap_internal_err("failed to remove archival disclosure")?; + .internal_context("failed to remove archival disclosure")?; } } } if let Some(requested_status) = &new_project.requested_status { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the requested status of this project!", ))); } @@ -910,7 +910,7 @@ pub async fn project_edit_internal( .map(|x| x.can_be_requested()) .unwrap_or(true) { - return Err(ApiError::Request(eyre::eyre!(String::from( + return Err(ApiError::Request(anyhow!(String::from( "Specified status cannot be requested!", )))); } @@ -926,7 +926,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if perms.contains(ProjectPermissions::EDIT_DETAILS) { @@ -940,7 +940,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "updating database records for `project_edit_internal`", )?; } @@ -955,7 +955,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `project_edit_internal`", )?; } @@ -970,7 +970,7 @@ pub async fn project_edit_internal( &mut transaction, ) .await - .wrap_api_err("executing `edit_project_categories`")?; + .api_context("executing `edit_project_categories`")?; } if let Some(categories) = &new_project.additional_categories { @@ -982,12 +982,12 @@ pub async fn project_edit_internal( &mut transaction, ) .await - .wrap_api_err("executing `edit_project_categories`")?; + .api_context("executing `edit_project_categories`")?; } if let Some(license_url) = &new_project.license_url { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the license URL of this project!", ))); } @@ -1003,12 +1003,12 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(slug) = &new_project.slug { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit this project's URL!", ))); } @@ -1019,9 +1019,9 @@ pub async fn project_edit_internal( &redis, ) .await - .wrap_internal_err("checking project slug availability")?; + .internal_context("checking project slug availability")?; if existing.is_some() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Your URL is already being used by another project!", ))); } @@ -1042,12 +1042,12 @@ pub async fn project_edit_internal( ) .fetch_one(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `project_edit_internal`", )?; if results.exists.unwrap_or(true) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Your URL is already being used by another project!", ))); } @@ -1064,12 +1064,12 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(license) = &new_project.license_id { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the license of this project!", ))); } @@ -1081,8 +1081,8 @@ pub async fn project_edit_internal( } spdx::Expression::parse(&license) - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("parsing request value")?; + .map_err(|err| anyhow!(err)) + .request_context("parsing request value")?; sqlx::query!( " @@ -1095,14 +1095,14 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(links) = &new_project.link_urls && !links.is_empty() { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the links of this project!", ))); } @@ -1113,7 +1113,7 @@ pub async fn project_edit_internal( platform .parse::() .map(|platform| platform.to_string()) - .wrap_request_err_with(|| { + .request_context_with(|| { format!("platform `{platform}` does not exist") }) }) @@ -1129,13 +1129,13 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; for (platform, url) in links { if let Some(url) = url { let platform = platform .parse::() - .wrap_request_err_with(|| { + .request_context_with(|| { format!("platform `{platform}` does not exist") })? .to_string(); @@ -1150,7 +1150,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `project_edit_internal`", )?; } @@ -1161,7 +1161,7 @@ pub async fn project_edit_internal( && (!project_item.inner.status.is_approved() || moderation_message.is_some()) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the moderation message of this project!", ))); } @@ -1177,7 +1177,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(moderation_message_body) = &new_project.moderation_message_body @@ -1186,7 +1186,7 @@ pub async fn project_edit_internal( && (!project_item.inner.status.is_approved() || moderation_message_body.is_some()) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the moderation message body of this project!", ))); } @@ -1202,12 +1202,12 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(description) = &new_project.description { if !perms.contains(ProjectPermissions::EDIT_BODY) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the description (body) of this project!", ))); } @@ -1223,12 +1223,12 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(monetization_status) = &new_project.monetization_status { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the monetization status of this project!", ))); } @@ -1238,7 +1238,7 @@ pub async fn project_edit_internal( == MonetizationStatus::ForceDemonetized) && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the monetization status of this project!", ))); } @@ -1254,14 +1254,14 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } if let Some(side_types_migration_review_status) = &new_project.side_types_migration_review_status { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the side types migration review status of this project!", ))); } @@ -1277,7 +1277,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; } let mut edited_versions = Vec::new(); @@ -1288,11 +1288,11 @@ pub async fn project_edit_internal( &redis, ) .await - .wrap_internal_err("fetching versions from database")? + .internal_context("fetching versions from database")? { let mut savepoint = sqlx_tracing::Acquire::begin(&mut transaction) .await - .wrap_internal_err("starting version edit savepoint")?; + .internal_context("starting version edit savepoint")?; match super::versions::version_edit_in_transaction( minecraft_meta.clone(), req.clone(), @@ -1314,13 +1314,13 @@ pub async fn project_edit_internal( // projects with heterogeneous loaders across versions and is best // handled with opportunistic update semantics Ok((version, _)) => { - savepoint.commit().await.wrap_internal_err( + savepoint.commit().await.internal_context( "committing version edit savepoint", )?; edited_versions.push(version); } Err(ApiError::Request(_)) => { - savepoint.rollback().await.wrap_internal_err( + savepoint.rollback().await.internal_context( "rolling back version edit savepoint", )?; } @@ -1344,7 +1344,7 @@ pub async fn project_edit_internal( }; if !perms.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the components of this project!", ))); } @@ -1358,8 +1358,8 @@ pub async fn project_edit_internal( (None, Some(edit)) => { // component is specified in the JSON and is non-null - create new component *component = - Some(edit.create().wrap_request_err_with(|| { - eyre!( + Some(edit.create().request_context_with(|| { + anyhow!( "failed to create `{}` component", type_name::() ) @@ -1367,14 +1367,12 @@ pub async fn project_edit_internal( } (Some(component), Some(edit)) => { // edit component - edit.apply_to(component).await.wrap_internal_err_with( - || { - eyre!( - "failed to update `{}` component", - type_name::() - ) - }, - )?; + edit.apply_to(component).await.internal_context_with(|| { + anyhow!( + "failed to update `{}` component", + type_name::() + ) + })?; } } @@ -1400,7 +1398,7 @@ pub async fn project_edit_internal( perms, ) .await - .wrap_api_err("updating Minecraft server component")?; + .api_context("updating Minecraft server component")?; reindex_versions |= update( &mut transaction, id, @@ -1409,7 +1407,7 @@ pub async fn project_edit_internal( perms, ) .await - .wrap_api_err("updating Minecraft Java server component")?; + .api_context("updating Minecraft Java server component")?; reindex_versions |= update( &mut transaction, id, @@ -1418,7 +1416,7 @@ pub async fn project_edit_internal( perms, ) .await - .wrap_api_err("updating Minecraft Bedrock server component")?; + .api_context("updating Minecraft Bedrock server component")?; let components_serial = project_item.inner.components.clone(); @@ -1426,7 +1424,7 @@ pub async fn project_edit_internal( &components_serial.component_kinds(), &exp::PROJECT_COMPONENT_RELATIONS, ) - .wrap_request_err("invalid component kinds")?; + .request_context("invalid component kinds")?; sqlx::query!( " @@ -1440,7 +1438,7 @@ pub async fn project_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to update components")?; + .internal_context("failed to update components")?; let reloaded_project = if validate_for_review { validate::ensure_project_is_valid_for_review( @@ -1473,7 +1471,7 @@ pub async fn project_edit_internal( &redis, ) .await - .wrap_api_err("deleting unused images")?; + .api_context("deleting unused images")?; if submit_for_review { reindex_versions |= submit_project_for_review( @@ -1503,7 +1501,7 @@ pub async fn project_edit_internal( for version in &edited_versions { db_models::DBVersion::clear_cache(version, &redis) .await - .wrap_internal_err("clearing cached version data from Redis")?; + .internal_context("clearing cached version data from Redis")?; } if !edited_versions.is_empty() { search_state @@ -1563,7 +1561,7 @@ async fn submit_project_for_review( &mut *transaction, ) .await - .wrap_internal_err("failed to fetch project disclosures")? + .internal_context("failed to fetch project disclosures")? .into_iter() .find(|disclosure| { matches!(disclosure.disclosure, ProjectDisclosure::Archived { .. }) @@ -1581,7 +1579,7 @@ async fn submit_project_for_review( &mut *transaction, ) .await - .wrap_internal_err("failed to remove archival disclosure")?; + .internal_context("failed to remove archival disclosure")?; } let mut state = mutation::sync_project_state( @@ -1606,7 +1604,7 @@ async fn submit_project_for_review( ) .execute(&mut *transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; if state.status().is_approved() || !user.scopes.contains(Scopes::MODERATION_WRITE) @@ -1633,7 +1631,7 @@ async fn submit_project_for_review( .map_ok(|row| db_models::DBUserId(row.id)) .try_collect::>() .await - .wrap_internal_err("fetching notified members from database")?; + .internal_context("fetching notified members from database")?; NotificationBuilder { body: NotificationBody::StatusChange { @@ -1644,7 +1642,7 @@ async fn submit_project_for_review( } .insert_many(notified_members.clone(), &mut *transaction, redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `project_edit_internal`", )?; @@ -1657,7 +1655,7 @@ async fn submit_project_for_review( } .insert_many(notified_members, &mut *transaction, redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `project_edit_internal`", )?; } @@ -1673,7 +1671,7 @@ async fn submit_project_for_review( } .insert(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "inserting database records for `project_edit_internal`", )?; @@ -1688,7 +1686,7 @@ async fn submit_project_for_review( ) .execute(&mut *transaction) .await - .wrap_internal_err("querying database for `project_edit_internal`")?; + .internal_context("querying database for `project_edit_internal`")?; Ok(false) } @@ -1702,7 +1700,7 @@ pub async fn edit_project_categories( ) -> Result<(), ApiError> { if !perms.contains(ProjectPermissions::EDIT_DETAILS) { let additional_str = if is_additional { "additional " } else { "" }; - return Err(ApiError::Auth(eyre::eyre!(format!( + return Err(ApiError::Auth(anyhow!(format!( "You do not have the permissions to edit the {additional_str}categories of this project!" )))); } @@ -1714,7 +1712,7 @@ pub async fn edit_project_categories( &mut *transaction, ) .await - .wrap_internal_err("fetching category from Redis")?; + .internal_context("fetching category from Redis")?; // TODO: We should filter out categories that don't match the project type of any of the versions // ie: if mod and modpack both share a name this should only have modpack if it only has a modpack as a version @@ -1730,7 +1728,7 @@ pub async fn edit_project_categories( } DBModCategory::insert_many(mod_categories, &mut *transaction) .await - .wrap_internal_err("inserting mod categories into database")?; + .internal_context("inserting mod categories into database")?; Ok(()) } @@ -1773,7 +1771,7 @@ pub async fn project_search( let results = search_backend .search_for_project(&SearchRequest::from(info), &redis) .await - .wrap_api_err("searching projects")?; + .api_context("searching projects")?; // TODO: add this back // let results = ReturnSearchResults { @@ -1806,7 +1804,7 @@ pub async fn project_search_post( let results = search_backend .search_for_project(&info, &redis) .await - .wrap_api_err("searching projects")?; + .api_context("searching projects")?; Ok(web::Json(results)) } @@ -1849,14 +1847,14 @@ pub async fn project_get_check_internal( let project_data = db_models::DBProject::get(&slug, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; if let Some(project) = project_data { Ok(HttpResponse::Ok().json(ProjectCheckResponse { id: models::ids::ProjectId::from(project.inner.id), })) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1909,7 +1907,7 @@ pub async fn dependency_list_internal( let result = db_models::DBProject::get(&string, &***ro_pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; let user_option = get_user_from_headers( &req, @@ -1924,9 +1922,9 @@ pub async fn dependency_list_internal( if let Some(project) = result { if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let dependencies = database::DBProject::get_dependencies( @@ -1935,7 +1933,7 @@ pub async fn dependency_list_internal( &redis, ) .await - .wrap_internal_err("fetching projects from database")?; + .internal_context("fetching projects from database")?; let project_ids = dependencies .iter() .filter_map(|x| { @@ -1970,11 +1968,11 @@ pub async fn dependency_list_internal( &redis, ) .await - .wrap_err("fetching dependency versions") + .context("fetching dependency versions") }, ) .await - .wrap_internal_err("fetching project dependencies")?; + .internal_context("fetching project dependencies")?; let mut projects = filter_visible_projects( projects_result, @@ -1983,7 +1981,7 @@ pub async fn dependency_list_internal( false, ) .await - .wrap_api_err("filtering visible projects")?; + .api_context("filtering visible projects")?; let mut versions = filter_visible_versions( versions_result, &user_option, @@ -1991,7 +1989,7 @@ pub async fn dependency_list_internal( &redis, ) .await - .wrap_api_err("filtering visible versions")?; + .api_context("filtering visible versions")?; projects.sort_by_key(|b| Reverse(b.published)); projects.dedup_by(|a, b| a.id == b.id); @@ -2001,7 +1999,7 @@ pub async fn dependency_list_internal( Ok(HttpResponse::Ok().json(DependencyInfo { projects, versions })) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -2047,7 +2045,7 @@ pub async fn projects_edit_route( search_state: web::Data, ) -> Result { let project_refs = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing project references")?; + .request_context("deserializing project references")?; if let Some(response) = crate::routes::redirect_query_refs( &req, "ids", @@ -2091,16 +2089,16 @@ pub async fn projects_edit( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; bulk_edit_project .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let project_ids: Vec = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(|x| x.into()) .collect(); @@ -2108,13 +2106,13 @@ pub async fn projects_edit( let projects_data = db_models::DBProject::get_many_ids(&project_ids, &**pool, &redis) .await - .wrap_internal_err("fetching projects to edit")?; + .internal_context("fetching projects to edit")?; if let Some(id) = project_ids .iter() .find(|x| !projects_data.iter().any(|y| x == &&y.inner.id)) { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Project {} not found", ProjectId(id.0 as u64) )))); @@ -2128,7 +2126,7 @@ pub async fn projects_edit( &team_ids, &**pool, &redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let organization_ids = projects_data .iter() @@ -2140,7 +2138,7 @@ pub async fn projects_edit( &redis, ) .await - .wrap_internal_err("fetching organizations from database")?; + .internal_context("fetching organizations from database")?; let organization_team_ids = organizations .iter() @@ -2153,16 +2151,16 @@ pub async fn projects_edit( &redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let categories = db_models::categories::Category::list(&**pool, &redis) .await - .wrap_internal_err("fetching category from Redis")?; + .internal_context("fetching category from Redis")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let mut changed_projects = Vec::new(); for project in projects_data { @@ -2196,18 +2194,18 @@ pub async fn projects_edit( if team_member.is_some() { if !permissions.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!(format!( + return Err(ApiError::Auth(anyhow!(format!( "You do not have the permissions to bulk edit project {}!", project.inner.name )))); } } else if project.inner.status.is_hidden() { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Project {} not found", ProjectId(project.inner.id.0 as u64) )))); } else { - return Err(ApiError::Auth(eyre::eyre!(format!( + return Err(ApiError::Auth(anyhow!(format!( "You are not a member of project {}!", project.inner.name )))); @@ -2240,7 +2238,7 @@ pub async fn projects_edit( &mut transaction, ) .await - .wrap_api_err("executing `bulk_edit_project_categories`")?; + .api_context("executing `bulk_edit_project_categories`")?; reindex_versions |= bulk_edit_project_categories( &categories, @@ -2257,7 +2255,7 @@ pub async fn projects_edit( &mut transaction, ) .await - .wrap_api_err("executing `bulk_edit_project_categories`")?; + .api_context("executing `bulk_edit_project_categories`")?; if let Some(links) = &bulk_edit_project.link_urls { let platforms_to_delete = links @@ -2266,7 +2264,7 @@ pub async fn projects_edit( platform .parse::() .map(|platform| platform.to_string()) - .wrap_request_err_with(|| { + .request_context_with(|| { format!("platform `{platform}` does not exist") }) }) @@ -2282,13 +2280,13 @@ pub async fn projects_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `projects_edit`")?; + .internal_context("querying database for `projects_edit`")?; for (platform, url) in links { if let Some(url) = url { let platform = platform .parse::() - .wrap_request_err_with(|| { + .request_context_with(|| { format!("platform `{platform}` does not exist") })? .to_string(); @@ -2303,7 +2301,7 @@ pub async fn projects_edit( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `projects_edit`", )?; } @@ -2406,7 +2404,7 @@ pub async fn bulk_edit_project_categories( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `bulk_edit_project_categories`", )?; @@ -2415,7 +2413,7 @@ pub async fn bulk_edit_project_categories( let category_id = all_db_categories .iter() .find(|x| x.category == category) - .wrap_request_err_with(|| { + .request_context_with(|| { format!("category `{}` does not exist", category.clone()) })? .id; @@ -2427,7 +2425,7 @@ pub async fn bulk_edit_project_categories( } DBModCategory::insert_many(mod_categories, &mut *transaction) .await - .wrap_internal_err("inserting mod categories into database")?; + .internal_context("inserting mod categories into database")?; } Ok(changed) @@ -2507,13 +2505,13 @@ pub async fn project_icon_edit_internal( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let project_item = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; @@ -2525,11 +2523,11 @@ pub async fn project_icon_edit_internal( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; // Hide the project if team_member.is_none() && organization_team_member.is_none() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The specified project does not exist!", ))); } @@ -2542,7 +2540,7 @@ pub async fn project_icon_edit_internal( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this project's icon.", ))); } @@ -2572,12 +2570,12 @@ pub async fn project_icon_edit_internal( &**file_host, ) .await - .wrap_api_err("uploading image")?; + .api_context("uploading image")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -2592,7 +2590,7 @@ pub async fn project_icon_edit_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_icon_edit_internal`")?; + .internal_context("querying database for `project_icon_edit_internal`")?; mutation::finalize_mutation( project_item.inner.id, @@ -2618,7 +2616,7 @@ pub async fn project_icon_edit_internal( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; search_state .queue @@ -2685,13 +2683,13 @@ pub async fn delete_project_icon_internal( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let project_item = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; @@ -2703,11 +2701,11 @@ pub async fn delete_project_icon_internal( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; // Hide the project if team_member.is_none() && organization_team_member.is_none() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The specified project does not exist!", ))); } @@ -2719,7 +2717,7 @@ pub async fn delete_project_icon_internal( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this project's icon.", ))); } @@ -2728,7 +2726,7 @@ pub async fn delete_project_icon_internal( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -2740,9 +2738,7 @@ pub async fn delete_project_icon_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( - "querying database for `delete_project_icon_internal`", - )?; + .internal_context("querying database for `delete_project_icon_internal`")?; mutation::finalize_mutation( project_item.inner.id, @@ -2760,7 +2756,7 @@ pub async fn delete_project_icon_internal( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; search_state .queue @@ -2849,8 +2845,8 @@ pub async fn add_gallery_item_internal( search_state: web::Data, ) -> Result { item.validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let user = get_user_from_headers( &req, @@ -2860,18 +2856,18 @@ pub async fn add_gallery_item_internal( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let project_item = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; if project_item.gallery_items.len() > 64 { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You have reached the maximum of gallery images to upload.", ))); } @@ -2884,11 +2880,11 @@ pub async fn add_gallery_item_internal( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; // Hide the project if team_member.is_none() && organization_team_member.is_none() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The specified project does not exist!", ))); } @@ -2901,7 +2897,7 @@ pub async fn add_gallery_item_internal( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this project's gallery.", ))); } @@ -2931,14 +2927,14 @@ pub async fn add_gallery_item_internal( &**file_host, ) .await - .wrap_api_err("uploading image")?; + .api_context("uploading image")?; if project_item .gallery_items .iter() .any(|x| x.image_url == upload_result.url) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You may not upload duplicate gallery images!", ))); } @@ -2946,7 +2942,7 @@ pub async fn add_gallery_item_internal( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if item.featured { sqlx::query!( @@ -2960,7 +2956,7 @@ pub async fn add_gallery_item_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `add_gallery_item_internal`", )?; } @@ -2981,7 +2977,7 @@ pub async fn add_gallery_item_internal( &mut transaction, ) .await - .wrap_internal_err("inserting galleries into database")?; + .internal_context("inserting galleries into database")?; let validation_error = if !user.scopes.contains(Scopes::MODERATION_WRITE) && project_item.inner.status == ProjectStatus::Processing @@ -3005,7 +3001,7 @@ pub async fn add_gallery_item_internal( &**file_host, ) .await - .wrap_api_err("deleting rejected gallery image upload")?; + .api_context("deleting rejected gallery image upload")?; return Err(error); } @@ -3095,11 +3091,11 @@ pub async fn edit_gallery_item_internal( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; item.validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let result = sqlx::query!( " @@ -3110,8 +3106,8 @@ pub async fn edit_gallery_item_internal( ) .fetch_optional(&**pool) .await - .wrap_internal_err("querying database for `edit_gallery_item_internal`")? - .wrap_request_err_with(|| { + .internal_context("querying database for `edit_gallery_item_internal`")? + .request_context_with(|| { format!( "gallery item at URL `{}` is not part of the project's gallery", item.url @@ -3124,8 +3120,8 @@ pub async fn edit_gallery_item_internal( &redis, ) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; @@ -3137,11 +3133,11 @@ pub async fn edit_gallery_item_internal( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; // Hide the project if team_member.is_none() && organization_team_member.is_none() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The specified project does not exist!", ))); } @@ -3153,7 +3149,7 @@ pub async fn edit_gallery_item_internal( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this project's gallery.", ))); } @@ -3162,7 +3158,7 @@ pub async fn edit_gallery_item_internal( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(featured) = item.featured { if featured { @@ -3177,7 +3173,7 @@ pub async fn edit_gallery_item_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("fetching featured status from database")?; + .internal_context("fetching featured status from database")?; } sqlx::query!( @@ -3191,7 +3187,7 @@ pub async fn edit_gallery_item_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `edit_gallery_item_internal`", )?; } @@ -3207,7 +3203,7 @@ pub async fn edit_gallery_item_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `edit_gallery_item_internal`", )?; } @@ -3223,7 +3219,7 @@ pub async fn edit_gallery_item_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `edit_gallery_item_internal`", )?; } @@ -3239,7 +3235,7 @@ pub async fn edit_gallery_item_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `edit_gallery_item_internal`", )?; } @@ -3312,7 +3308,7 @@ pub async fn delete_gallery_item_internal( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let item = sqlx::query!( " @@ -3323,8 +3319,8 @@ pub async fn delete_gallery_item_internal( ) .fetch_optional(&**pool) .await - .wrap_internal_err("querying database for `delete_gallery_item_internal`")? - .wrap_request_err_with(|| { + .internal_context("querying database for `delete_gallery_item_internal`")? + .request_context_with(|| { format!( "gallery item at URL `{}` is not part of the project's gallery", item.url @@ -3337,8 +3333,8 @@ pub async fn delete_gallery_item_internal( &redis, ) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; @@ -3350,11 +3346,11 @@ pub async fn delete_gallery_item_internal( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; // Hide the project if team_member.is_none() && organization_team_member.is_none() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The specified project does not exist!", ))); } @@ -3367,7 +3363,7 @@ pub async fn delete_gallery_item_internal( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::EDIT_DETAILS) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this project's gallery.", ))); } @@ -3376,7 +3372,7 @@ pub async fn delete_gallery_item_internal( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -3387,9 +3383,7 @@ pub async fn delete_gallery_item_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( - "querying database for `delete_gallery_item_internal`", - )?; + .internal_context("querying database for `delete_gallery_item_internal`")?; mutation::finalize_mutation( project_item.inner.id, @@ -3407,7 +3401,7 @@ pub async fn delete_gallery_item_internal( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; search_state .queue @@ -3472,7 +3466,7 @@ pub async fn project_delete_internal( Scopes::PROJECT_DELETE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; // In two cases, we return `The specified project does not exist!`: @@ -3485,8 +3479,8 @@ pub async fn project_delete_internal( let project = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("failed to get project")? - .wrap_auth_err("the specified project does not exist")?; + .internal_context("failed to get project")? + .auth_context("the specified project does not exist")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) { let (team_member, organization_team_member) = @@ -3496,11 +3490,11 @@ pub async fn project_delete_internal( &**pool, ) .await - .wrap_internal_err("failed to get user team member permissions")?; + .internal_context("failed to get user team member permissions")?; // Hide the project if team_member.is_none() && organization_team_member.is_none() { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "The specified project does not exist!" ))); } @@ -3513,7 +3507,7 @@ pub async fn project_delete_internal( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::DELETE_PROJECT) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to delete this project!", ))); } @@ -3522,7 +3516,7 @@ pub async fn project_delete_internal( let mut transaction = pool .begin() .await - .wrap_internal_err("failed to start transaction")?; + .internal_context("failed to start transaction")?; let locked_project = sqlx::query!( r#" SELECT status, slug @@ -3534,7 +3528,7 @@ pub async fn project_delete_internal( ) .fetch_one(&mut transaction) .await - .wrap_internal_err("locking project for deletion")?; + .internal_context("locking project for deletion")?; let original_status = ProjectStatus::from_string(&locked_project.status); let original_slug = locked_project.slug; @@ -3544,7 +3538,7 @@ pub async fn project_delete_internal( &mut transaction, ) .await - .wrap_internal_err("removing project from technical review queue")?; + .internal_context("removing project from technical review queue")?; // rejected & withheld projects are transferred to ghost so moderation data is preserved if matches!( @@ -3573,7 +3567,7 @@ pub async fn project_delete_internal( ) .fetch_one(&mut transaction) .await - .wrap_internal_err("checking deleted slug availability")? + .internal_context("checking deleted slug availability")? .exists; if !taken { @@ -3599,7 +3593,7 @@ pub async fn project_delete_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "failed to detach project from organization and update slug", )?; @@ -3615,11 +3609,11 @@ pub async fn project_delete_internal( .map_ok(|x| db_ids::DBUserId(x.user_id)) .try_collect::>() .await - .wrap_internal_err("failed to remove project team members")?; + .internal_context("failed to remove project team members")?; let new_member_id = db_ids::generate_team_member_id(&mut transaction) .await - .wrap_internal_err("failed to generate team member ID")?; + .internal_context("failed to generate team member ID")?; DBTeamMember { id: new_member_id, team_id: project.inner.team_id, @@ -3634,7 +3628,7 @@ pub async fn project_delete_internal( } .insert(&mut transaction) .await - .wrap_internal_err("failed to transfer project ownership to ghost")?; + .internal_context("failed to transfer project ownership to ghost")?; ThreadMessageBuilder { author_id: Some(deleted_user), @@ -3653,7 +3647,7 @@ pub async fn project_delete_internal( } .insert(&mut transaction) .await - .wrap_internal_err( + .internal_context( "failed to insert project transfer thread message", )?; @@ -3666,7 +3660,7 @@ pub async fn project_delete_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to delete project from collections_mods")?; + .internal_context("failed to delete project from collections_mods")?; sqlx::query!( " @@ -3677,7 +3671,7 @@ pub async fn project_delete_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to delete project followers")?; + .internal_context("failed to delete project followers")?; mutation::finalize_project_edit( project.inner.id, @@ -3695,10 +3689,10 @@ pub async fn project_delete_internal( cache_user_ids.push(deleted_user); db_models::DBUser::clear_project_cache(&cache_user_ids, &redis) .await - .wrap_internal_err("failed to clear user project cache")?; + .internal_context("failed to clear user project cache")?; DBTeamMember::clear_cache(project.inner.team_id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; search_state .queue .push_project_removal(project.inner.id.into()) @@ -3713,12 +3707,12 @@ pub async fn project_delete_internal( let uploaded_images = db_models::DBImage::get_many_contexted(context, &mut transaction) .await - .wrap_internal_err("failed to get project images")?; + .internal_context("failed to get project images")?; for image in uploaded_images { image_item::DBImage::remove(image.id, &mut transaction, &redis) .await - .wrap_internal_err_with(|| { - eyre!("failed to remove project image `{:?}`", image.id) + .internal_context_with(|| { + anyhow!("failed to remove project image `{:?}`", image.id) })?; } @@ -3731,7 +3725,7 @@ pub async fn project_delete_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("failed to delete project from collections_mods")?; + .internal_context("failed to delete project from collections_mods")?; let result = db_models::DBProject::remove( project.inner.id, @@ -3739,12 +3733,12 @@ pub async fn project_delete_internal( &redis, ) .await - .wrap_internal_err("failed to remove project")?; + .internal_context("failed to remove project")?; transaction .commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; if result.is_some() { db_models::DBProject::clear_cache( @@ -3754,14 +3748,14 @@ pub async fn project_delete_internal( &redis, ) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; search_state .queue .push_project_removal(project.inner.id.into()) .await; Ok(()) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -3809,13 +3803,13 @@ pub async fn project_follow_internal( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let project = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; @@ -3824,15 +3818,15 @@ pub async fn project_follow_internal( if !is_visible_project(&project.inner, &Some(user), &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let insert_result = sqlx::query!( " @@ -3845,10 +3839,10 @@ pub async fn project_follow_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_follow_internal`")?; + .internal_context("querying database for `project_follow_internal`")?; if insert_result.rows_affected() == 0 { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "you are already following this project", ))); } @@ -3863,12 +3857,12 @@ pub async fn project_follow_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_follow_internal`")?; + .internal_context("querying database for `project_follow_internal`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; db_models::DBProject::clear_cache( project_id, @@ -3877,7 +3871,7 @@ pub async fn project_follow_internal( &redis, ) .await - .wrap_internal_err("clearing cached project data")?; + .internal_context("clearing cached project data")?; Ok(HttpResponse::NoContent().body("")) } @@ -3926,13 +3920,13 @@ pub async fn project_unfollow_internal( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let string = info.into_inner().0; let project = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; @@ -3942,7 +3936,7 @@ pub async fn project_unfollow_internal( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let delete_result = sqlx::query!( " @@ -3954,10 +3948,10 @@ pub async fn project_unfollow_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_unfollow_internal`")?; + .internal_context("querying database for `project_unfollow_internal`")?; if delete_result.rows_affected() == 0 { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "you are not following this project", ))); } @@ -3972,12 +3966,12 @@ pub async fn project_unfollow_internal( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `project_unfollow_internal`")?; + .internal_context("querying database for `project_unfollow_internal`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; db_models::DBProject::clear_cache( project_id, @@ -3986,7 +3980,7 @@ pub async fn project_unfollow_internal( &redis, ) .await - .wrap_internal_err("clearing cached project data")?; + .internal_context("clearing cached project data")?; Ok(HttpResponse::NoContent().body("")) } @@ -4031,24 +4025,24 @@ pub async fn project_get_organization( let string = info.into_inner().0; let result = db_models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_request_err_with(|| { + .internal_context("fetching project from database")? + .request_context_with(|| { "the specified project does not exist!".to_string() })?; if !is_visible_project(&result.inner, ¤t_user, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - Err(ApiError::Request(eyre::eyre!( + Err(ApiError::Request(anyhow!( "The specified project does not exist!", ))) } else if let Some(organization_id) = result.inner.organization_id { let organization = db_models::DBOrganization::get_id(organization_id, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")? - .wrap_request_err_with(|| { + .internal_context("fetching organization from database")? + .request_context_with(|| { "the attached organization does not exist!".to_string() })?; @@ -4058,7 +4052,7 @@ pub async fn project_get_organization( &redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = crate::database::models::DBUser::get_many_ids( &members_data.iter().map(|x| x.user_id).collect::>(), @@ -4066,7 +4060,7 @@ pub async fn project_get_organization( &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let logged_in = current_user .as_ref() .and_then(|user| { @@ -4101,6 +4095,6 @@ pub async fn project_get_organization( ); Ok(HttpResponse::Ok().json(organization)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/routes/v3/projects/mutation.rs b/apps/labrinth/src/routes/v3/projects/mutation.rs index eafbc23bcbf..b14b6d275b2 100644 --- a/apps/labrinth/src/routes/v3/projects/mutation.rs +++ b/apps/labrinth/src/routes/v3/projects/mutation.rs @@ -1,4 +1,4 @@ -use eyre::eyre; +use anyhow::anyhow; use xredis::RedisPool; use crate::auth::UserWithScopes; @@ -76,7 +76,7 @@ impl SyncedProjectState { transaction, ) .await - .wrap_internal_err("verifying project moderation issues")?; + .internal_context("verifying project moderation issues")?; } Ok(()) } @@ -102,7 +102,7 @@ impl SyncedProjectState { ) .execute(&mut *transaction) .await - .wrap_internal_err("auto-approving project")?; + .internal_context("auto-approving project")?; self.verify_facets(transaction).await?; @@ -117,7 +117,7 @@ impl SyncedProjectState { } .insert(transaction) .await - .wrap_internal_err("recording project auto-approval")?; + .internal_context("recording project auto-approval")?; let notified_members = sqlx::query!( r#" @@ -129,7 +129,7 @@ impl SyncedProjectState { ) .fetch_all(&mut *transaction) .await - .wrap_internal_err("fetching project approval notification recipients")? + .internal_context("fetching project approval notification recipients")? .into_iter() .map(|row| DBUserId(row.user_id)) .collect::>(); @@ -147,7 +147,7 @@ impl SyncedProjectState { NotificationBuilder { body } .insert_many(notified_members.clone(), transaction, redis) .await - .wrap_internal_err("notifying project team of auto-approval")?; + .internal_context("notifying project team of auto-approval")?; } self.data.inner.status = new_status; @@ -213,7 +213,7 @@ async fn sync_technical_review( sqlx::query!("SELECT pg_advisory_xact_lock($1)", project_id.0) .fetch_one(&mut *transaction) .await - .wrap_internal_err("locking project state synchronization")?; + .internal_context("locking project state synchronization")?; } let exited_projects = delphi::tech_review_queue::sync_projects( @@ -222,7 +222,7 @@ async fn sync_technical_review( transaction, ) .await - .wrap_api_err("synchronizing project technical review state")?; + .api_context("synchronizing project technical review state")?; let queued_projects = sqlx::query_scalar!( r#" SELECT project_id AS "project_id!: DBProjectId" @@ -233,7 +233,7 @@ async fn sync_technical_review( ) .fetch_all(&mut *transaction) .await - .wrap_internal_err("fetching synchronized technical review membership")?; + .internal_context("fetching synchronized technical review membership")?; Ok((exited_projects, queued_projects)) } @@ -250,7 +250,7 @@ pub(crate) async fn load_project_state( sqlx::query!("SELECT pg_advisory_xact_lock($1)", project_id.0) .fetch_one(&mut *transaction) .await - .wrap_internal_err("locking project state synchronization")?; + .internal_context("locking project state synchronization")?; let queued_projects = sqlx::query_scalar!( r#" @@ -262,7 +262,7 @@ pub(crate) async fn load_project_state( ) .fetch_all(&mut *transaction) .await - .wrap_internal_err("fetching synchronized technical review membership")?; + .internal_context("fetching synchronized technical review membership")?; load_project_state_with_membership( project_id, @@ -287,22 +287,22 @@ async fn load_project_state_with_membership( redis, ) .await - .wrap_internal_err("reloading project for state synchronization")?; - let data = projects.pop().wrap_not_found_err("resource not found")?; + .internal_context("reloading project for state synchronization")?; + let data = projects.pop().not_found_context("resource not found")?; let version_ids = sqlx::query_scalar!( r#"SELECT id AS "id!: DBVersionId" FROM versions WHERE mod_id = $1 ORDER BY id"#, project_id.0, ) .fetch_all(&mut *transaction) .await - .wrap_internal_err("fetching all project version IDs")?; + .internal_context("fetching all project version IDs")?; let versions = db_models::DBVersion::get_many_uncached( &version_ids, &mut *transaction, redis, ) .await - .wrap_internal_err("reloading project versions for state synchronization")? + .internal_context("reloading project versions for state synchronization")? .into_iter() .map(Version::from) .collect::>(); @@ -310,14 +310,14 @@ async fn load_project_state_with_membership( let available_categories = db_models::categories::Category::list(&mut *transaction, redis) .await - .wrap_internal_err("fetching project categories")?; + .internal_context("fetching project categories")?; let disclosures = db_models::DBProjectDisclosure::get_many_for_project( data.inner.id, false, &mut *transaction, ) .await - .wrap_internal_err("fetching project disclosures")? + .internal_context("fetching project disclosures")? .into_iter() .map(|disclosure| disclosure.disclosure) .collect::>(); @@ -338,7 +338,7 @@ async fn load_project_state_with_membership( ) .fetch_all(&mut *transaction) .await - .wrap_internal_err("fetching project team members")? + .internal_context("fetching project team members")? .into_iter() .map(|member| ThreadIssueTeamMember { team_id: DBTeamId(member.team_id).into(), @@ -367,7 +367,7 @@ async fn load_project_state_with_membership( let thread_issues = db_models::DBThreadIssue::sync_project_verdicts(&context, transaction) .await - .wrap_internal_err("synchronizing project thread issue verdicts")?; + .internal_context("synchronizing project thread issue verdicts")?; Ok(SyncedProjectState { data, @@ -478,7 +478,7 @@ pub(crate) async fn prepare_mutations( if state.project.status == ProjectStatus::Processing && state.has_required_nags { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "project cannot have required validation nags while in review" ))); } @@ -497,7 +497,7 @@ impl PreparedMutations { transaction .commit() .await - .wrap_internal_err("committing project mutation")?; + .internal_context("committing project mutation")?; for state in &self.states { db_models::DBProject::clear_cache( @@ -507,7 +507,7 @@ impl PreparedMutations { redis, ) .await - .wrap_internal_err("clearing cached project data")?; + .internal_context("clearing cached project data")?; } Ok(()) @@ -541,7 +541,7 @@ pub(crate) async fn finalize_project_edit( .is_some_and(|user| user.scopes.contains(Scopes::MODERATION_WRITE)) && state.has_required_nags { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "project must have no required validation nags before or during review or approval" ))); } @@ -554,7 +554,7 @@ pub(crate) async fn finalize_project_edit( .iter() .any(|issue| issue.verdict == ThreadIssueVerdict::Open) { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "project must have no open moderation issues before review" ))); } @@ -565,7 +565,7 @@ pub(crate) async fn finalize_project_edit( .iter() .any(|issue| issue.verdict != ThreadIssueVerdict::Resolved) { - return Err(ApiError::Request(eyre!( + return Err(ApiError::Request(anyhow!( "all moderation issues must be resolved before approval" ))); } @@ -576,7 +576,7 @@ pub(crate) async fn finalize_project_edit( transaction .commit() .await - .wrap_internal_err("committing project mutation")?; + .internal_context("committing project mutation")?; db_models::DBProject::clear_cache( project_id, @@ -585,7 +585,7 @@ pub(crate) async fn finalize_project_edit( redis, ) .await - .wrap_internal_err("clearing cached project data")?; + .internal_context("clearing cached project data")?; if original_slug != state.data.inner.slug { db_models::DBProject::clear_cache( @@ -595,7 +595,7 @@ pub(crate) async fn finalize_project_edit( redis, ) .await - .wrap_internal_err("clearing previous project slug cache")?; + .internal_context("clearing previous project slug cache")?; } Ok(()) diff --git a/apps/labrinth/src/routes/v3/projects/validate.rs b/apps/labrinth/src/routes/v3/projects/validate.rs index 1ca6f3bc17e..0e9cdf3c07a 100644 --- a/apps/labrinth/src/routes/v3/projects/validate.rs +++ b/apps/labrinth/src/routes/v3/projects/validate.rs @@ -1,5 +1,5 @@ use actix_web::{HttpRequest, HttpResponse, get, web}; -use eyre::eyre; +use anyhow::anyhow; use serde::Serialize; use xredis::RedisPool; @@ -33,7 +33,7 @@ pub(crate) fn require_valid_project( .iter() .any(|nag| nag.severity == ProjectNagSeverity::Required) { - return Err(ApiError::Request(eyre!(ProjectValidationError(nags)))); + return Err(ApiError::Request(anyhow!(ProjectValidationError(nags)))); } Ok(()) } @@ -77,30 +77,30 @@ pub(crate) async fn ensure_project_is_valid_for_review( redis, ) .await - .wrap_internal_err("reloading project for review validation")?; + .internal_context("reloading project for review validation")?; let reloaded_project = - projects.pop().wrap_not_found_err("resource not found")?; + projects.pop().not_found_context("resource not found")?; let versions = db_models::DBVersion::get_many_uncached( &reloaded_project.versions, &mut *transaction, redis, ) .await - .wrap_internal_err("reloading project versions for review validation")? + .internal_context("reloading project versions for review validation")? .into_iter() .map(Version::from) .collect::>(); let available_categories = db_models::categories::Category::list(&**pool, redis) .await - .wrap_internal_err("fetching project categories")?; + .internal_context("fetching project categories")?; let disclosures = db_models::DBProjectDisclosure::get_many_for_project( reloaded_project.inner.id, false, &mut *transaction, ) .await - .wrap_internal_err("fetching project disclosures")? + .internal_context("fetching project disclosures")? .into_iter() .map(|disclosure| disclosure.disclosure) .collect::>(); @@ -155,13 +155,13 @@ pub async fn validate( Scopes::PROJECT_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let project = db_models::DBProject::get(&info.into_inner().0, &***ro_pool, &redis) .await - .wrap_internal_err("fetching project from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching project from database")? + .not_found_context("resource not found")?; let (team_member, organization_team_member) = db_models::DBTeamMember::get_for_project_permissions( @@ -170,7 +170,7 @@ pub async fn validate( &***ro_pool, ) .await - .wrap_internal_err("fetching project permissions")?; + .internal_context("fetching project permissions")?; if !scopes.contains(Scopes::MODERATION_READ) && ProjectPermissions::get_permissions_by_scopes( @@ -180,7 +180,7 @@ pub async fn validate( ) .is_none() { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to validate this project" ))); } @@ -188,21 +188,21 @@ pub async fn validate( let versions = db_models::DBVersion::get_many(&project.versions, &***ro_pool, &redis) .await - .wrap_internal_err("fetching project versions from database")? + .internal_context("fetching project versions from database")? .into_iter() .map(Version::from) .collect::>(); let available_categories = db_models::categories::Category::list(&**pool, &redis) .await - .wrap_internal_err("fetching project categories")?; + .internal_context("fetching project categories")?; let disclosures = db_models::DBProjectDisclosure::get_many_for_project( project.inner.id, false, &***ro_pool, ) .await - .wrap_internal_err("fetching project disclosures")? + .internal_context("fetching project disclosures")? .into_iter() .map(|disclosure| disclosure.disclosure) .collect::>(); diff --git a/apps/labrinth/src/routes/v3/reports.rs b/apps/labrinth/src/routes/v3/reports.rs index c4a0deea3cf..97d5b51d794 100644 --- a/apps/labrinth/src/routes/v3/reports.rs +++ b/apps/labrinth/src/routes/v3/reports.rs @@ -23,6 +23,7 @@ use crate::util::http::HTTP_CLIENT; use crate::util::img; use crate::util::routes::read_typed_from_payload; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, post, web}; +use anyhow::anyhow; use ariadne::ids::UserId; use ariadne::ids::base62_impl::{parse_base62, to_base62}; use chrono::Utc; @@ -77,7 +78,7 @@ pub async fn report_create( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let current_user = get_user_from_headers( &req, @@ -87,23 +88,23 @@ pub async fn report_create( Scopes::REPORT_CREATE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; let new_report: CreateReport = read_typed_from_payload(&mut body) .await - .wrap_api_err("reading request payload")?; + .api_context("reading request payload")?; let id = crate::database::models::generate_report_id(&mut transaction) .await - .wrap_internal_err("generating report ID")?; + .internal_context("generating report ID")?; let report_type = crate::database::models::categories::ReportType::get_id( &new_report.report_type, &mut transaction, ) .await - .wrap_internal_err("generating report ID")? - .wrap_request_err_with(|| { + .internal_context("generating report ID")? + .request_context_with(|| { format!("invalid report type: `{}`", new_report.report_type) })?; @@ -126,7 +127,7 @@ pub async fn report_create( ItemType::Project => { let project_id = ProjectId( parse_base62(new_report.item_id.as_str()) - .wrap_request_err("parsing reported project ID")?, + .request_context("parsing reported project ID")?, ); let result = sqlx::query!( @@ -135,10 +136,10 @@ pub async fn report_create( ) .fetch_one(&mut transaction) .await - .wrap_internal_err("querying database for `report_create`")?; + .internal_context("querying database for `report_create`")?; if !result.exists.unwrap_or(false) { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Project could not be found: {}", new_report.item_id )))); @@ -149,7 +150,7 @@ pub async fn report_create( ItemType::Version => { let version_id = VersionId( parse_base62(new_report.item_id.as_str()) - .wrap_request_err("parsing reported version ID")?, + .request_context("parsing reported version ID")?, ); let result = sqlx::query!( @@ -158,10 +159,10 @@ pub async fn report_create( ) .fetch_one(&mut transaction) .await - .wrap_internal_err("querying database for `report_create`")?; + .internal_context("querying database for `report_create`")?; if !result.exists.unwrap_or(false) { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Version could not be found: {}", new_report.item_id )))); @@ -172,7 +173,7 @@ pub async fn report_create( ItemType::User => { let user_id = UserId( parse_base62(new_report.item_id.as_str()) - .wrap_request_err("parsing reported user ID")?, + .request_context("parsing reported user ID")?, ); let result = sqlx::query!( @@ -181,10 +182,10 @@ pub async fn report_create( ) .fetch_one(&mut transaction) .await - .wrap_internal_err("querying database for `report_create`")?; + .internal_context("querying database for `report_create`")?; if !result.exists.unwrap_or(false) { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "User could not be found: {}", new_report.item_id )))); @@ -195,7 +196,7 @@ pub async fn report_create( ItemType::Organization => { let organization_id = OrganizationId( parse_base62(new_report.item_id.as_str()) - .wrap_request_err("parsing reported organization ID")?, + .request_context("parsing reported organization ID")?, ); let result = sqlx::query!( @@ -204,10 +205,10 @@ pub async fn report_create( ) .fetch_one(&mut transaction) .await - .wrap_internal_err("querying database for `report_create`")?; + .internal_context("querying database for `report_create`")?; if !result.exists.unwrap_or(false) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Organization could not be found: {}", new_report.item_id ))); @@ -220,16 +221,16 @@ pub async fn report_create( let (instance_part, version_part) = new_report .item_id .split_once('/') - .wrap_request_err_with(|| "shared instance reports must format the item ID as `instance_id/version_id`" + .request_context_with(|| "shared instance reports must format the item ID as `instance_id/version_id`" .to_string())?; let shared_instance_id = SharedInstanceId( parse_base62(instance_part) - .wrap_request_err("parsing reported shared instance ID")? + .request_context("parsing reported shared instance ID")? as i64, ); let shared_instance_version_id: i32 = - version_part.parse().wrap_request_err(format!( + version_part.parse().request_context(format!( "shared instance version is not a number: `{version_part}`" ))?; @@ -244,12 +245,12 @@ pub async fn report_create( .bearer_auth(&ENV.SHARED_INSTANCES_KEY) .send() .await - .wrap_internal_err( + .internal_context( "failed to reach the shared instance service (instance lookup)", )?; if !instance_response.status().is_success() { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Shared instance could not be found: {instance_part}" )))); } @@ -259,10 +260,10 @@ pub async fn report_create( .bearer_auth(&ENV.SHARED_INSTANCES_KEY) .send() .await - .wrap_internal_err("failed to reach the shared instance service (version lookup)")?; + .internal_context("failed to reach the shared instance service (version lookup)")?; if !version_response.status().is_success() { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Shared instance version could not be found: {instance_part}/{version_part}" )))); } @@ -271,7 +272,7 @@ pub async fn report_create( report.shared_instance_version_id = Some(shared_instance_version_id) } ItemType::Unknown => { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Invalid report item type: {}", new_report.item_type.as_str() )))); @@ -281,19 +282,19 @@ pub async fn report_create( report .insert(&mut transaction) .await - .wrap_internal_err("inserting database records for `report_create`")?; + .internal_context("inserting database records for `report_create`")?; for image_id in new_report.uploaded_images { if let Some(db_image) = image_item::DBImage::get(image_id.into(), &mut transaction, &redis) .await - .wrap_internal_err("fetching image from database")? + .internal_context("fetching image from database")? { let image: Image = db_image.into(); if !matches!(image.context, ImageContext::Report { .. }) || image.context.inner_id().is_some() { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Image {image_id} is not unused and in the 'report' context" )))); } @@ -309,13 +310,13 @@ pub async fn report_create( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `report_create`")?; + .internal_context("querying database for `report_create`")?; image_item::DBImage::clear_cache(image.id.into(), &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } else { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Image {image_id} could not be found" )))); } @@ -329,7 +330,7 @@ pub async fn report_create( } .insert(&mut transaction) .await - .wrap_internal_err("inserting database records for `report_create`")?; + .internal_context("inserting database records for `report_create`")?; // Notify the reporter that the report has been submitted NotificationBuilder { @@ -339,12 +340,12 @@ pub async fn report_create( } .insert(current_user.id.into(), &mut transaction, &redis) .await - .wrap_internal_err("inserting database records for `report_create`")?; + .internal_context("inserting database records for `report_create`")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::Ok().json(Report { id: id.into(), @@ -415,7 +416,7 @@ pub async fn reports( Scopes::REPORT_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; use futures::stream::TryStreamExt; @@ -424,7 +425,7 @@ pub async fn reports( .as_deref() .map(parse_base62) .transpose() - .wrap_request_err("parsing `item_id`")? + .request_context("parsing `item_id`")? .map(|id| id as i64); let report_ids = if scopes.contains(Scopes::MODERATION_READ) @@ -450,7 +451,7 @@ pub async fn reports( .map_ok(|m| crate::database::models::ids::DBReportId(m.id)) .try_collect::>() .await - .wrap_internal_err("fetching report IDs from database")? + .internal_context("fetching report IDs from database")? } else { sqlx::query!( r#" @@ -473,7 +474,7 @@ pub async fn reports( .map_ok(|m| crate::database::models::ids::DBReportId(m.id)) .try_collect::>() .await - .wrap_internal_err("querying database for `reports`")? + .internal_context("querying database for `reports`")? }; let query_reports = @@ -482,7 +483,7 @@ pub async fn reports( &**pool, ) .await - .wrap_internal_err("fetching reports from database")?; + .internal_context("fetching reports from database")?; let mut reports: Vec = Vec::new(); @@ -523,7 +524,7 @@ pub async fn reports_get( ) -> Result { let report_ids: Vec = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(|x| x.into()) .collect(); @@ -534,7 +535,7 @@ pub async fn reports_get( &**pool, ) .await - .wrap_internal_err("fetching reports from database")?; + .internal_context("fetching reports from database")?; let UserWithScopes { user, scopes } = get_user_from_headers( &req, @@ -544,7 +545,7 @@ pub async fn reports_get( Scopes::REPORT_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let all_reports = reports_data .into_iter() @@ -585,25 +586,25 @@ pub async fn report_get( Scopes::REPORT_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id = info.into_inner().0.into(); let report = crate::database::models::report_item::DBReport::get(id, &**pool) .await - .wrap_internal_err("fetching report from database")?; + .internal_context("fetching report from database")?; if let Some(report) = report { if !scopes.contains(Scopes::MODERATION_READ) && report.reporter != user.id.into() { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let report: Report = report.into(); Ok(HttpResponse::Ok().json(report)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -643,25 +644,25 @@ pub async fn report_edit( Scopes::REPORT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id = info.into_inner().0.into(); let report = crate::database::models::report_item::DBReport::get(id, &**pool) .await - .wrap_internal_err("fetching report from database")?; + .internal_context("fetching report from database")?; if let Some(report) = report { if !scopes.contains(Scopes::MODERATION_WRITE) && report.reporter != user.id.into() { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(edit_body) = &edit_report.body { sqlx::query!( @@ -675,12 +676,12 @@ pub async fn report_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("updating edit body in database")?; + .internal_context("updating edit body in database")?; } if let Some(edit_closed) = edit_report.closed { if !scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot reopen a report!", ))); } @@ -697,9 +698,7 @@ pub async fn report_edit( } .insert(&mut transaction) .await - .wrap_internal_err( - "inserting database records for `report_edit`", - )?; + .internal_context("inserting database records for `report_edit`")?; NotificationBuilder { body: NotificationBody::ReportStatusUpdated { @@ -708,9 +707,7 @@ pub async fn report_edit( } .insert(report.reporter, &mut transaction, &redis) .await - .wrap_internal_err( - "inserting database records for `report_edit`", - )?; + .internal_context("inserting database records for `report_edit`")?; sqlx::query!( " @@ -723,7 +720,7 @@ pub async fn report_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("updating database records for `report_edit`")?; + .internal_context("updating database records for `report_edit`")?; } // delete any images no longer in the body @@ -741,16 +738,16 @@ pub async fn report_edit( &redis, ) .await - .wrap_api_err("deleting unused images")?; + .api_context("deleting unused images")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -781,12 +778,12 @@ pub async fn report_delete( Scopes::REPORT_DELETE | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let id = info.into_inner().0; let context = ImageContext::Report { @@ -797,11 +794,11 @@ pub async fn report_delete( &mut transaction, ) .await - .wrap_internal_err("fetching images from database")?; + .internal_context("fetching images from database")?; for image in uploaded_images { image_item::DBImage::remove(image.id, &mut transaction, &redis) .await - .wrap_internal_err("deleting image from database")?; + .internal_context("deleting image from database")?; } let result = crate::database::models::report_item::DBReport::remove_full( @@ -809,15 +806,15 @@ pub async fn report_delete( &mut transaction, ) .await - .wrap_internal_err("deleting report from database")?; + .internal_context("deleting report from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; if result.is_some() { Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/routes/v3/statistics.rs b/apps/labrinth/src/routes/v3/statistics.rs index d98c3071315..0a5dee0f632 100644 --- a/apps/labrinth/src/routes/v3/statistics.rs +++ b/apps/labrinth/src/routes/v3/statistics.rs @@ -39,7 +39,7 @@ pub async fn get_stats( ) .fetch_one(&***ro_pool) .await - .wrap_internal_err("counting projects")?; + .internal_context("counting projects")?; let versions = sqlx::query!( " @@ -59,7 +59,7 @@ pub async fn get_stats( ) .fetch_one(&***ro_pool) .await - .wrap_internal_err("counting versions")?; + .internal_context("counting versions")?; let authors = sqlx::query!( " @@ -75,7 +75,7 @@ pub async fn get_stats( ) .fetch_one(&***ro_pool) .await - .wrap_internal_err("counting project authors")?; + .internal_context("counting project authors")?; let files = sqlx::query!( " @@ -94,7 +94,7 @@ pub async fn get_stats( ) .fetch_one(&***ro_pool) .await - .wrap_internal_err("counting version files")?; + .internal_context("counting version files")?; let v3_stats = V3Stats { projects: projects.count, diff --git a/apps/labrinth/src/routes/v3/tags.rs b/apps/labrinth/src/routes/v3/tags.rs index fd5e8a8c14c..89007dfb46f 100644 --- a/apps/labrinth/src/routes/v3/tags.rs +++ b/apps/labrinth/src/routes/v3/tags.rs @@ -1,5 +1,6 @@ use crate::util::MinecraftMeta; use crate::util::error::Context as _; +use anyhow::anyhow; use std::collections::HashMap; use super::ApiError; @@ -54,7 +55,7 @@ pub async fn category_list( ) -> Result { let results = Category::list(&**pool, &redis) .await - .wrap_internal_err("fetching category from Redis")? + .internal_context("fetching category from Redis")? .into_iter() .map(|x| CategoryData { icon: x.icon, @@ -92,7 +93,7 @@ pub async fn loader_list( ) -> Result { let loaders = Loader::list(&**pool, &redis) .await - .wrap_internal_err("fetching loader from Redis")?; + .internal_context("fetching loader from Redis")?; let mut results = loaders .into_iter() @@ -202,7 +203,7 @@ pub async fn loader_fields_list( }) .collect(), _ => { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "`{}` is not a valid loader field", query.loader_field ))); @@ -291,7 +292,7 @@ pub async fn license_text( })); } - Err(ApiError::Request(eyre::eyre!( + Err(ApiError::Request(anyhow!( "Invalid SPDX identifier specified", ))) } @@ -339,7 +340,7 @@ pub async fn report_type_list( ) -> Result { let results = ReportType::list(&**pool, &redis) .await - .wrap_internal_err("reading HTTP response body")?; + .internal_context("reading HTTP response body")?; Ok(HttpResponse::Ok().json(results)) } @@ -358,6 +359,6 @@ pub async fn project_type_list( ) -> Result { let results = ProjectType::list(&**pool, &redis) .await - .wrap_internal_err("fetching project type from Redis")?; + .internal_context("fetching project type from Redis")?; Ok(HttpResponse::Ok().json(results)) } diff --git a/apps/labrinth/src/routes/v3/teams.rs b/apps/labrinth/src/routes/v3/teams.rs index 1d67e5b456c..82b4b7a3a2b 100644 --- a/apps/labrinth/src/routes/v3/teams.rs +++ b/apps/labrinth/src/routes/v3/teams.rs @@ -16,6 +16,7 @@ use crate::routes::ApiError; use crate::util::error::ApiContext as _; use crate::util::error::Context; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, post, web}; +use anyhow::anyhow; use ariadne::ids::UserId; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; @@ -52,7 +53,7 @@ async fn affected_project_ids( .map(|project_ids| { project_ids.into_iter().map(DBProjectId).collect() }) - .wrap_internal_err("fetching projects affected by team mutation") + .internal_context("fetching projects affected by team mutation") } } } @@ -103,7 +104,7 @@ pub async fn team_members_get_project_internal( let project_data = crate::database::models::DBProject::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; if let Some(project) = project_data { let current_user = get_user_from_headers( @@ -118,9 +119,9 @@ pub async fn team_members_get_project_internal( if !is_visible_project(&project.inner, ¤t_user, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let members_data = DBTeamMember::get_from_team_full( project.inner.team_id, @@ -128,14 +129,14 @@ pub async fn team_members_get_project_internal( &redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = DBUser::get_many_ids( &members_data.iter().map(|x| x.user_id).collect::>(), &**pool, &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let user_id = current_user.as_ref().map(|x| x.user.id.into()); let logged_in = if let Some(user_id) = user_id { @@ -146,7 +147,7 @@ pub async fn team_members_get_project_internal( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; team_member.is_some() || organization_team_member.is_some() } else { @@ -175,7 +176,7 @@ pub async fn team_members_get_project_internal( Ok(HttpResponse::Ok().json(team_members)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -192,7 +193,7 @@ pub async fn team_members_get_organization( let organization_data = crate::database::models::DBOrganization::get(&string, &**pool, &redis) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; let current_user = get_user_from_headers( &req, @@ -207,7 +208,7 @@ pub async fn team_members_get_organization( if let Some(organization) = organization_data && is_visible_organization(&organization, ¤t_user, &pool, &redis) .await - .wrap_api_err("checking organization visibility")? + .api_context("checking organization visibility")? { let members_data = DBTeamMember::get_from_team_full( organization.team_id, @@ -215,14 +216,14 @@ pub async fn team_members_get_organization( &redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = crate::database::models::DBUser::get_many_ids( &members_data.iter().map(|x| x.user_id).collect::>(), &**pool, &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let user_id = current_user.as_ref().map(|x| x.user.id.into()); @@ -256,7 +257,7 @@ pub async fn team_members_get_organization( Ok(HttpResponse::Ok().json(team_members)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -284,14 +285,14 @@ pub async fn team_members_get( let members_data = DBTeamMember::get_from_team_full(id.into(), &**pool, &redis) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = crate::database::models::DBUser::get_many_ids( &members_data.iter().map(|x| x.user_id).collect::>(), &**pool, &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let current_user = get_user_from_headers( &req, @@ -366,7 +367,7 @@ pub async fn teams_get( use itertools::Itertools; let team_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(|x| x.into()) .collect::>(); @@ -374,14 +375,14 @@ pub async fn teams_get( let teams_data = DBTeamMember::get_from_team_full_many(&team_ids, &**pool, &redis) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = crate::database::models::DBUser::get_many_ids( &teams_data.iter().map(|x| x.user_id).collect::>(), &**pool, &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let current_user = get_user_from_headers( &req, @@ -456,7 +457,7 @@ pub async fn join_team( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let member = DBTeamMember::get_from_user_id_pending( team_id, @@ -464,18 +465,18 @@ pub async fn join_team( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; if let Some(member) = member { if member.accepted { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You are already a member of this team", ))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; // Edit Team Member to set Accepted to True DBTeamMember::edit_team_member( @@ -491,21 +492,21 @@ pub async fn join_team( &mut transaction, ) .await - .wrap_internal_err("updating team member in database")?; + .internal_context("updating team member in database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBUser::clear_project_cache(&[current_user.user.id.into()], &redis) .await - .wrap_internal_err("clearing cached user in Redis")?; + .internal_context("clearing cached user in Redis")?; DBTeamMember::clear_cache(team_id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "There is no pending request from this team", ))); } @@ -563,7 +564,7 @@ pub async fn add_team_member( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let current_user = get_user_from_headers( &req, @@ -573,11 +574,11 @@ pub async fn add_team_member( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let team_association = DBTeam::get_association(team_id, &**pool) .await - .wrap_internal_err("fetching team from database")? - .wrap_request_err_with(|| { + .internal_context("fetching team from database")? + .request_context_with(|| { "the team specified does not exist".to_string() })?; let member = DBTeamMember::get_from_user_id( @@ -586,7 +587,7 @@ pub async fn add_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; match team_association { // If team is associated with a project, check if they have permissions to invite users to that project TeamAssociationId::Project(pid) => { @@ -595,7 +596,7 @@ pub async fn add_team_member( pid, &**pool, ) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; let organization_team_member = if let Some(organization) = &organization { DBTeamMember::get_from_user_id( @@ -604,7 +605,7 @@ pub async fn add_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? } else { None }; @@ -616,18 +617,18 @@ pub async fn add_team_member( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::MANAGE_INVITES) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to invite users to this team", ))); } if !permissions.contains(new_member.permissions) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The new member has permissions that you don't have", ))); } if new_member.organization_permissions.is_some() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The organization permissions of a project team member cannot be set", ))); } @@ -643,14 +644,14 @@ pub async fn add_team_member( if !organization_permissions .contains(OrganizationPermissions::MANAGE_INVITES) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to invite users to this organization", ))); } if !organization_permissions.contains( new_member.organization_permissions.unwrap_or_default(), ) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The new member has organization permissions that you don't have", ))); } @@ -658,7 +659,7 @@ pub async fn add_team_member( OrganizationPermissions::EDIT_MEMBER_DEFAULT_PERMISSIONS, ) && !new_member.permissions.is_empty() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to give this user default project permissions. Ensure 'permissions' is set if it is not, and empty (0).", ))); } @@ -668,7 +669,7 @@ pub async fn add_team_member( if new_member.payouts_split < Decimal::ZERO || new_member.payouts_split > Decimal::from(5000) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Payouts split must be between 0 and 5000!", ))); } @@ -679,15 +680,15 @@ pub async fn add_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; if let Some(req) = request { if req.accepted { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The user is already a member of that team", ))); } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "There is already a pending member request for this user", ))); } @@ -698,8 +699,8 @@ pub async fn add_team_member( &redis, ) .await - .wrap_internal_err("fetching user from database")? - .wrap_request_err_with(|| "an invalid User ID specified".to_string())?; + .internal_context("fetching user from database")? + .request_context_with(|| "an invalid User ID specified".to_string())?; let mut force_accepted = false; if let TeamAssociationId::Project(pid) = team_association { @@ -709,7 +710,7 @@ pub async fn add_team_member( pid, &**pool, ) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; let new_user_organization_team_member = if let Some(organization) = &organization { DBTeamMember::get_from_user_id( @@ -718,7 +719,7 @@ pub async fn add_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? } else { None }; @@ -727,7 +728,7 @@ pub async fn add_team_member( .is_some_and(|tm| tm.is_owner) && new_member.permissions != ProjectPermissions::all() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot override the owner of an organization's permissions in a project team", ))); } @@ -744,7 +745,7 @@ pub async fn add_team_member( let new_id = crate::database::models::ids::generate_team_member_id(&mut transaction) .await - .wrap_internal_err("generating team member ID")?; + .internal_context("generating team member ID")?; DBTeamMember { id: new_id, team_id, @@ -759,7 +760,7 @@ pub async fn add_team_member( } .insert(&mut transaction) .await - .wrap_internal_err("inserting database records for `add_team_member`")?; + .internal_context("inserting database records for `add_team_member`")?; // If the user has an opportunity to accept the invite, send a notification if !force_accepted { @@ -775,7 +776,7 @@ pub async fn add_team_member( } .insert(new_member.user_id.into(), &mut transaction, &redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `add_team_member`", )?; } @@ -790,7 +791,7 @@ pub async fn add_team_member( } .insert(new_member.user_id.into(), &mut transaction, &redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `add_team_member`", )?; } @@ -809,10 +810,10 @@ pub async fn add_team_member( .await?; DBTeamMember::clear_cache(team_id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; DBUser::clear_project_cache(&[new_member.user_id.into()], &redis) .await - .wrap_internal_err("clearing cached user in Redis")?; + .internal_context("clearing cached user in Redis")?; Ok(HttpResponse::NoContent().body("")) } @@ -852,8 +853,8 @@ pub async fn edit_team_member( let user_id = DBUser::get(&ids.1, &**pool, &redis) .await - .wrap_internal_err("failed to fetch the specified user")? - .wrap_request_err("the specified user does not exist")? + .internal_context("failed to fetch the specified user")? + .request_context("the specified user does not exist")? .id; let current_user = get_user_from_headers( @@ -864,24 +865,24 @@ pub async fn edit_team_member( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let team_association = DBTeam::get_association(id, &**pool) .await - .wrap_internal_err("failed to fetch the specified team")? - .wrap_request_err("the specified team does not exist")?; + .internal_context("failed to fetch the specified team")? + .request_context("the specified team does not exist")?; let member = DBTeamMember::get_from_user_id( id, current_user.user.id.into(), &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; let edit_member_db = DBTeamMember::get_from_user_id_pending(id, user_id, &**pool) .await - .wrap_internal_err("failed to fetch team member")? - .wrap_request_err( + .internal_context("failed to fetch team member")? + .request_context( "this member does not exist in this team - \ the member must first be created via `POST`", )?; @@ -889,13 +890,13 @@ pub async fn edit_team_member( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if edit_member_db.is_owner && (edit_member.permissions.is_some() || edit_member.organization_permissions.is_some()) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The owner's permission's in a team cannot be edited", ))); } @@ -907,7 +908,7 @@ pub async fn edit_team_member( project_id, &**pool, ) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; let organization_team_member = if let Some(organization) = &organization { DBTeamMember::get_from_user_id( @@ -916,7 +917,7 @@ pub async fn edit_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? } else { None }; @@ -929,7 +930,7 @@ pub async fn edit_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? } else { None }; @@ -941,7 +942,7 @@ pub async fn edit_team_member( .permissions .is_some_and(|x| x != ProjectPermissions::all()) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You cannot override the project permissions of the organization owner!", ))); } @@ -953,7 +954,7 @@ pub async fn edit_team_member( ) .unwrap_or_default(); if !permissions.contains(ProjectPermissions::EDIT_MEMBER) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit members of this team", ))); } @@ -961,13 +962,13 @@ pub async fn edit_team_member( if let Some(new_permissions) = edit_member.permissions && !permissions.contains(new_permissions) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The new permissions have permissions that you don't have", ))); } if edit_member.organization_permissions.is_some() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The organization permissions of a project team member cannot be edited", ))); } @@ -983,7 +984,7 @@ pub async fn edit_team_member( if !organization_permissions .contains(OrganizationPermissions::EDIT_MEMBER) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit members of this team", ))); } @@ -991,7 +992,7 @@ pub async fn edit_team_member( if let Some(new_permissions) = edit_member.organization_permissions && !organization_permissions.contains(new_permissions) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The new organization permissions have permissions that you don't have", ))); } @@ -1001,7 +1002,7 @@ pub async fn edit_team_member( OrganizationPermissions::EDIT_MEMBER_DEFAULT_PERMISSIONS, ) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to give this user default project permissions.", ))); } @@ -1012,7 +1013,7 @@ pub async fn edit_team_member( && (payouts_split < Decimal::ZERO || payouts_split > Decimal::from(5000)) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Payouts split must be between 0 and 5000!", ))); } @@ -1030,7 +1031,7 @@ pub async fn edit_team_member( &mut transaction, ) .await - .wrap_internal_err("updating team member in database")?; + .internal_context("updating team member in database")?; let affected_project_ids = affected_project_ids(team_association, &mut transaction).await?; @@ -1044,7 +1045,7 @@ pub async fn edit_team_member( .await?; DBTeamMember::clear_cache(id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } @@ -1085,22 +1086,22 @@ pub async fn transfer_ownership( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; // Forbid transferring ownership of a project team that is owned by an organization // These are owned by the organization owner, and must be removed from the organization first // There shouldnt be an owner on these projects in these cases, but just in case. let team_association_id = DBTeam::get_association(id.into(), &**pool) .await - .wrap_internal_err("fetching team from database")?; + .internal_context("fetching team from database")?; if let Some(TeamAssociationId::Project(pid)) = team_association_id { let result = DBProject::get_id(pid, &**pool, &redis) .await - .wrap_internal_err("fetching project for ownership transfer")?; + .internal_context("fetching project for ownership transfer")?; if let Some(project_item) = result && project_item.inner.organization_id.is_some() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You cannot transfer ownership of a project team that is owned by an organization", ))); } @@ -1113,13 +1114,13 @@ pub async fn transfer_ownership( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? - .wrap_auth_err_with(|| { + .internal_context("fetching team member from database")? + .auth_context_with(|| { "you don't have permission to edit members of this team".to_string() })?; if !member.is_owner { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit the ownership of this team", ))); } @@ -1131,13 +1132,13 @@ pub async fn transfer_ownership( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? - .wrap_request_err_with(|| { + .internal_context("fetching team member from database")? + .request_context_with(|| { "the new owner specified does not exist".to_string() })?; if !new_member.accepted { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You can only transfer ownership to members who are currently in your team", ))); } @@ -1145,13 +1146,13 @@ pub async fn transfer_ownership( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; // The following are the only places new_is_owner is modified. if let Some(former_owner) = DBTeamMember::get_from_team_full(id.into(), &**pool, &redis) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? .into_iter() .find(|x| x.is_owner) { @@ -1168,7 +1169,7 @@ pub async fn transfer_ownership( &mut transaction, ) .await - .wrap_internal_err("updating team member in database")?; + .internal_context("updating team member in database")?; } DBTeamMember::edit_team_member( @@ -1191,7 +1192,7 @@ pub async fn transfer_ownership( &mut transaction, ) .await - .wrap_internal_err("updating database records for `transfer_ownership`")?; + .internal_context("updating database records for `transfer_ownership`")?; let project_teams_edited = if let Some(TeamAssociationId::Organization(oid)) = team_association_id @@ -1211,7 +1212,7 @@ pub async fn transfer_ownership( ) .fetch_all(&mut transaction) .await - .wrap_internal_err("fetching team IDs from database")?; + .internal_context("fetching team IDs from database")?; let team_ids: Vec = team_ids @@ -1227,7 +1228,7 @@ pub async fn transfer_ownership( &mut transaction, ) .await - .wrap_internal_err("deleting team member from database")?; + .internal_context("deleting team member from database")?; } team_ids @@ -1246,7 +1247,7 @@ pub async fn transfer_ownership( } .insert(new_owner.user_id.into(), &mut transaction, &redis) .await - .wrap_internal_err( + .internal_context( "inserting database records for `transfer_ownership`", )?; } @@ -1266,16 +1267,16 @@ pub async fn transfer_ownership( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; } DBTeamMember::clear_cache(id.into(), &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; for team_id in project_teams_edited { DBTeamMember::clear_cache(team_id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } Ok(HttpResponse::NoContent().body("")) @@ -1312,12 +1313,12 @@ pub async fn remove_team_member( Scopes::PROJECT_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let team_association = DBTeam::get_association(id, &**pool) .await - .wrap_internal_err("fetching team from database")? - .wrap_request_err_with(|| { + .internal_context("fetching team from database")? + .request_context_with(|| { "the team specified does not exist".to_string() })?; let member = DBTeamMember::get_from_user_id( @@ -1326,17 +1327,17 @@ pub async fn remove_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; let delete_member = DBTeamMember::get_from_user_id_pending(id, user_id, &**pool) .await - .wrap_internal_err("deleting team member from database")?; + .internal_context("deleting team member from database")?; if let Some(delete_member) = delete_member { if delete_member.is_owner { // The owner cannot be removed from a team - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "The owner can't be removed from a team", ))); } @@ -1344,7 +1345,7 @@ pub async fn remove_team_member( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; // Organization attached to a project this team is attached to match team_association { @@ -1354,7 +1355,7 @@ pub async fn remove_team_member( pid, &**pool, ) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; let organization_team_member = if let Some(organization) = &organization { @@ -1364,7 +1365,7 @@ pub async fn remove_team_member( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? } else { None }; @@ -1387,11 +1388,11 @@ pub async fn remove_team_member( { DBTeamMember::delete(id, user_id, &mut transaction) .await - .wrap_internal_err( + .internal_context( "deleting team member from database", )?; } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to remove a member from this team", ))); } @@ -1405,9 +1406,9 @@ pub async fn remove_team_member( // permission can remove it. DBTeamMember::delete(id, user_id, &mut transaction) .await - .wrap_internal_err("deleting team member from database")?; + .internal_context("deleting team member from database")?; } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to cancel a team invite", ))); } @@ -1429,11 +1430,11 @@ pub async fn remove_team_member( { DBTeamMember::delete(id, user_id, &mut transaction) .await - .wrap_internal_err( + .internal_context( "deleting team member from database", )?; } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to remove a member from this organization", ))); } @@ -1447,9 +1448,9 @@ pub async fn remove_team_member( // permission can remove it. DBTeamMember::delete(id, user_id, &mut transaction) .await - .wrap_internal_err("deleting team member from database")?; + .internal_context("deleting team member from database")?; } else { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to cancel an organization invite", ))); } @@ -1469,13 +1470,13 @@ pub async fn remove_team_member( DBTeamMember::clear_cache(id, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; DBUser::clear_project_cache(&[delete_member.user_id], &redis) .await - .wrap_internal_err("deleting user from database")?; + .internal_context("deleting user from database")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/routes/v3/threads.rs b/apps/labrinth/src/routes/v3/threads.rs index bc28220cfe0..ed1e2fed5a5 100644 --- a/apps/labrinth/src/routes/v3/threads.rs +++ b/apps/labrinth/src/routes/v3/threads.rs @@ -26,6 +26,7 @@ use crate::util::error::Context as _; use actix_web::{ HttpRequest, HttpResponse, delete, get, patch, post, put, web, }; +use anyhow::anyhow; use futures::TryStreamExt; use serde::Deserialize; use xredis::RedisPool; @@ -62,7 +63,7 @@ pub async fn is_authorized_thread( user_id as database::models::ids::DBUserId, ) .fetch_one(pool) - .await.wrap_internal_err("fetching report exists from database")? + .await.internal_context("fetching report exists from database")? .exists; report_exists.unwrap_or(false) @@ -78,7 +79,7 @@ pub async fn is_authorized_thread( user_id as database::models::ids::DBUserId, ) .fetch_one(pool) - .await.wrap_internal_err("fetching project exists from database")? + .await.internal_context("fetching project exists from database")? .exists; if !project_exists.unwrap_or(false) { @@ -88,7 +89,7 @@ pub async fn is_authorized_thread( user_id as database::models::ids::DBUserId, ) .fetch_one(pool) - .await.wrap_internal_err("fetching organization exists from database")? + .await.internal_context("fetching organization exists from database")? .exists; org_exists.unwrap_or(false) @@ -156,7 +157,7 @@ pub async fn filter_authorized_threads( }); }) .try_collect::>() - .await.wrap_internal_err("fetching query results from database")?; + .await.internal_context("fetching query results from database")?; } let mut org_project_thread_ids = check_threads @@ -188,7 +189,7 @@ pub async fn filter_authorized_threads( }); }) .try_collect::>() - .await.wrap_internal_err("fetching query results from database")?; + .await.internal_context("fetching query results from database")?; } let report_thread_ids = check_threads @@ -220,7 +221,7 @@ pub async fn filter_authorized_threads( }) .try_collect::>() .await - .wrap_internal_err("fetching query results from database")?; + .internal_context("fetching query results from database")?; } } @@ -243,7 +244,7 @@ pub async fn filter_authorized_threads( let users: Vec = database::models::DBUser::get_many_ids(&user_ids, &***pool, redis) .await - .wrap_internal_err("fetching users from database")? + .internal_context("fetching users from database")? .into_iter() .map(From::from) .collect(); @@ -307,7 +308,7 @@ pub async fn thread_get( let thread_data = database::models::DBThread::get(string, &**pool) .await - .wrap_internal_err("fetching thread from database")?; + .internal_context("fetching thread from database")?; let user = get_user_from_headers( &req, @@ -317,12 +318,12 @@ pub async fn thread_get( Scopes::THREAD_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if let Some(mut data) = thread_data && is_authorized_thread(&data, &user, Scopes::MODERATION_READ, &pool) .await - .wrap_api_err("checking thread authorization")? + .api_context("checking thread authorization")? { let is_moderator = user.scopes.contains(Scopes::MODERATION_READ); let authors = &mut data.members; @@ -347,14 +348,14 @@ pub async fn thread_get( let users: Vec = database::models::DBUser::get_many_ids(authors, &**pool, &redis) .await - .wrap_internal_err("fetching users from database")? + .internal_context("fetching users from database")? .into_iter() .map(From::from) .collect(); return Ok(HttpResponse::Ok().json(Thread::from(data, users, &user))); } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } #[derive(Deserialize)] @@ -393,11 +394,11 @@ pub async fn threads_get( Scopes::THREAD_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let thread_ids: Vec = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(|x| x.into()) .collect(); @@ -405,11 +406,11 @@ pub async fn threads_get( let threads_data = database::models::DBThread::get_many(&thread_ids, &**pool) .await - .wrap_internal_err("fetching threads from database")?; + .internal_context("fetching threads from database")?; let threads = filter_authorized_threads(threads_data, &user, &pool, &redis) .await - .wrap_api_err("filtering authorized threads")?; + .api_context("filtering authorized threads")?; Ok(HttpResponse::Ok().json(threads)) } @@ -446,7 +447,7 @@ async fn thread_project_id( ) .fetch_optional(pool) .await - .wrap_internal_err("fetching thread project")? + .internal_context("fetching thread project")? .flatten() .map(database::models::DBProjectId)) } @@ -466,7 +467,7 @@ async fn thread_issue_project_id( ) .fetch_optional(pool) .await - .wrap_internal_err("fetching thread issue project")? + .internal_context("fetching thread issue project")? .flatten() .map(database::models::DBProjectId)) } @@ -495,7 +496,7 @@ async fn thread_issue_facet_context( ) .fetch_optional(pool) .await - .wrap_internal_err("fetching thread issue facet context")? + .internal_context("fetching thread issue facet context")? .and_then(|row| { row.mod_id.map(|project_id| ThreadIssueFacetContext { project_id: database::models::DBProjectId(project_id), @@ -516,7 +517,7 @@ async fn project_exists( ) .fetch_one(pool) .await - .wrap_internal_err("checking whether thread issue project exists") + .internal_context("checking whether thread issue project exists") } async fn is_project_team_member( @@ -553,7 +554,7 @@ async fn is_project_team_member( ) .fetch_one(&mut *transaction) .await - .wrap_internal_err("checking project team membership") + .internal_context("checking project team membership") } async fn prepare_thread_issue_mutation( @@ -569,7 +570,7 @@ async fn prepare_thread_issue_mutation( sqlx::query!("SELECT pg_advisory_xact_lock($1)", project_id.0) .fetch_one(&mut *transaction) .await - .wrap_internal_err("locking project thread issues")?; + .internal_context("locking project thread issues")?; Ok(()) } @@ -596,11 +597,11 @@ pub async fn thread_issues_create( Scopes::THREAD_WRITE | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; if new_issues.issues.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "must provide at least one thread issue" ))); } @@ -609,7 +610,7 @@ pub async fn thread_issues_create( .iter() .any(|issue| issue.facets.is_empty()) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "each thread issue must have at least one facet" ))); } @@ -617,14 +618,14 @@ pub async fn thread_issues_create( let thread_id: database::models::DBThreadId = info.into_inner().0.into(); let project_id = thread_project_id(thread_id, &pool) .await? - .wrap_not_found_err("resource not found")?; + .not_found_context("resource not found")?; if !project_exists(project_id, &pool).await? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; prepare_thread_issue_mutation(project_id, &mut transaction).await?; database::models::DBThreadIssue::insert_many( @@ -645,7 +646,7 @@ pub async fn thread_issues_create( &mut transaction, ) .await - .wrap_internal_err("creating thread issues")?; + .internal_context("creating thread issues")?; super::projects::mutation::finalize_mutation( project_id, @@ -672,12 +673,12 @@ pub async fn thread_issue_facet_edit( web::Json(edit): web::Json, ) -> Result<(), ApiError> { if edit.user_addressed.is_none() && edit.moderator_verified.is_none() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "must provide a thread issue field to update" ))); } if edit.moderator_verified == Some(false) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "a verified thread issue cannot be unverified" ))); } @@ -690,26 +691,26 @@ pub async fn thread_issue_facet_edit( Scopes::THREAD_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let facet_id: database::models::DBThreadIssueFacetId = info.into_inner().0.into(); let facet_context = thread_issue_facet_context(facet_id, &pool) .await? - .wrap_not_found_err("resource not found")?; + .not_found_context("resource not found")?; let project_id = facet_context.project_id; let project_exists = project_exists(project_id, &pool).await?; if edit.moderator_verified.is_some() && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "only moderators can verify thread issues" ))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if project_exists { prepare_thread_issue_mutation(project_id, &mut transaction).await?; } @@ -722,7 +723,7 @@ pub async fn thread_issue_facet_edit( ) .await? { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "only project team members or moderators can address thread issues" ))); } @@ -740,9 +741,9 @@ pub async fn thread_issue_facet_edit( &mut transaction, ) .await - .wrap_internal_err("checking project team reply requirement")? + .internal_context("checking project team reply requirement")? { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "a project team member must send a message in the thread before addressing this issue" ))); } @@ -756,9 +757,9 @@ pub async fn thread_issue_facet_edit( .await?; if !state .can_address_facet(facet_id) - .wrap_not_found_err("resource not found")? + .not_found_context("resource not found")? { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "moderation issue requirements must be changed before addressing the issue" ))); } @@ -770,9 +771,9 @@ pub async fn thread_issue_facet_edit( &mut transaction, ) .await - .wrap_internal_err("updating thread issue")?; + .internal_context("updating thread issue")?; if !updated { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } if project_exists { @@ -790,7 +791,7 @@ pub async fn thread_issue_facet_edit( transaction .commit() .await - .wrap_internal_err("committing thread issue update") + .internal_context("committing thread issue update") } } @@ -811,26 +812,26 @@ pub async fn thread_issue_delete( Scopes::THREAD_WRITE | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let issue_id: database::models::DBThreadIssueId = info.into_inner().0.into(); let project_id = thread_issue_project_id(issue_id, &pool) .await? - .wrap_not_found_err("resource not found")?; + .not_found_context("resource not found")?; let project_exists = project_exists(project_id, &pool).await?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if project_exists { prepare_thread_issue_mutation(project_id, &mut transaction).await?; } if !database::models::DBThreadIssue::remove(issue_id, &mut transaction) .await - .wrap_internal_err("deleting thread issue")? + .internal_context("deleting thread issue")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } if project_exists { @@ -846,7 +847,7 @@ pub async fn thread_issue_delete( transaction .commit() .await - .wrap_internal_err("committing thread issue deletion") + .internal_context("committing thread issue deletion") } } @@ -885,7 +886,7 @@ pub async fn thread_send_message( Scopes::THREAD_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; thread_send_message_internal( &user, @@ -895,7 +896,7 @@ pub async fn thread_send_message( &redis, ) .await - .wrap_api_err("sending thread message")?; + .api_context("sending thread message")?; Ok(HttpResponse::NoContent().finish()) } @@ -918,13 +919,11 @@ pub async fn thread_send_message_internal( } = &new_message.body { if body.len() > 65536 { - return Err(ApiError::Request(eyre::eyre!( - "Input body is too long!", - ))); + return Err(ApiError::Request(anyhow!("Input body is too long!",))); } if *private && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You are not allowed to send private messages!", ))); } @@ -935,16 +934,16 @@ pub async fn thread_send_message_internal( pool, ) .await - .wrap_internal_err("fetching thread message from database")?; + .internal_context("fetching thread message from database")?; if let Some(thread_message) = thread_message { if thread_message.thread_id != string { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Message replied to is from another thread!", ))); } } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Message replied to does not exist!", ))); } @@ -952,27 +951,27 @@ pub async fn thread_send_message_internal( is_private = *private; } else { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You may only send text messages through this route!", ))); } let result = database::models::DBThread::get(string, pool) .await - .wrap_internal_err("fetching thread from database")?; + .internal_context("fetching thread from database")?; if let Some(thread) = result { if !is_authorized_thread(&thread, user, Scopes::MODERATION_WRITE, pool) .await - .wrap_api_err("checking thread authorization")? + .api_context("checking thread authorization")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let id = ThreadMessageBuilder { author_id: Some(user.user.id.into()), @@ -982,7 +981,7 @@ pub async fn thread_send_message_internal( } .insert(&mut transaction) .await - .wrap_internal_err( + .internal_context( "inserting database records for `thread_send_message_internal`", )?; @@ -990,7 +989,7 @@ pub async fn thread_send_message_internal( let project = database::models::DBProject::get_id(project_id, pool, redis) .await - .wrap_internal_err("fetching thread project")?; + .internal_context("fetching thread project")?; if let Some(project) = project && project.inner.status != ProjectStatus::Processing @@ -1004,7 +1003,7 @@ pub async fn thread_send_message_internal( redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; NotificationBuilder { body: NotificationBody::ModeratorMessage { @@ -1020,7 +1019,7 @@ pub async fn thread_send_message_internal( redis, ) .await - .wrap_internal_err("inserting database records for `thread_send_message_internal`")?; + .internal_context("inserting database records for `thread_send_message_internal`")?; NotificationBuilder { body: NotificationBody::ModerationMessageReceived { @@ -1033,19 +1032,19 @@ pub async fn thread_send_message_internal( redis, ) .await - .wrap_internal_err("inserting database records for `thread_send_message_internal`")?; + .internal_context("inserting database records for `thread_send_message_internal`")?; } } else if let Some(report_id) = thread.report_id { let report = database::models::report_item::DBReport::get(report_id, pool) .await - .wrap_internal_err("fetching report from database")?; + .internal_context("fetching report from database")?; if let Some(report) = report { if report.closed && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "You may not reply to a closed report", ))); } @@ -1061,7 +1060,7 @@ pub async fn thread_send_message_internal( } .insert(report.reporter, &mut transaction, redis) .await - .wrap_internal_err("inserting database records for `thread_send_message_internal`")?; + .internal_context("inserting database records for `thread_send_message_internal`")?; } } } @@ -1077,7 +1076,7 @@ pub async fn thread_send_message_internal( redis, ) .await - .wrap_internal_err("fetching image from database")? + .internal_context("fetching image from database")? { let image: Image = db_image.into(); if !matches!( @@ -1085,7 +1084,7 @@ pub async fn thread_send_message_internal( ImageContext::ThreadMessage { .. } ) || image.context.inner_id().is_some() { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Image {image_id} is not unused and in the 'thread_message' context" )))); } @@ -1101,15 +1100,15 @@ pub async fn thread_send_message_internal( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `thread_send_message_internal`", )?; image_item::DBImage::clear_cache(image.id.into(), redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } else { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Image {image_id} does not exist" )))); } @@ -1119,11 +1118,11 @@ pub async fn thread_send_message_internal( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(()) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1156,20 +1155,20 @@ pub async fn message_delete( Scopes::THREAD_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let result = database::models::DBThreadMessage::get( info.into_inner().0.into(), &**pool, ) .await - .wrap_internal_err("fetching thread message from database")?; + .internal_context("fetching thread message from database")?; if let Some(thread) = result { if !user.scopes.contains(Scopes::MODERATION_WRITE) && thread.author_id != Some(user.user.id.into()) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You cannot delete this message!", ))); } @@ -1177,7 +1176,7 @@ pub async fn message_delete( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let context = ImageContext::ThreadMessage { thread_message_id: Some(thread.id.into()), @@ -1185,7 +1184,7 @@ pub async fn message_delete( let images = database::DBImage::get_many_contexted(context, &mut transaction) .await - .wrap_internal_err("fetching images from database")?; + .internal_context("fetching images from database")?; for image in images { let name = image.url.split(&format!("{}/", ENV.CDN_URL)).nth(1); if let Some(icon_path) = name { @@ -1195,11 +1194,11 @@ pub async fn message_delete( FileHostPublicity::Public, // FIXME: Consider using private file storage? ) .await - .wrap_internal_err("deleting file from file host")?; + .internal_context("deleting file from file host")?; } database::DBImage::remove(image.id, &mut transaction, &redis) .await - .wrap_internal_err("deleting image from database")?; + .internal_context("deleting image from database")?; } let private = thread.body.is_private(); @@ -1209,14 +1208,14 @@ pub async fn message_delete( &mut transaction, ) .await - .wrap_internal_err("deleting thread message from database")?; + .internal_context("deleting thread message from database")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/routes/v3/users.rs b/apps/labrinth/src/routes/v3/users.rs index cd0fe35b7b4..d0e466cdd82 100644 --- a/apps/labrinth/src/routes/v3/users.rs +++ b/apps/labrinth/src/routes/v3/users.rs @@ -29,8 +29,8 @@ use crate::{ util::{img::delete_old_images, routes::read_limited_from_payload}, }; use actix_web::{HttpRequest, HttpResponse, delete, get, patch, web}; +use anyhow::anyhow; use ariadne::ids::UserId; -use eyre::eyre; use serde::{Deserialize, Serialize}; use validator::Validate; @@ -96,20 +96,20 @@ pub async fn all_projects( .ok(); let target_user = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching user from database")? + .not_found_context("resource not found")?; let user_project_ids = DBUser::get_projects(target_user.id, &**pool, &redis) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let organization_ids = DBUser::get_organizations(target_user.id, &**pool) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let organizations_data = DBOrganization::get_many_ids(&organization_ids, &**pool, &redis) .await - .wrap_internal_err("fetching organizations from database")?; + .internal_context("fetching organizations from database")?; let team_ids = organizations_data .iter() @@ -120,7 +120,7 @@ pub async fn all_projects( &team_ids, &**pool, &redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = DBUser::get_many_ids( &teams_data .iter() @@ -130,7 +130,7 @@ pub async fn all_projects( &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let mut team_groups = HashMap::new(); for member in teams_data { @@ -145,7 +145,7 @@ pub async fn all_projects( for data in organizations_data { if !is_visible_organization(&data, &user, &pool, &redis) .await - .wrap_api_err("checking organization visibility")? + .api_context("checking organization visibility")? { continue; } @@ -194,7 +194,7 @@ pub async fn all_projects( ) .fetch_all(&**pool) .await - .wrap_internal_err("fetching organization project IDs from database")? + .internal_context("fetching organization project IDs from database")? .into_iter() .map(|row| DBProjectId(row.id)) .collect::>(); @@ -208,10 +208,10 @@ pub async fn all_projects( let projects_data = crate::database::DBProject::get_many_ids(&project_ids, &**pool, &redis) .await - .wrap_internal_err("fetching user and organization projects")?; + .internal_context("fetching user and organization projects")?; let projects = filter_visible_projects(projects_data, &user, &pool, true) .await - .wrap_api_err("filtering visible projects")?; + .api_context("filtering visible projects")?; Ok(web::Json(AllProjectsResponse { projects, @@ -240,10 +240,10 @@ pub async fn admin_user_email( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_READ) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to get a user from their email!", ))); } @@ -257,9 +257,9 @@ pub async fn admin_user_email( ) .fetch_optional(&**pool) .await - .wrap_internal_err("fetching user ID from database")? + .internal_context("fetching user ID from database")? .map(|x| x.id) - .wrap_request_err_with(|| { + .request_context_with(|| { "the email provided is not associated with a user!".to_string() })?; @@ -269,12 +269,12 @@ pub async fn admin_user_email( &redis, ) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(user) = user { Ok(web::Json(user.into())) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -299,25 +299,25 @@ pub async fn admin_user_discord( Scopes::SESSION_ACCESS, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !user.scopes.contains(Scopes::ADMIN_READ) { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you must be an admin to look up users by discord ID" ))); } let user_id = DBUser::get_by_discord_id(query.discord_id, &***ro_pool) .await - .wrap_internal_err("fetching user ID from database")? - .wrap_request_err( + .internal_context("fetching user ID from database")? + .request_context( "the discord ID provided is not associated with a user", )?; let user = DBUser::get_id(user_id, &***ro_pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching user from database")? + .not_found_context("resource not found")?; Ok(web::Json(user.into())) } @@ -353,12 +353,12 @@ pub async fn projects_list( let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(id) = id_option.map(|x| x.id) { let project_data = DBUser::get_projects(id, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; let projects: Vec<_> = crate::database::DBProject::get_many_ids( &project_data, @@ -366,13 +366,13 @@ pub async fn projects_list( &redis, ) .await - .wrap_internal_err("fetching organization projects")?; + .internal_context("fetching organization projects")?; let projects = filter_visible_projects(projects, &user, &pool, true) .await - .wrap_api_err("filtering visible projects")?; + .api_context("filtering visible projects")?; Ok(HttpResponse::Ok().json(projects)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -401,7 +401,7 @@ pub async fn user_auth_get( Scopes::USER_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; if !scopes.contains(Scopes::USER_READ_EMAIL) { user.email = None; @@ -414,7 +414,7 @@ pub async fn user_auth_get( if scopes.contains(Scopes::MODERATION_READ) { let note = DBModerationNote::get_user(user.id.into(), &**pool, &redis) .await - .wrap_internal_err("fetching moderation note from database")?; + .internal_context("fetching moderation note from database")?; user.moderation_notes = Some(note.map(Into::into)); } @@ -441,24 +441,24 @@ pub async fn get_user_preferences( Scopes::USER_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let target = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching user from database")? + .not_found_context("resource not found")?; let can_access = requester.id == target.id.into() || scopes.contains(Scopes::MODERATION_READ); if !can_access { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to access this user's preferences" ))); } let preference_overrides = DBUserPreferences::get(target.id, &**pool) .await - .wrap_internal_err("failed to fetch user preferences")?; + .internal_context("failed to fetch user preferences")?; Ok(web::Json(UserPreferences::resolve(preference_overrides))) } @@ -488,17 +488,17 @@ pub async fn edit_user_preferences( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let target = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching user from database")? + .not_found_context("resource not found")?; let can_access = requester.id == target.id.into() || scopes.contains(Scopes::MODERATION_WRITE); if !can_access { - return Err(ApiError::Auth(eyre!( + return Err(ApiError::Auth(anyhow!( "you do not have permission to access this user's preferences" ))); } @@ -506,11 +506,11 @@ pub async fn edit_user_preferences( let mut txn = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let stored = DBUserPreferences::get_for_update(target.id, &mut txn) .await - .wrap_internal_err("failed to fetch user preferences")?; + .internal_context("failed to fetch user preferences")?; let mut preferences = UserPreferences::resolve(stored); body.into_inner().apply_to(&mut preferences); @@ -518,11 +518,11 @@ pub async fn edit_user_preferences( let overrides = preferences.into_diff_from(&UserPreferences::default()); DBUserPreferences::upsert(target.id, &overrides, &mut txn) .await - .wrap_internal_err("failed to update user preferences")?; + .internal_context("failed to update user preferences")?; txn.commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; let preferences = UserPreferences::resolve(Some(overrides)); @@ -552,7 +552,7 @@ pub async fn users_search( let query = query.query.trim(); let users = DBUser::search(query, &**pool) .await - .wrap_internal_err("failed to search users")? + .internal_context("failed to search users")? .into_iter() .map(Into::into) .collect(); @@ -584,11 +584,11 @@ pub async fn users_get( session_queue: web::Data, ) -> Result { let user_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; let users_data = DBUser::get_many(&user_ids, &**pool, &redis) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let auth_user = get_user_from_headers( &req, @@ -610,7 +610,7 @@ pub async fn users_get( &redis, ) .await - .wrap_internal_err("fetching moderation notes from database")? + .internal_context("fetching moderation notes from database")? } else { HashMap::new() }; @@ -659,7 +659,7 @@ pub async fn user_get( ) -> Result { let user_data = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(data) = user_data { let auth_user = get_user_from_headers( @@ -702,7 +702,7 @@ pub async fn user_get( if is_mod { let note = DBModerationNote::get_user(user_id, &**pool, &redis) .await - .wrap_internal_err("fetching moderation note from database")?; + .internal_context("fetching moderation note from database")?; response.moderation_notes = Some(note.map(Into::into)); response.lock = lock.map(Into::into); } @@ -715,7 +715,7 @@ pub async fn user_get( Ok(HttpResponse::Ok().json(response)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -737,27 +737,27 @@ pub async fn user_notes_edit( Scopes::SESSION_ACCESS | Scopes::MODERATION_WRITE, ) .await - .wrap_auth_err("authenticating API request")? + .auth_context("authenticating API request")? .user; new_note .validate_not_empty() - .wrap_api_err("validating not empty")?; + .api_context("validating not empty")?; let expected_version = crate::models::moderation_notes::parse_if_match_header(&req) - .wrap_api_err( + .api_context( "executing `moderation_notes::parse_if_match_header`", )?; let user_data = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")? - .wrap_not_found_err("resource not found")?; + .internal_context("fetching user from database")? + .not_found_context("resource not found")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(expected) = expected_version { let updated = DBModerationNote::update( Some(user_data.id), @@ -769,10 +769,10 @@ pub async fn user_notes_edit( &mut transaction, ) .await - .wrap_internal_err("updating moderation note in database")?; + .internal_context("updating moderation note in database")?; if updated.is_none() { - return Err(ApiError::PreconditionFailed(eyre::eyre!( + return Err(ApiError::PreconditionFailed(anyhow!( "moderation note version does not match", ))); } @@ -786,10 +786,10 @@ pub async fn user_notes_edit( &mut transaction, ) .await - .wrap_internal_err("inserting moderation note into database")?; + .internal_context("inserting moderation note into database")?; if updated.is_none() { - return Err(ApiError::PreconditionRequired(eyre::eyre!( + return Err(ApiError::PreconditionRequired(anyhow!( "moderation note version does not match", ))); } @@ -798,10 +798,10 @@ pub async fn user_notes_edit( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBModerationNote::clear_user_cache(user_data.id, &redis) .await - .wrap_internal_err("clearing cached moderation note in Redis")?; + .internal_context("clearing cached moderation note in Redis")?; Ok(HttpResponse::NoContent().finish()) } @@ -827,12 +827,12 @@ pub async fn collections_list( let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(id) = id_option.map(|x| x.id) { let collection_data = DBUser::get_collections(id, &**pool) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; let response: Vec<_> = crate::database::models::DBCollection::get_many( &collection_data, @@ -840,15 +840,15 @@ pub async fn collections_list( &redis, ) .await - .wrap_internal_err("fetching collections from database")?; + .internal_context("fetching collections from database")?; let collections = filter_visible_collections(response, &user, true) .await - .wrap_api_err("filtering visible collections")?; + .api_context("filtering visible collections")?; Ok(HttpResponse::Ok().json(collections)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -873,18 +873,18 @@ pub async fn orgs_list( let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(id) = id_option.map(|x| x.id) { let org_data = DBUser::get_organizations(id, &**pool) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; let organizations_data = crate::database::models::organization_item::DBOrganization::get_many_ids( &org_data, &**pool, &redis, ) - .await.wrap_internal_err("fetching organizations from database")?; + .await.internal_context("fetching organizations from database")?; let team_ids = organizations_data .iter() @@ -896,14 +896,14 @@ pub async fn orgs_list( &team_ids, &**pool, &redis, ) .await - .wrap_internal_err("fetching team members from database")?; + .internal_context("fetching team members from database")?; let users = DBUser::get_many_ids( &teams_data.iter().map(|x| x.user_id).collect::>(), &**pool, &redis, ) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let mut organizations = vec![]; let mut team_groups = HashMap::new(); @@ -914,7 +914,7 @@ pub async fn orgs_list( for data in organizations_data { if !is_visible_organization(&data, &user, &pool, &redis) .await - .wrap_api_err("checking organization visibility")? + .api_context("checking organization visibility")? { continue; } @@ -953,7 +953,7 @@ pub async fn orgs_list( Ok(HttpResponse::Ok().json(organizations)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1004,16 +1004,16 @@ pub async fn user_edit( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; new_user .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(actual_user) = id_option { let id = actual_user.id; @@ -1023,13 +1023,13 @@ pub async fn user_edit( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; if let Some(username) = &new_user.username { let existing_user_id_option = DBUser::get(username, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if existing_user_id_option .map(|x| UserId::from(x.id)) @@ -1046,9 +1046,9 @@ pub async fn user_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `user_edit`")?; + .internal_context("querying database for `user_edit`")?; } else { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Username {username} is taken!" )))); } @@ -1066,12 +1066,12 @@ pub async fn user_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("fetching bio from database")?; + .internal_context("fetching bio from database")?; } if let Some(role) = &new_user.role { if !scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the role of this user!", ))); } @@ -1089,12 +1089,12 @@ pub async fn user_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `user_edit`")?; + .internal_context("querying database for `user_edit`")?; } if let Some(badges) = &new_user.badges { if !scopes.contains(Scopes::ADMIN_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the badges of this user!", ))); } @@ -1110,12 +1110,12 @@ pub async fn user_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `user_edit`")?; + .internal_context("querying database for `user_edit`")?; } if let Some(venmo_handle) = &new_user.venmo_handle { if !scopes.contains(Scopes::PAYOUTS_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit the venmo handle of this user!", ))); } @@ -1131,7 +1131,7 @@ pub async fn user_edit( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `user_edit`")?; + .internal_context("querying database for `user_edit`")?; } if let Some(allow_friend_requests) = &user.allow_friend_requests { @@ -1146,7 +1146,7 @@ pub async fn user_edit( ) .execute(&mut transaction) .await - .wrap_internal_err( + .internal_context( "fetching allow friend requests from database", )?; } @@ -1154,18 +1154,18 @@ pub async fn user_edit( transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; DBUser::clear_caches(&[(id, Some(actual_user.username))], &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( "You do not have permission to edit this user!", ))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1223,16 +1223,16 @@ pub async fn user_icon_edit( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(actual_user) = id_option { if user.user.id != actual_user.id.into() && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this user's icon.", ))); } @@ -1244,7 +1244,7 @@ pub async fn user_icon_edit( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; let bytes = read_limited_from_payload( &mut payload, @@ -1270,7 +1270,7 @@ pub async fn user_icon_edit( &**file_host, ) .await - .wrap_api_err("uploading image")?; + .api_context("uploading image")?; sqlx::query!( " @@ -1284,14 +1284,14 @@ pub async fn user_icon_edit( ) .execute(&**pool) .await - .wrap_internal_err("querying database for `user_icon_edit`")?; + .internal_context("querying database for `user_icon_edit`")?; DBUser::clear_caches(&[(actual_user.id, None)], &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1324,16 +1324,16 @@ pub async fn user_icon_delete( Scopes::USER_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(actual_user) = id_option { if user.user.id != actual_user.id.into() && !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to edit this user's icon.", ))); } @@ -1345,7 +1345,7 @@ pub async fn user_icon_delete( &**file_host, ) .await - .wrap_api_err("deleting old images")?; + .api_context("deleting old images")?; sqlx::query!( " @@ -1357,15 +1357,15 @@ pub async fn user_icon_delete( ) .execute(&**pool) .await - .wrap_internal_err("querying database for `user_icon_delete`")?; + .internal_context("querying database for `user_icon_delete`")?; DBUser::clear_caches(&[(actual_user.id, None)], &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1396,16 +1396,16 @@ pub async fn user_delete( Scopes::USER_DELETE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("failed to get user")?; + .internal_context("failed to get user")?; let id = id_option .map(|x| x.id) - .wrap_not_found_err("resource not found")?; + .not_found_context("resource not found")?; if !user.scopes.contains(Scopes::ADMIN_WRITE) && user.user.id != id.into() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to delete this user!", ))); } @@ -1413,21 +1413,21 @@ pub async fn user_delete( let mut transaction = pool .begin() .await - .wrap_internal_err("failed to begin transaction")?; + .internal_context("failed to begin transaction")?; let result = DBUser::remove(id, &mut transaction, &redis) .await - .wrap_internal_err("failed to remove user")?; + .internal_context("failed to remove user")?; transaction .commit() .await - .wrap_internal_err("failed to commit transaction")?; + .internal_context("failed to commit transaction")?; if result.is_some() { Ok(()) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1458,37 +1458,37 @@ pub async fn user_follows( Scopes::USER_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(id) = id_option.map(|x| x.id) { if !user.scopes.contains(Scopes::ADMIN_READ) && user.user.id != id.into() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to see the projects this user follows!", ))); } let project_ids = DBUser::get_follows(id, &**pool) .await - .wrap_internal_err("fetching users from database")?; + .internal_context("fetching users from database")?; let projects: Vec<_> = crate::database::DBProject::get_many_ids( &project_ids, &**pool, &redis, ) .await - .wrap_internal_err("fetching followed projects")? + .internal_context("fetching followed projects")? .into_iter() .map(Project::from) .collect(); Ok(HttpResponse::Ok().json(projects)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1519,16 +1519,16 @@ pub async fn user_notifications( Scopes::NOTIFICATION_READ, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id_option = DBUser::get(&info.into_inner().0, &**pool, &redis) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(id) = id_option.map(|x| x.id) { if !user.scopes.contains(Scopes::ADMIN_READ) && user.user.id != id.into() { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to see the notifications of this user!", ))); } @@ -1537,7 +1537,7 @@ pub async fn user_notifications( crate::database::models::notification_item::DBNotification::get_many_user_exposed_on_site( id, &**pool, &redis, ) - .await.wrap_internal_err("fetching notifications from database")? + .await.internal_context("fetching notifications from database")? .into_iter() .map(Into::into) .collect(); @@ -1545,6 +1545,6 @@ pub async fn user_notifications( notifications.sort_by_key(|b| Reverse(b.created)); Ok(HttpResponse::Ok().json(notifications)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/routes/v3/version_creation.rs b/apps/labrinth/src/routes/v3/version_creation.rs index 79820064aed..9a3222aad2d 100644 --- a/apps/labrinth/src/routes/v3/version_creation.rs +++ b/apps/labrinth/src/routes/v3/version_creation.rs @@ -34,8 +34,8 @@ use crate::validate::{ValidationResult, validate_file}; use actix_multipart::{Field, Multipart}; use actix_web::web::Data; use actix_web::{HttpRequest, HttpResponse, post, web}; +use anyhow::Context as _; use chrono::Utc; -use eyre::WrapErr as _; use futures::stream::StreamExt; use hex::ToHex; use itertools::Itertools; @@ -1223,16 +1223,16 @@ pub async fn validate_minecraft_component( minecraft_meta: web::Data, component: &exp::minecraft::ModVersion, loaders: &[models::loader_item::Loader], -) -> eyre::Result<()> { - eyre::ensure!( +) -> anyhow::Result<()> { + anyhow::ensure!( !loaders.is_empty(), "Minecraft fields do not apply to the supplied loaders" ); - eyre::ensure!( + anyhow::ensure!( !component.game_versions.is_empty(), "at least one Minecraft game version is required" ); - eyre::ensure!( + anyhow::ensure!( component.mrpack_loaders.is_empty() || loaders.iter().any(|loader| loader.loader == "mrpack"), "`mrpack_loaders` requires the `mrpack` loader" @@ -1240,7 +1240,7 @@ pub async fn validate_minecraft_component( minecraft_meta .validate_minecraft_versions(&component.game_versions) .await - .wrap_err("validating minecraft game versions") + .context("validating minecraft game versions") } pub async fn create_minecraft_component( @@ -1250,7 +1250,7 @@ pub async fn create_minecraft_component( loaders: &[models::loader_item::Loader], ) -> Result, CreateError> { let build = async { - eyre::ensure!( + anyhow::ensure!( typed.is_none() || fields.is_empty(), "cannot combine typed and flattened Minecraft fields" ); @@ -1258,7 +1258,7 @@ pub async fn create_minecraft_component( if !applies && typed.is_none() && fields.is_empty() { return Ok(None); } - eyre::ensure!( + anyhow::ensure!( !fields.contains_key("mrpack_loaders") || loaders.iter().any(|loader| loader.loader == "mrpack"), "`mrpack_loaders` requires the `mrpack` loader" @@ -1274,7 +1274,7 @@ pub async fn create_minecraft_component( loaders, ) .await?; - eyre::Ok(Some(component)) + anyhow::Ok(Some(component)) } .await; build.map_err(|error| CreateError::InvalidInput(error.to_string())) diff --git a/apps/labrinth/src/routes/v3/version_file.rs b/apps/labrinth/src/routes/v3/version_file.rs index e2b5f87dcd1..97e927c3ead 100644 --- a/apps/labrinth/src/routes/v3/version_file.rs +++ b/apps/labrinth/src/routes/v3/version_file.rs @@ -10,6 +10,7 @@ use crate::models::pats::Scopes; use crate::models::projects::{ProjectStatus, VersionStatus, VersionType}; use crate::models::teams::ProjectPermissions; use crate::queue::session::AuthQueue; +use anyhow::anyhow; use crate::routes::{FileHash, HashAlgorithm}; use crate::util::error::ApiContext as _; @@ -93,29 +94,27 @@ pub async fn get_version_from_hash( &redis, ) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(file) = file { let version = database::models::DBVersion::get(file.version_id, &***pool, &redis) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(version) = version { if !is_visible_version(&version.inner, &user_option, &pool, &redis) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { - return Err(ApiError::NotFound(eyre::eyre!( - "resource not found" - ))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } Ok(HttpResponse::Ok() .json(models::projects::Version::from(version))) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -223,7 +222,7 @@ pub async fn get_update_from_hash( &redis, ) .await - .wrap_internal_err("querying database for `get_update_from_hash`")? + .internal_context("querying database for `get_update_from_hash`")? { let latest = get_latest_matching_versions( &[LatestVersionFilter { @@ -236,21 +235,19 @@ pub async fn get_update_from_hash( &pool, ) .await - .wrap_api_err("fetching latest matching version")?; + .api_context("fetching latest matching version")?; if let Some(version_id) = latest.into_values().next() && let Some(first) = database::models::DBVersion::get(version_id, &***pool, &redis) .await - .wrap_internal_err("fetching version from database")? + .internal_context("fetching version from database")? { if !is_visible_version(&first.inner, &user_option, &pool, &redis) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { - return Err(ApiError::NotFound(eyre::eyre!( - "resource not found" - ))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } return Ok( @@ -258,7 +255,7 @@ pub async fn get_update_from_hash( ); } } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } // Requests above with multiple versions below @@ -325,19 +322,19 @@ pub async fn get_versions_from_hashes( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let version_ids = files.iter().map(|x| x.version_id).collect::>(); let versions_data = filter_visible_versions( database::models::DBVersion::get_many(&version_ids, &***pool, &redis) .await - .wrap_internal_err("fetching versions from database")?, + .internal_context("fetching versions from database")?, &user_option, pool.as_ref(), &redis, ) .await - .wrap_api_err("filtering visible versions")?; + .api_context("filtering visible versions")?; let mut response = HashMap::new(); @@ -405,7 +402,7 @@ pub async fn get_projects_from_hashes( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let project_ids = files.iter().map(|x| x.project_id).collect::>(); @@ -416,13 +413,13 @@ pub async fn get_projects_from_hashes( &redis, ) .await - .wrap_internal_err("fetching projects for visibility filtering")?, + .internal_context("fetching projects for visibility filtering")?, &user_option, &pool, false, ) .await - .wrap_api_err("filtering visible projects")?; + .api_context("filtering visible projects")?; let mut response = HashMap::new(); @@ -533,7 +530,7 @@ pub async fn update_files( let file_hashes_to_versions = update_files_internal(req, pool, redis, update_data, session_queue) .await - .wrap_api_err("updating files internal")?; + .api_context("updating files internal")?; let resp = file_hashes_to_versions .into_iter() .filter_map(|(hash, versions)| { @@ -579,19 +576,19 @@ async fn update_files_internal( &redis, ) .await - .wrap_internal_err("updating versions in database")?; + .internal_context("updating versions in database")?; let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; // Custom plans for this query cost more to plan than to execute, and the // generic plan executes at least as fast, so skip replanning per call. sqlx::query!("SET LOCAL plan_cache_mode = force_generic_plan") .execute(&mut transaction) .await - .wrap_internal_err("forcing generic plan for update query")?; + .internal_context("forcing generic plan for update query")?; let latest_version_ids = sqlx::query_scalar!( r#" @@ -680,12 +677,12 @@ async fn update_files_internal( ) .fetch_all(&mut transaction) .await - .wrap_internal_err("fetching latest visible update versions")?; + .internal_context("fetching latest visible update versions")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; let versions = database::models::DBVersion::get_many( &latest_version_ids @@ -696,7 +693,7 @@ async fn update_files_internal( &redis, ) .await - .wrap_internal_err("fetching update versions")?; + .internal_context("fetching update versions")?; let mut response = HashMap::>::new(); for file in files { @@ -791,7 +788,7 @@ pub async fn update_individual_files( &redis, ) .await - .wrap_internal_err("updating versions in database")?; + .internal_context("updating versions in database")?; let filters = files .iter() @@ -810,7 +807,7 @@ pub async fn update_individual_files( .collect::>(); let latest = get_latest_matching_versions(&filters, &pool) .await - .wrap_api_err("fetching latest matching versions")?; + .api_context("fetching latest matching versions")?; let versions = database::models::DBVersion::get_many( &latest.values().copied().unique().collect::>(), @@ -818,7 +815,7 @@ pub async fn update_individual_files( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let visible_version_ids = filter_visible_version_ids( versions.iter().map(|x| &x.inner).collect(), &user_option, @@ -826,7 +823,7 @@ pub async fn update_individual_files( &redis, ) .await - .wrap_api_err("filtering visible update versions")?; + .api_context("filtering visible update versions")?; let response = latest .into_iter() @@ -923,7 +920,7 @@ async fn get_latest_matching_versions( ) .fetch_all(pool) .await - .wrap_internal_err("fetching latest matching versions")?; + .internal_context("fetching latest matching versions")?; Ok(rows .into_iter() @@ -982,7 +979,7 @@ pub async fn delete_file( Scopes::VERSION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let hash = info.into_inner().0.to_lowercase(); let algorithm = hash_query.algorithm.clone().unwrap_or_else(|| { @@ -996,7 +993,7 @@ pub async fn delete_file( &redis, ) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(row) = file { if !user.scopes.contains(Scopes::ADMIN_WRITE) { @@ -1007,7 +1004,7 @@ pub async fn delete_file( &**pool, ) .await - .wrap_internal_err("fetching version team member")?; + .internal_context("fetching version team member")?; let organization = database::models::DBOrganization::get_associated_organization_project_id( @@ -1015,7 +1012,7 @@ pub async fn delete_file( &**pool, ) .await - .wrap_internal_err("fetching project organization")?; + .internal_context("fetching project organization")?; let organization_team_member = if let Some(organization) = &organization @@ -1027,7 +1024,7 @@ pub async fn delete_file( &**pool, ) .await - .wrap_internal_err("fetching organization team member")? + .internal_context("fetching organization team member")? } else { None }; @@ -1040,7 +1037,7 @@ pub async fn delete_file( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::DELETE_VERSION) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to delete this file!", ))); } @@ -1049,23 +1046,23 @@ pub async fn delete_file( let version = database::models::DBVersion::get(row.version_id, &**pool, &redis) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(version) = version { if version.files.len() < 2 { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "Versions must have at least one file uploaded to them", ))); } database::models::DBVersion::clear_cache(&version, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; sqlx::query!( " @@ -1076,7 +1073,7 @@ pub async fn delete_file( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `delete_file`")?; + .internal_context("querying database for `delete_file`")?; sqlx::query!( " @@ -1087,10 +1084,10 @@ pub async fn delete_file( ) .execute(&mut transaction) .await - .wrap_internal_err("querying database for `delete_file`")?; + .internal_context("querying database for `delete_file`")?; database::models::version_item::cleanup_unused_attribution_files_and_groups(&mut transaction) - .await.wrap_internal_err("deleting version item from database")?; + .await.internal_context("deleting version item from database")?; super::projects::mutation::finalize_mutation( row.project_id, @@ -1103,7 +1100,7 @@ pub async fn delete_file( Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1173,31 +1170,29 @@ pub async fn download_version( &redis, ) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(file) = file { let version = database::models::DBVersion::get(file.version_id, &***pool, &redis) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(version) = version { if !is_visible_version(&version.inner, &user_option, &pool, &redis) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { - return Err(ApiError::NotFound(eyre::eyre!( - "resource not found" - ))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } Ok(HttpResponse::TemporaryRedirect() .append_header(("Location", &*file.url)) .json(DownloadRedirect { url: file.url })) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/routes/v3/versions.rs b/apps/labrinth/src/routes/v3/versions.rs index ee7eb23bcca..118f3f400f9 100644 --- a/apps/labrinth/src/routes/v3/versions.rs +++ b/apps/labrinth/src/routes/v3/versions.rs @@ -1,5 +1,6 @@ use crate::util::MinecraftMeta; use crate::util::error::ApiContext as _; +use anyhow::anyhow; use std::collections::HashMap; use super::ApiError; @@ -92,7 +93,7 @@ pub async fn version_project_get_helper( ) -> Result { let result = database::models::DBProject::get(&id.0, &***ro_pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; let user_option = get_user_from_headers( &req, @@ -107,9 +108,9 @@ pub async fn version_project_get_helper( if let Some(project) = result { if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let versions = database::models::DBVersion::get_many( @@ -118,7 +119,7 @@ pub async fn version_project_get_helper( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let id_opt = parse_base62(&id.1).ok(); let version = versions.into_iter().find(|x| { @@ -134,7 +135,7 @@ pub async fn version_project_get_helper( &redis, ) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { let version_id = version.inner.id; let project_id = version.inner.project_id; @@ -170,7 +171,7 @@ pub async fn version_project_get_helper( } } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } #[derive(Serialize, Deserialize)] @@ -216,7 +217,7 @@ pub async fn versions_get( ) -> Result { let version_ids = serde_json::from_str::>(&ids.ids) - .wrap_request_err("deserializing JSON data")? + .request_context("deserializing JSON data")? .into_iter() .map(|x| x.into()) .collect::>(); @@ -226,7 +227,7 @@ pub async fn versions_get( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let user_option = get_user_from_headers( &req, @@ -241,7 +242,7 @@ pub async fn versions_get( let mut versions = filter_visible_versions(versions_data, &user_option, &ro_pool, &redis) .await - .wrap_api_err("filtering visible versions")?; + .api_context("filtering visible versions")?; if !ids.include_changelog { for version in &mut versions { @@ -302,7 +303,7 @@ pub async fn version_get_helper( let version_data = database::models::DBVersion::get(id.into(), &***ro_pool, &redis) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; let user_option = get_user_from_headers( &req, @@ -317,7 +318,7 @@ pub async fn version_get_helper( if let Some(data) = version_data && is_visible_version(&data.inner, &user_option, &ro_pool, &redis) .await - .wrap_api_err("checking version visibility")? + .api_context("checking version visibility")? { let version_id = data.inner.id; let project_id = data.inner.project_id; @@ -354,7 +355,7 @@ pub async fn version_get_helper( return Ok(web::Json(version)); } - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } #[derive(Serialize, Deserialize, Validate, Default, Debug)] @@ -488,7 +489,7 @@ pub async fn version_edit_helper( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let (version_item, user) = version_edit_in_transaction( minecraft_meta.clone(), req, @@ -511,7 +512,7 @@ pub async fn version_edit_helper( .await?; database::models::DBVersion::clear_cache(&version_item, &redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; search_state .queue .push_version_changes( @@ -549,18 +550,18 @@ pub(crate) async fn version_edit_in_transaction( Scopes::VERSION_WRITE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; new_version .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; let version_id = info.0.into(); let result = database::models::DBVersion::get(version_id, &**pool, &redis) .await - .wrap_internal_err("fetching version from database")?; + .internal_context("fetching version from database")?; if let Some(version_item) = result { let team_member = @@ -571,7 +572,7 @@ pub(crate) async fn version_edit_in_transaction( &**pool, ) .await - .wrap_internal_err("fetching team member from database")?; + .internal_context("fetching team member from database")?; let organization = DBOrganization::get_associated_organization_project_id( @@ -579,7 +580,7 @@ pub(crate) async fn version_edit_in_transaction( &**pool, ) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; let organization_team_member = if let Some(organization) = &organization { @@ -589,7 +590,7 @@ pub(crate) async fn version_edit_in_transaction( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? } else { None }; @@ -602,7 +603,7 @@ pub(crate) async fn version_edit_in_transaction( if let Some(perms) = permissions { if !perms.contains(ProjectPermissions::UPLOAD_VERSION) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have the permissions to edit this version!", ))); } @@ -618,8 +619,8 @@ pub(crate) async fn version_edit_in_transaction( &redis, ) .await - .wrap_internal_err("fetching loader from Redis")? - .wrap_request_err_with(|| { + .internal_context("fetching loader from Redis")? + .request_context_with(|| { format!( "no database entry for loader `{}`", loader.0 @@ -644,7 +645,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; } @@ -661,7 +662,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; } @@ -678,7 +679,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err("fetching version type from database")?; + .internal_context("fetching version type from database")?; } if let Some(dependencies) = &new_version.dependencies { @@ -690,7 +691,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err("fetching dependencies from database")?; + .internal_context("fetching dependencies from database")?; let builders = dependencies .iter() @@ -708,7 +709,7 @@ pub(crate) async fn version_edit_in_transaction( &mut *transaction, ) .await - .wrap_internal_err( + .internal_context( "inserting database records for `version_edit_helper`", )?; } @@ -720,7 +721,7 @@ pub(crate) async fn version_edit_in_transaction( if new_version.minecraft_mod.is_some() && !new_version.fields.is_empty() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "cannot combine typed and flattened Minecraft fields" ))); } @@ -729,7 +730,7 @@ pub(crate) async fn version_edit_in_transaction( None => crate::models::minecraft::parse_minecraft_fields( &new_version.fields, ) - .wrap_request_err("parsing Minecraft fields")?, + .request_context("parsing Minecraft fields")?, }; let edits_mrpack_loaders = edit.mrpack_loaders.is_some(); let component = if let Some(mut component) = @@ -737,10 +738,10 @@ pub(crate) async fn version_edit_in_transaction( { edit.apply_to(&mut component) .await - .wrap_request_err("applying Minecraft version edit")?; + .request_context("applying Minecraft version edit")?; component } else { - edit.create().wrap_request_err( + edit.create().request_context( "creating Minecraft version component", )? }; @@ -749,7 +750,7 @@ pub(crate) async fn version_edit_in_transaction( &redis, ) .await - .wrap_internal_err("fetching loaders")?; + .internal_context("fetching loaders")?; let loader_ids = if let Some(ids) = &new_loader_ids { ids.clone() } else { @@ -763,9 +764,7 @@ pub(crate) async fn version_edit_in_transaction( ) .fetch_all(&mut *transaction) .await - .wrap_internal_err( - "fetching version loaders from database", - )? + .internal_context("fetching version loaders from database")? .into_iter() .map(|row| database::models::ids::LoaderId(row.loader_id)) .collect::>() @@ -779,7 +778,7 @@ pub(crate) async fn version_edit_in_transaction( .iter() .any(|loader| loader.loader == "mrpack") { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "`mrpack_loaders` requires the `mrpack` loader" ))); } @@ -789,7 +788,7 @@ pub(crate) async fn version_edit_in_transaction( &selected_loaders, ) .await - .wrap_request_err("validating Minecraft version component")?; + .request_context("validating Minecraft version component")?; sqlx::query!( r#" UPDATE versions @@ -801,7 +800,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err("updating Minecraft version component")?; + .internal_context("updating Minecraft version component")?; } if let Some(loader_ids) = new_loader_ids { @@ -813,7 +812,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err("fetching loaders from database")?; + .internal_context("fetching loaders from database")?; let loader_versions = loader_ids .into_iter() @@ -827,7 +826,7 @@ pub(crate) async fn version_edit_in_transaction( &mut *transaction, ) .await - .wrap_internal_err("inserting loader versions into database")?; + .internal_context("inserting loader versions into database")?; } if let Some(featured) = &new_version.featured { @@ -842,7 +841,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err("fetching featured status from database")?; + .internal_context("fetching featured status from database")?; } if let Some(body) = &new_version.changelog { @@ -857,14 +856,14 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; } if let Some(downloads) = &new_version.downloads { if !user.scopes.contains(Scopes::MODERATION_WRITE) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You don't have permission to set the downloads of this mod", ))); } @@ -880,7 +879,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; @@ -898,14 +897,14 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; } if let Some(status) = &new_version.status { if !status.can_be_requested() { - return Err(ApiError::Request(eyre::eyre!( + return Err(ApiError::Request(anyhow!( "The requested status cannot be set!", ))); } @@ -921,7 +920,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; } @@ -939,10 +938,10 @@ pub(crate) async fn version_edit_in_transaction( ) .fetch_optional(&**pool) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )? - .wrap_request_err_with(|| { + .request_context_with(|| { format!( "specified file with hash `{}` does not exist", file_type.algorithm.clone() @@ -960,7 +959,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; } @@ -978,7 +977,7 @@ pub(crate) async fn version_edit_in_transaction( ) .execute(&mut *transaction) .await - .wrap_internal_err( + .internal_context( "querying database for `version_edit_helper`", )?; } @@ -999,16 +998,16 @@ pub(crate) async fn version_edit_in_transaction( &redis, ) .await - .wrap_api_err("deleting unused images")?; + .api_context("deleting unused images")?; Ok((version_item, user)) } else { - Err(ApiError::Auth(eyre::eyre!( + Err(ApiError::Auth(anyhow!( "You do not have permission to edit this version!", ))) } } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1097,7 +1096,7 @@ pub(crate) async fn auto_featured_filters( let loaders = database::models::loader_item::Loader::list(&**ro_pool, redis) .await - .wrap_internal_err("fetching automatic featured filters")?; + .internal_context("fetching automatic featured filters")?; let game_versions = minecraft_meta.minecraft_versions().await; Ok(game_versions .iter() @@ -1261,7 +1260,7 @@ pub async fn version_list_internal( let result = database::models::DBProject::get(&string, &***ro_pool, &redis) .await - .wrap_internal_err("fetching project from database")?; + .internal_context("fetching project from database")?; let user_option = get_user_from_headers( &req, @@ -1276,9 +1275,9 @@ pub async fn version_list_internal( if let Some(project) = result { if !is_visible_project(&project.inner, &user_option, &pool, false) .await - .wrap_api_err("checking project visibility")? + .api_context("checking project visibility")? { - return Err(ApiError::NotFound(eyre::eyre!("resource not found"))); + return Err(ApiError::NotFound(anyhow!("resource not found"))); } let versions = database::models::DBVersion::get_many( @@ -1287,7 +1286,7 @@ pub async fn version_list_internal( &redis, ) .await - .wrap_internal_err("fetching versions from database")?; + .internal_context("fetching versions from database")?; let response = filter_project_versions( minecraft_meta.clone(), versions, @@ -1301,7 +1300,7 @@ pub async fn version_list_internal( let mut response = filter_visible_versions(response, &user_option, &ro_pool, &redis) .await - .wrap_api_err("filtering visible versions")?; + .api_context("filtering visible versions")?; if !filters.include_changelog { for version in &mut response { @@ -1311,7 +1310,7 @@ pub async fn version_list_internal( Ok(HttpResponse::Ok().json(response)) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } @@ -1363,13 +1362,13 @@ pub async fn version_delete( Scopes::VERSION_DELETE, ) .await - .wrap_auth_err("authenticating API request")?; + .auth_context("authenticating API request")?; let id = info.into_inner().0; let version = database::models::DBVersion::get(id.into(), &**pool, &redis) .await - .wrap_internal_err("fetching version from database")? - .wrap_request_err_with(|| { + .internal_context("fetching version from database")? + .request_context_with(|| { "the specified version does not exist!".to_string() })?; @@ -1382,7 +1381,7 @@ pub async fn version_delete( &**pool, ) .await - .wrap_internal_err("fetching project team member")?; + .internal_context("fetching project team member")?; let organization = DBOrganization::get_associated_organization_project_id( @@ -1390,7 +1389,7 @@ pub async fn version_delete( &**pool, ) .await - .wrap_internal_err("fetching organization from database")?; + .internal_context("fetching organization from database")?; let organization_team_member = if let Some(organization) = &organization { @@ -1400,7 +1399,7 @@ pub async fn version_delete( &**pool, ) .await - .wrap_internal_err("fetching team member from database")? + .internal_context("fetching team member from database")? } else { None }; @@ -1412,7 +1411,7 @@ pub async fn version_delete( .unwrap_or_default(); if !permissions.contains(ProjectPermissions::DELETE_VERSION) { - return Err(ApiError::Auth(eyre::eyre!( + return Err(ApiError::Auth(anyhow!( "You do not have permission to delete versions in this team", ))); } @@ -1421,7 +1420,7 @@ pub async fn version_delete( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let context = ImageContext::Version { version_id: Some(version.inner.id.into()), @@ -1431,11 +1430,11 @@ pub async fn version_delete( &mut transaction, ) .await - .wrap_internal_err("fetching images from database")?; + .internal_context("fetching images from database")?; for image in uploaded_images { image_item::DBImage::remove(image.id, &mut transaction, &redis) .await - .wrap_internal_err("deleting image from database")?; + .internal_context("deleting image from database")?; } let result = database::models::DBVersion::remove_full( @@ -1444,7 +1443,7 @@ pub async fn version_delete( &mut transaction, ) .await - .wrap_internal_err("deleting version from database")?; + .internal_context("deleting version from database")?; super::projects::mutation::finalize_mutation( version.inner.project_id, @@ -1464,6 +1463,6 @@ pub async fn version_delete( if result.is_some() { Ok(HttpResponse::NoContent().body("")) } else { - Err(ApiError::NotFound(eyre::eyre!("resource not found"))) + Err(ApiError::NotFound(anyhow!("resource not found"))) } } diff --git a/apps/labrinth/src/search/backend/common.rs b/apps/labrinth/src/search/backend/common.rs index 95892751862..0f02d24e40d 100644 --- a/apps/labrinth/src/search/backend/common.rs +++ b/apps/labrinth/src/search/backend/common.rs @@ -1,7 +1,7 @@ use crate::routes::ApiError; use crate::search::SearchRequest; use crate::util::error::Context; -use eyre::eyre; +use anyhow::anyhow; use std::borrow::Cow; pub struct ParsedSearchRequest<'a> { @@ -20,13 +20,13 @@ pub fn parse_search_request( .as_deref() .unwrap_or("0") .parse::() - .wrap_request_err("invalid offset")?; + .request_context("invalid offset")?; let limit = info .limit .as_deref() .unwrap_or("10") .parse::() - .wrap_request_err("invalid limit")? + .request_context("invalid limit")? .min(100); let hits_per_page = if limit == 0 { 1 } else { limit }; @@ -88,7 +88,7 @@ pub fn parse_search_index( "minecraft_java_server.ping.data.players_online" => SearchSort { index: SearchIndex::MinecraftJavaServerPlayersOnline, }, - i => return Err(ApiError::Request(eyre!("invalid index '{i}'"))), + i => return Err(ApiError::Request(anyhow!("invalid index '{i}'"))), }) } diff --git a/apps/labrinth/src/search/backend/elasticsearch/filter.rs b/apps/labrinth/src/search/backend/elasticsearch/filter.rs index 06e00167402..4e17192face 100644 --- a/apps/labrinth/src/search/backend/elasticsearch/filter.rs +++ b/apps/labrinth/src/search/backend/elasticsearch/filter.rs @@ -1,4 +1,4 @@ -use eyre::{Result, eyre}; +use anyhow::{Result, anyhow}; use serde_json::{Value, json}; use crate::search::filter::{ @@ -28,10 +28,10 @@ pub(super) fn serialize_filter( ) -> Result { let (nodes, depth) = filter_complexity(filter); if nodes > MAX_FILTER_NODES { - return Err(eyre!("search filter has too many expressions")); + return Err(anyhow!("search filter has too many expressions")); } if depth > MAX_FILTER_DEPTH { - return Err(eyre!("search filter is nested too deeply")); + return Err(anyhow!("search filter is nested too deeply")); } let mut inner_hits_index = 0; @@ -89,7 +89,7 @@ fn plan_partitioned_and( FilterScope::Project => project.push(lower(expression)?), FilterScope::Version => version.push(lower(expression)?), FilterScope::Mixed => { - return Err(eyre!("could not partition mixed search filter")); + return Err(anyhow!("could not partition mixed search filter")); } } } @@ -133,7 +133,7 @@ fn lower(filter: &FilterExpr) -> Result { .map(or_query), FilterExpr::Predicate(predicate) => predicate_query(predicate), FilterExpr::Not(_) => { - Err(eyre!("search filter contains an unnormalized negation")) + Err(anyhow!("search filter contains an unnormalized negation")) } } } @@ -186,8 +186,11 @@ fn literal_value(field: &str, literal: &FilterLiteral) -> Result { Ok(Value::String(normalize_for_search(value))) } FilterLiteral::String(value) => Ok(Value::String(value.clone())), - FilterLiteral::Number(value) => serde_json::from_str(value) - .map_err(|error| eyre!("invalid numeric filter literal: {error}")), + FilterLiteral::Number(value) => { + serde_json::from_str(value).map_err(|error| { + anyhow!("invalid numeric filter literal: {error}") + }) + } FilterLiteral::Bool(value) => Ok(Value::Bool(*value)), } } @@ -297,7 +300,7 @@ fn to_dnf(filter: &FilterExpr) -> Result>> { for expression in expressions.iter() { clauses.extend(to_dnf(expression)?); if clauses.len() > MAX_DNF_CLAUSES { - return Err(eyre!( + return Err(anyhow!( "search filter has too many boolean clauses" )); } @@ -309,7 +312,7 @@ fn to_dnf(filter: &FilterExpr) -> Result>> { for expression in expressions.iter() { let right = to_dnf(expression)?; if clauses.len().saturating_mul(right.len()) > MAX_DNF_CLAUSES { - return Err(eyre!( + return Err(anyhow!( "search filter has too many boolean clauses" )); } @@ -327,7 +330,7 @@ fn to_dnf(filter: &FilterExpr) -> Result>> { Ok(clauses) } FilterExpr::Not(_) => { - Err(eyre!("search filter contains an unnormalized negation")) + Err(anyhow!("search filter contains an unnormalized negation")) } } } diff --git a/apps/labrinth/src/search/backend/elasticsearch/mod.rs b/apps/labrinth/src/search/backend/elasticsearch/mod.rs index cd18be9130f..2fdf6b9983e 100644 --- a/apps/labrinth/src/search/backend/elasticsearch/mod.rs +++ b/apps/labrinth/src/search/backend/elasticsearch/mod.rs @@ -5,8 +5,8 @@ //! into its project document. use crate::util::error::ApiContext as _; +use anyhow::{Result, anyhow}; use async_trait::async_trait; -use eyre::{Result, eyre}; use itertools::Itertools; use reqwest::{Method, Response, StatusCode}; use serde::Serialize; @@ -113,7 +113,7 @@ impl ElasticsearchClient { .request(Method::GET, &format!("/_alias/{alias}")) .send() .await - .wrap_err("failed to get Elasticsearch alias")?; + .context("failed to get Elasticsearch alias")?; if response.status() == StatusCode::NOT_FOUND { return Ok(None); } @@ -129,7 +129,7 @@ impl ElasticsearchClient { .request(Method::HEAD, &format!("/{index}")) .send() .await - .wrap_err("failed to check Elasticsearch index existence")?; + .context("failed to check Elasticsearch index existence")?; Ok(response.status().is_success()) } @@ -139,7 +139,7 @@ impl ElasticsearchClient { .json(schema) .send() .await - .wrap_err("failed to create Elasticsearch index")?; + .context("failed to create Elasticsearch index")?; response_json(response, "create Elasticsearch index").await?; Ok(()) } @@ -149,7 +149,7 @@ impl ElasticsearchClient { .request(Method::DELETE, &format!("/{index}")) .send() .await - .wrap_err("failed to delete Elasticsearch index")?; + .context("failed to delete Elasticsearch index")?; if response.status() == StatusCode::NOT_FOUND { return Ok(()); } @@ -182,7 +182,7 @@ impl ElasticsearchClient { .json(&json!({"actions": actions})) .send() .await - .wrap_err("failed to swap Elasticsearch alias")?; + .context("failed to swap Elasticsearch alias")?; response_json(response, "swap Elasticsearch alias").await?; Ok(()) } @@ -194,7 +194,7 @@ impl ElasticsearchClient { .body(body) .send() .await - .wrap_err("failed to execute Elasticsearch bulk request")?; + .context("failed to execute Elasticsearch bulk request")?; let body = response_json(response, "execute Elasticsearch bulk request") .await?; @@ -210,7 +210,7 @@ impl ElasticsearchClient { .take(10) .map(|error| error.to_string()) .join("; "); - return Err(eyre!( + return Err(anyhow!( "Elasticsearch bulk request contained failures: {failures}" )); } @@ -228,14 +228,14 @@ impl ElasticsearchClient { .json(&json!({"query": query})) .send() .await - .wrap_err("failed to delete Elasticsearch documents")?; + .context("failed to delete Elasticsearch documents")?; let body = response_json(response, "delete Elasticsearch documents").await?; if body["failures"] .as_array() .is_some_and(|failures| !failures.is_empty()) { - return Err(eyre!( + return Err(anyhow!( "Elasticsearch delete-by-query contained failures: {}", body["failures"] )); @@ -248,7 +248,7 @@ impl ElasticsearchClient { .request(Method::POST, &format!("/{index}/_refresh")) .send() .await - .wrap_err("failed to refresh Elasticsearch index")?; + .context("failed to refresh Elasticsearch index")?; response_json(response, "refresh Elasticsearch index").await?; Ok(()) } @@ -261,7 +261,7 @@ impl ElasticsearchClient { ) .send() .await - .wrap_err("failed to force-merge Elasticsearch index")?; + .context("failed to force-merge Elasticsearch index")?; response_json(response, "force-merge Elasticsearch index").await?; Ok(()) } @@ -272,14 +272,14 @@ async fn response_json(response: Response, operation: &str) -> Result { let body = response .text() .await - .wrap_err_with(|| format!("failed to read response for {operation}"))?; + .with_context(|| format!("failed to read response for {operation}"))?; let json = serde_json::from_str(&body).unwrap_or_else(|_| { json!({ "unparsed_response": body }) }); if !status.is_success() { - return Err(eyre!("{operation} failed ({status}): {json}")); + return Err(anyhow!("{operation} failed ({status}): {json}")); } Ok(json) } @@ -339,7 +339,7 @@ impl Elasticsearch { ) -> Result, ApiError> { let facet_part = if let Some(facets_json) = info.facets.as_deref() { from_legacy_v2_facets_json(facets_json) - .wrap_request_err("failed to parse facets")? + .request_context("failed to parse facets")? } else { None }; @@ -348,13 +348,13 @@ impl Elasticsearch { .filter(|filter| !filter.trim().is_empty()) .map(|filter| parse_expression(&filter)) .transpose() - .wrap_request_err("failed to parse filters")?; + .request_context("failed to parse filters")?; FilterExpr::and([facet_part, filter_part].into_iter().flatten()) .map(normalize) .map(|filter| { serialize_filter(&filter) - .wrap_request_err("failed to build search filter") + .request_context("failed to build search filter") }) .transpose() } @@ -386,10 +386,10 @@ impl Elasticsearch { .json(body) .send() .await - .wrap_internal_err("failed to execute Elasticsearch search")?; + .internal_context("failed to execute Elasticsearch search")?; let mut body = response_json(response, "execute Elasticsearch search") .await - .wrap_internal_err("parsing Elasticsearch search response")?; + .internal_context("parsing Elasticsearch search response")?; if sort_only && !body["hits"]["hits"].is_array() { body["hits"]["hits"] = Value::Array(Vec::new()); } @@ -408,18 +408,13 @@ impl Elasticsearch { ) .send() .await - .wrap_internal_err("failed to open Elasticsearch point in time")?; + .internal_context("failed to open Elasticsearch point in time")?; let body = response_json(response, "open Elasticsearch point in time") .await - .wrap_internal_err( - "parsing Elasticsearch point-in-time response", - )?; - body["id"] - .as_str() - .map(ToOwned::to_owned) - .wrap_internal_err( - "finding ID in Elasticsearch point-in-time response", - ) + .internal_context("parsing Elasticsearch point-in-time response")?; + body["id"].as_str().map(ToOwned::to_owned).internal_context( + "finding ID in Elasticsearch point-in-time response", + ) } async fn close_point_in_time(&self, id: &str) -> Result<(), ApiError> { @@ -429,12 +424,10 @@ impl Elasticsearch { .json(&json!({"id": id})) .send() .await - .wrap_internal_err("failed to close Elasticsearch point in time")?; + .internal_context("failed to close Elasticsearch point in time")?; response_json(response, "close Elasticsearch point in time") .await - .wrap_internal_err( - "parsing Elasticsearch point-in-time response", - )?; + .internal_context("parsing Elasticsearch point-in-time response")?; Ok(()) } @@ -454,7 +447,7 @@ impl Elasticsearch { .json(body) .send() .await - .wrap_internal_err( + .internal_context( "failed to execute Elasticsearch point in time search", )?; let mut body = response_json( @@ -462,7 +455,7 @@ impl Elasticsearch { "execute Elasticsearch point in time search", ) .await - .wrap_internal_err( + .internal_context( "parsing Elasticsearch point-in-time search response", )?; if sort_only && !body["hits"]["hits"].is_array() { @@ -483,7 +476,7 @@ impl Elasticsearch { let mut point_in_time_id = self .open_point_in_time(alias) .await - .wrap_api_err("executing `open_point_in_time`")?; + .api_context("executing `open_point_in_time`")?; let result = self .execute_deep_search_with_point_in_time( query, @@ -531,7 +524,7 @@ impl Elasticsearch { let body = self .execute_point_in_time_search(&body, true) .await - .wrap_api_err("executing `execute_point_in_time_search`")?; + .api_context("executing `execute_point_in_time_search`")?; if let Some(id) = body["pit_id"].as_str() { *point_in_time_id = id.to_string(); } @@ -596,7 +589,7 @@ impl Elasticsearch { let body = self .execute_point_in_time_search(&body, false) .await - .wrap_api_err("executing `execute_point_in_time_search`")?; + .api_context("executing `execute_point_in_time_search`")?; if let Some(id) = body["pit_id"].as_str() { *point_in_time_id = id.to_string(); } @@ -872,12 +865,12 @@ impl Elasticsearch { info: &SearchRequest, ) -> Result { let parsed = parse_search_request(info) - .wrap_api_err("executing `parse_search_request`")?; + .api_context("executing `parse_search_request`")?; let search_sort = parse_search_index(parsed.index, info.new_filters.as_deref()) - .wrap_api_err("executing `parse_search_index`")?; + .api_context("executing `parse_search_index`")?; let filter = Self::build_filter(info) - .wrap_api_err("executing `Self::build_filter`")?; + .api_context("executing `Self::build_filter`")?; let mut filters = vec![json!({"term": {"document_type": "project"}})]; if let Some(filter) = &filter { filters.push(filter.query.clone()); @@ -901,7 +894,7 @@ impl Elasticsearch { parsed.hits_per_page, ) .await - .wrap_api_err("executing `execute_deep_search`")? + .api_context("executing `execute_deep_search`")? } else { let body = Self::search_body( &query, @@ -914,7 +907,7 @@ impl Elasticsearch { ); self.execute_search(&alias, &body, false) .await - .wrap_api_err("executing `execute_search`")? + .api_context("executing `execute_search`")? }; let total_hits = body["hits"]["total"]["value"] .as_u64() @@ -1006,7 +999,7 @@ impl SearchBackend for Elasticsearch { self.config.index_chunk_size, ) .await - .wrap_err("failed to fetch projects from local DB")?; + .context("failed to fetch projects from local DB")?; if documents.projects.is_empty() { info!( "no more documents; indexed {total_projects} projects and {total_versions} versions in {chunk_index} chunks" @@ -1090,7 +1083,7 @@ impl SearchBackend for Elasticsearch { .request(Method::GET, "/_tasks?detailed=true") .send() .await - .wrap_err("failed to get Elasticsearch tasks")?; + .context("failed to get Elasticsearch tasks")?; response_json(response, "get Elasticsearch tasks").await } @@ -1102,7 +1095,7 @@ impl SearchBackend for Elasticsearch { .request(Method::POST, "/_tasks/_cancel") .send() .await - .wrap_err("failed to cancel Elasticsearch tasks")?; + .context("failed to cancel Elasticsearch tasks")?; response_json(response, "cancel Elasticsearch tasks").await?; } TasksCancelFilter::AllEnqueued => { @@ -1131,7 +1124,7 @@ impl SearchBackend for Elasticsearch { ) .send() .await - .wrap_err( + .context( "failed to cancel Elasticsearch task", )?; response_json( @@ -1181,10 +1174,10 @@ fn projects_to_bulk(documents: &[UploadSearchProject]) -> Result { )?; let mut source = serde_json::to_value(document) - .wrap_err("failed to serialize `UploadSearchProject`")?; - let object = source - .as_object_mut() - .ok_or_else(|| eyre!("project search document is not an object"))?; + .context("failed to serialize `UploadSearchProject`")?; + let object = source.as_object_mut().ok_or_else(|| { + anyhow!("project search document is not an object") + })?; object.insert( "document_type".to_string(), Value::String("project".to_string()), @@ -1210,10 +1203,10 @@ fn versions_to_bulk(documents: &[UploadSearchVersion]) -> Result { )?; let mut source = serde_json::to_value(document) - .wrap_err("failed to serialize `UploadSearchVersion`")?; + .context("failed to serialize `UploadSearchVersion`")?; source .as_object_mut() - .ok_or_else(|| eyre!("version search document is not an object"))? + .ok_or_else(|| anyhow!("version search document is not an object"))? .insert( "document_type".to_string(), json!({ diff --git a/apps/labrinth/src/search/incremental.rs b/apps/labrinth/src/search/incremental.rs index 2fe4bd7b415..a41ef87300e 100644 --- a/apps/labrinth/src/search/incremental.rs +++ b/apps/labrinth/src/search/incremental.rs @@ -83,7 +83,7 @@ impl IncrementalSearchQueue { } } - pub async fn drain(&self) -> eyre::Result<()> { + pub async fn drain(&self) -> anyhow::Result<()> { let operations = { let mut operations = self.operations.lock().await; mem::take(&mut *operations) diff --git a/apps/labrinth/src/search/incremental/consume.rs b/apps/labrinth/src/search/incremental/consume.rs index 8f51627b2e4..6acc63235d7 100644 --- a/apps/labrinth/src/search/incremental/consume.rs +++ b/apps/labrinth/src/search/incremental/consume.rs @@ -1,5 +1,5 @@ use actix_web::web; -use eyre::WrapErr; +use anyhow::Context; use rdkafka::{ Message, consumer::{CommitMode, Consumer, StreamConsumer}, @@ -39,11 +39,11 @@ pub async fn run( redis_pool: RedisPool, search_backend: web::Data, kafka_client: web::Data, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { let consumer = &kafka_client.incremental_index_search_consumer; consumer .subscribe(&[SEARCH_PROJECT_INDEX_QUEUE_TOPIC]) - .wrap_err("failed to subscribe to Kafka topic")?; + .context("failed to subscribe to Kafka topic")?; tracing::info!( kafka.topic = SEARCH_PROJECT_INDEX_QUEUE_TOPIC, @@ -69,7 +69,7 @@ async fn consume( redis_pool: &RedisPool, search_backend: &dyn SearchBackend, consumer: &StreamConsumer, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { // keep buffer capacity (pre-)allocated let mut messages = Vec::with_capacity(1024); loop { @@ -79,7 +79,7 @@ async fn consume( let first_message = consumer .recv() .await - .wrap_err("failed to receive Kafka message")?; + .context("failed to receive Kafka message")?; messages.push(first_message); let delay = Duration::from_secs( @@ -96,21 +96,21 @@ async fn consume( // // do a little trick with an `AsyncFnMut` closure // so that we can explicitly specify the return type - let mut collect_more_messages = async || -> eyre::Result<()> { + let mut collect_more_messages = async || -> anyhow::Result<()> { while messages.len() < ENV.SEARCH_INCREMENTAL_INDEX_BATCH_MAX_SIZE { let message = consumer .recv() .await - .wrap_err("failed to receive Kafka message")?; + .context("failed to receive Kafka message")?; messages.push(message); } - eyre::Ok(()) + anyhow::Ok(()) }; match tokio::time::timeout(delay, collect_more_messages()).await { Ok(Ok(())) | Err(_) => {} Ok(Err(err)) => { return Err( - err.wrap_err("failed to receive more Kafka messages") + err.context("failed to receive more Kafka messages") ); } } @@ -172,7 +172,7 @@ async fn consume_batch( search_backend: &dyn SearchBackend, consumer: &StreamConsumer, messages: impl IntoIterator>, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { let start = Instant::now(); let mut project_ids_to_change = HashSet::new(); @@ -192,7 +192,7 @@ async fn consume_batch( ); consumer .commit_message(&message, CommitMode::Async) - .wrap_err("failed to commit empty Kafka message")?; + .context("failed to commit empty Kafka message")?; continue; }; @@ -209,7 +209,7 @@ async fn consume_batch( ); consumer .commit_message(&message, CommitMode::Async) - .wrap_err("failed to commit malformed Kafka message")?; + .context("failed to commit malformed Kafka message")?; continue; } }; @@ -298,7 +298,7 @@ async fn consume_batch( batch_size = project_ids_with_all_versions_to_change.len() )) .await - .wrap_err_with(|| { + .with_context(|| { format!( "failed to build search documents for {} projects and all their versions", project_ids_with_all_versions_to_change.len() @@ -329,7 +329,7 @@ async fn consume_batch( version_count = version_ids_to_change.len() )) .await - .wrap_err_with(|| { + .with_context(|| { format!( "failed to build search documents for {} projects and {} versions", project_ids_with_version_changes.len(), @@ -366,7 +366,7 @@ async fn consume_batch( batch_size = project_ids_to_change.len() )) .await - .wrap_err_with(|| { + .with_context(|| { format!( "failed to build search documents for {} projects", project_ids_to_change.len() @@ -393,7 +393,7 @@ async fn consume_batch( removed_versions: &version_ids_to_change, }) .await - .wrap_err("failed to apply search index update")?; + .context("failed to apply search index update")?; info!( project_count = documents.projects.len(), version_count = documents.versions.len(), @@ -406,7 +406,7 @@ async fn consume_batch( for message in messages_to_commit { consumer .commit_message(&message, CommitMode::Async) - .wrap_err("failed to commit Kafka message")?; + .context("failed to commit Kafka message")?; } info!( @@ -424,7 +424,7 @@ pub async fn reindex_project_document( redis_pool: &RedisPool, search_backend: &dyn SearchBackend, project_id: ProjectId, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { reindex_project_documents( ro_pool, redis_pool, @@ -439,12 +439,12 @@ pub async fn reindex_project_documents( redis_pool: &RedisPool, search_backend: &dyn SearchBackend, project_ids: &[ProjectId], -) -> eyre::Result<()> { +) -> anyhow::Result<()> { info!("Creating project documents"); let projects = build_project_documents(ro_pool, redis_pool, project_ids) .instrument(info_span!("index", batch_size = project_ids.len())) .await - .wrap_err_with(|| { + .with_context(|| { format!( "failed to build search documents for {} projects", project_ids.len() diff --git a/apps/labrinth/src/search/indexing.rs b/apps/labrinth/src/search/indexing.rs index 546f6860314..43e6c8c8645 100644 --- a/apps/labrinth/src/search/indexing.rs +++ b/apps/labrinth/src/search/indexing.rs @@ -1,6 +1,6 @@ +use anyhow::Result; use chrono::{DateTime, Utc}; use dashmap::DashMap; -use eyre::Result; use futures::TryStreamExt; use heck::ToKebabCase; use itertools::Itertools; @@ -68,7 +68,7 @@ pub async fn index_local( redis: &RedisPool, cursor: i64, limit: i64, -) -> eyre::Result<(SearchDocumentBatch, i64)> { +) -> anyhow::Result<(SearchDocumentBatch, i64)> { info!("Indexing local projects!"); let searchable_statuses = searchable_statuses(); @@ -107,7 +107,7 @@ pub async fn index_local( }) .try_collect::>() .await - .wrap_err("failed to fetch projects")?; + .context("failed to fetch projects")?; let project_ids = db_projects.iter().map(|x| x.id.0).collect::>(); let Some(largest) = project_ids.iter().max() else { @@ -123,7 +123,7 @@ pub async fn build_project_documents( pool: &PgPool, redis: &RedisPool, project_ids: &[ProjectId], -) -> eyre::Result> { +) -> anyhow::Result> { let version_ids = HashSet::new(); Ok(build_search_document_batch( pool, @@ -139,7 +139,7 @@ pub async fn build_project_and_all_version_documents( pool: &PgPool, redis: &RedisPool, project_ids: &[ProjectId], -) -> eyre::Result { +) -> anyhow::Result { build_search_document_batch(pool, redis, project_ids, None).await } @@ -148,7 +148,7 @@ pub async fn build_version_change_documents( redis: &RedisPool, project_ids: &[ProjectId], version_ids: &[VersionId], -) -> eyre::Result { +) -> anyhow::Result { let version_ids = version_ids .iter() .copied() @@ -163,7 +163,7 @@ async fn build_search_document_batch( redis: &RedisPool, project_ids: &[ProjectId], version_ids: Option<&HashSet>, -) -> eyre::Result { +) -> anyhow::Result { let searchable_statuses = searchable_statuses(); let project_ids = project_ids .iter() @@ -200,7 +200,7 @@ async fn build_search_document_batch( }) .try_collect::>() .await - .wrap_err("failed to fetch project")?; + .context("failed to fetch project")?; build_search_documents(pool, redis, db_projects, version_ids).await } @@ -210,7 +210,7 @@ async fn build_search_documents( redis: &RedisPool, db_projects: Vec, version_ids: Option<&HashSet>, -) -> eyre::Result { +) -> anyhow::Result { let searchable_statuses = searchable_statuses(); let project_ids = db_projects.iter().map(|x| x.id.0).collect::>(); let project_components = db_projects @@ -220,7 +220,7 @@ async fn build_search_documents( let project_query_context = exp::project::fetch_query_context(&project_components, pool, redis) .await - .wrap_err("failed to fetch query context")?; + .context("failed to fetch query context")?; info!("Indexing local dependencies!"); @@ -268,7 +268,7 @@ async fn build_search_documents( }, ) .await - .wrap_err("failed to fetch project dependencies")?; + .context("failed to fetch project dependencies")?; struct PartialGallery { url: String, @@ -349,7 +349,7 @@ async fn build_search_documents( }, ) .await - .wrap_err("failed to fetch project disclosures")?; + .context("failed to fetch project disclosures")?; info!("Indexing local versions!"); let mut versions = load_project_versions(pool, project_ids.clone()).await?; @@ -723,7 +723,7 @@ async fn build_search_documents( .components .clone() .into_query(ProjectId::from(project.id), &project_query_context) - .wrap_err("failed to populate query components")?; + .context("failed to populate query components")?; let indexed_name = normalize_for_search(&project.name); project_uploads.push(UploadSearchProject { @@ -867,7 +867,7 @@ async fn load_project_versions( }, ) .await - .wrap_err("failed to fetch versions")?; + .context("failed to fetch versions")?; // Get project types, loaders #[derive(Default)] @@ -909,7 +909,7 @@ async fn load_project_versions( }) .try_collect() .await - .wrap_err("failed to fetch loaders and project types")?; + .context("failed to fetch loaders and project types")?; // Convert to partial versions let mut res_versions: HashMap> = diff --git a/apps/labrinth/src/search/mod.rs b/apps/labrinth/src/search/mod.rs index e85c52b5b8e..3ed9788696b 100644 --- a/apps/labrinth/src/search/mod.rs +++ b/apps/labrinth/src/search/mod.rs @@ -96,10 +96,10 @@ pub trait SearchBackend: Send + Sync { let mut results = self .search_for_project_raw(info) .await - .wrap_api_err("searching projects")?; + .api_context("searching projects")?; hydrate_search_results(&mut results.hits, redis) .await - .wrap_internal_err("hydrating search results from database")?; + .internal_context("hydrating search results from database")?; Ok(results) } @@ -112,25 +112,25 @@ pub trait SearchBackend: Send + Sync { &self, ro_pool: PgPool, redis: RedisPool, - ) -> eyre::Result<()>; + ) -> anyhow::Result<()>; async fn apply_update( &self, update: SearchIndexUpdate<'_>, - ) -> eyre::Result<()>; + ) -> anyhow::Result<()>; - async fn tasks(&self) -> eyre::Result; + async fn tasks(&self) -> anyhow::Result; async fn tasks_cancel( &self, filter: &TasksCancelFilter, - ) -> eyre::Result<()>; + ) -> anyhow::Result<()>; } async fn hydrate_search_results( hits: &mut [ResultSearchProject], redis_pool: &RedisPool, -) -> eyre::Result<()> { +) -> anyhow::Result<()> { // Minecraft Java servers should fetch the latest player count that we have // from Redis, rather than the (pretty stale) data from search backend // TODO: this block should be made generic over the component type, diff --git a/apps/labrinth/src/test/db.rs b/apps/labrinth/src/test/db.rs index 428722cb090..f54e482ac86 100644 --- a/apps/labrinth/src/test/db.rs +++ b/apps/labrinth/src/test/db.rs @@ -1,5 +1,5 @@ use crate::database::Executor; -use eyre::{Context, Result}; +use anyhow::{Context, Result}; use sqlx::AssertSqlSafe; use crate::database::{PgPool, models::DBUserId}; @@ -46,9 +46,9 @@ pub async fn mark_email_verified(db: &PgPool, user_id: DBUserId) -> Result<()> { ) .execute(db) .await - .wrap_err("failed to mark user email as verified")?; + .context("failed to mark user email as verified")?; - eyre::ensure!(result.rows_affected() == 1, "user does not exist"); + anyhow::ensure!(result.rows_affected() == 1, "user does not exist"); Ok(()) } @@ -74,7 +74,7 @@ pub mod user_id { pub async fn add_minecraft_meta_dummy_data(db: &PgPool) -> Result<()> { db.execute(include_str!("../../fixtures/minecraft-meta-dummy-data.sql")) .await - .wrap_err("failed to add Minecraft metadata dummy data")?; + .context("failed to add Minecraft metadata dummy data")?; Ok(()) } @@ -110,7 +110,7 @@ pub async fn add_dummy_data(db: &PgPool) -> Result<()> { ), )) .await - .wrap_err("failed to add dummy data")?; + .context("failed to add dummy data")?; for user_id in [ user_id::ADMIN, diff --git a/apps/labrinth/src/util/avalara1099.rs b/apps/labrinth/src/util/avalara1099.rs index 8b9ebfb3290..57d0387ccb8 100644 --- a/apps/labrinth/src/util/avalara1099.rs +++ b/apps/labrinth/src/util/avalara1099.rs @@ -3,6 +3,7 @@ use crate::env::ENV; use crate::routes::ApiError; use crate::util::error::ApiContext as _; use crate::util::error::Context as _; +use anyhow::anyhow; use ariadne::ids::base62_impl::to_base62; use chrono::Datelike; use serde::{Deserialize, Serialize}; @@ -65,7 +66,7 @@ pub async fn request_form( let (request_builder, company_id) = team_request(reqwest::Method::POST, "/form_requests") - .wrap_api_err("executing `team_request`")?; + .api_context("executing `team_request`")?; let response = request_builder .json(&DataWrapper { @@ -88,18 +89,18 @@ pub async fn request_form( }) .send() .await - .wrap_internal_err("deserializing HTTP response")?; + .internal_context("deserializing HTTP response")?; Ok(if response.status().is_success() { Ok(response .json::>() .await - .wrap_internal_err("deserializing HTTP response")?) + .internal_context("deserializing HTTP response")?) } else { Err(response .json() .await - .wrap_internal_err("deserializing HTTP response")?) + .internal_context("deserializing HTTP response")?) }) } @@ -114,18 +115,18 @@ pub async fn check_form( &format!( "/w9forms?filter[reference_id_eq]={reference_id}&page[number]=1&page[size]=1" ), - ).wrap_api_err("executing `team_request`")?; + ).api_context("executing `team_request`")?; let response = request_builder .send() .await - .wrap_internal_err("sending HTTP request")?; + .internal_context("sending HTTP request")?; Ok(if response.status().is_success() { let body = response .text() .await - .wrap_internal_err("reading HTTP response body")?; + .internal_context("reading HTTP response body")?; let serde_result = serde_json::from_str::>(&body); @@ -134,7 +135,7 @@ pub async fn check_form( Ok(list_wrapper.data.pop().map(|data| DataWrapper { data })) } Err(e) => { - return Err(ApiError::Request(eyre::eyre!(format!( + return Err(ApiError::Request(anyhow!(format!( "Error parsing avalara1099 response: {e}. Actual response body: {body}" )))); } @@ -143,7 +144,7 @@ pub async fn check_form( Err(response .json() .await - .wrap_internal_err("deserializing HTTP response")?) + .internal_context("deserializing HTTP response")?) }) } diff --git a/apps/labrinth/src/util/captcha.rs b/apps/labrinth/src/util/captcha.rs index 70154a06daa..09f40fbbd99 100644 --- a/apps/labrinth/src/util/captcha.rs +++ b/apps/labrinth/src/util/captcha.rs @@ -2,6 +2,7 @@ use crate::env::ENV; use crate::routes::ApiError; use crate::util::error::Context as _; use actix_web::HttpRequest; +use anyhow::anyhow; use serde::Deserialize; use std::collections::HashMap; use xredis::RedisPool; @@ -32,7 +33,7 @@ pub async fn check_turnstile( conn_info.peer_addr() }; - let ip_addr = ip_addr.wrap_request_err("captcha validation failed")?; + let ip_addr = ip_addr.request_context("captcha validation failed")?; let client = reqwest::Client::new(); @@ -52,11 +53,11 @@ pub async fn check_turnstile( .form(&form) .send() .await - .wrap_request_err("captcha validation failed")? + .request_context("captcha validation failed")? .json() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("captcha validation failed")?; + .map_err(|err| anyhow!(err)) + .request_context("captcha validation failed")?; if !val.success { return Ok(false); @@ -74,7 +75,7 @@ async fn mark_token_used( let mut conn = redis .connect() .await - .wrap_internal_err("connecting to Redis")?; + .internal_context("connecting to Redis")?; let key = conn.key() .with_slot(USED_TURNSTILE_NAMESPACE, challenge, challenge); @@ -87,7 +88,7 @@ async fn mark_token_used( .arg(TURNSTILE_TOKEN_LIFETIME_SECS) .query_async(&mut conn) .await - .wrap_internal_err("marking captcha token as used")?; + .internal_context("marking captcha token as used")?; Ok(newly_set.is_some()) } diff --git a/apps/labrinth/src/util/cel.rs b/apps/labrinth/src/util/cel.rs index 6d38f462042..7b5f48bd603 100644 --- a/apps/labrinth/src/util/cel.rs +++ b/apps/labrinth/src/util/cel.rs @@ -7,8 +7,8 @@ use std::{ use ::cel::{ Context as CelContext, ExecutionError, Program as CelProgram, Value, }; +use anyhow::{Context as _, Result, anyhow}; use chumsky::{Parser, prelude::*}; -use eyre::{Result, WrapErr, eyre}; use serde::Serialize; use thiserror::Error; use url::{Host, Url}; @@ -128,14 +128,14 @@ pub struct Program { impl Program { pub fn compile(source: &str) -> Result { let preprocessed = preprocess(source) - .wrap_err("failed to preprocess cel expression")?; + .context("failed to preprocess cel expression")?; let bindings = preprocessed .bindings .into_iter() .map(|binding| { let inner = CelProgram::compile(&binding.expression) - .map_err(|error| eyre!(error)) - .wrap_err_with(|| { + .map_err(|error| anyhow!(error)) + .with_context(|| { format!( "failed to compile `#bind {}` on line {}", binding.name, binding.line @@ -149,7 +149,7 @@ impl Program { }) .collect::>>()?; let inner = CelProgram::compile(&preprocessed.expression) - .map_err(|error| eyre!(error))?; + .map_err(|error| anyhow!(error))?; Ok(Self { inner, bindings }) } diff --git a/apps/labrinth/src/util/error.rs b/apps/labrinth/src/util/error.rs index 8b52a20c7b1..c825e892b6d 100644 --- a/apps/labrinth/src/util/error.rs +++ b/apps/labrinth/src/util/error.rs @@ -8,25 +8,25 @@ use crate::routes::ApiError; /// Adds context to an [`ApiError`] while preserving its HTTP status variant. pub trait ApiContext: Sized { /// Wraps the report held by the error variant with a lazily-created message. - fn wrap_api_err_with(self, f: impl FnOnce() -> D) -> Result + fn api_context_with(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static; /// Wraps the report held by the error variant with the given message. - fn wrap_api_err(self, msg: D) -> Result + fn api_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_api_err_with(|| msg) + self.api_context_with(|| msg) } } impl ApiContext for Result { - fn wrap_api_err_with(self, f: impl FnOnce() -> D) -> Result + fn api_context_with(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.map_err(|error| error.wrap_err(f())) + self.map_err(|error| error.context(f())) } } @@ -36,227 +36,226 @@ impl ApiContext for Result { reason = "this trait's purpose is improving error handling" )] pub trait Context: Sized { - /// Maps the error variant into an [`eyre::Report`], creating the message + /// Maps the error variant into an [`anyhow::Error`], creating the message /// using `f`. - fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result + fn with_context(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static; - /// Maps the error variant into an [`eyre::Report`] with the given message. + /// Maps the error variant into an [`anyhow::Error`] with the given message. #[inline] - fn wrap_err(self, msg: D) -> Result + fn context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(|| msg) + self.with_context(|| msg) } /// Maps the error variant into an [`ApiError::Internal`] using the closure to create the message. #[inline] - fn wrap_internal_err_with( + fn internal_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::Internal) + self.with_context(f).map_err(ApiError::Internal) } /// Maps the error variant into an [`ApiError::Internal`] with the given message. #[inline] - fn wrap_internal_err(self, msg: D) -> Result + fn internal_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_internal_err_with(|| msg) + self.internal_context_with(|| msg) } /// Maps the error variant into an [`ApiError::Request`] using the closure to create the message. #[inline] - fn wrap_request_err_with( + fn request_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::Request) + self.with_context(f).map_err(ApiError::Request) } /// Maps the error variant into an [`ApiError::Request`] with the given message. #[inline] - fn wrap_request_err(self, msg: D) -> Result + fn request_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_request_err_with(|| msg) + self.request_context_with(|| msg) } /// Maps the error variant into an [`ApiError::Auth`] using the closure to create the message. #[inline] - fn wrap_auth_err_with(self, f: impl FnOnce() -> D) -> Result + fn auth_context_with(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::Auth) + self.with_context(f).map_err(ApiError::Auth) } /// Maps the error variant into an [`ApiError::Auth`] with the given message. #[inline] - fn wrap_auth_err(self, msg: D) -> Result + fn auth_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_auth_err_with(|| msg) + self.auth_context_with(|| msg) } /// Maps the error variant into an [`ApiError::NotFound`] using the closure to create the message. #[inline] - fn wrap_not_found_err_with( + fn not_found_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::NotFound) + self.with_context(f).map_err(ApiError::NotFound) } /// Maps the error variant into an [`ApiError::NotFound`] with the given message. #[inline] - fn wrap_not_found_err(self, msg: D) -> Result + fn not_found_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_not_found_err_with(|| msg) + self.not_found_context_with(|| msg) } /// Maps the error variant into an [`ApiError::Conflict`] using the closure to create the message. #[inline] - fn wrap_conflict_err_with( + fn conflict_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::Conflict) + self.with_context(f).map_err(ApiError::Conflict) } /// Maps the error variant into an [`ApiError::Conflict`] with the given message. #[inline] - fn wrap_conflict_err(self, msg: D) -> Result + fn conflict_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_conflict_err_with(|| msg) + self.conflict_context_with(|| msg) } /// Maps the error variant into an [`ApiError::FailedDependency`] using the closure to create the message. #[inline] - fn wrap_failed_dependency_err_with( + fn failed_dependency_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::FailedDependency) + self.with_context(f).map_err(ApiError::FailedDependency) } /// Maps the error variant into an [`ApiError::FailedDependency`] with the given message. #[inline] - fn wrap_failed_dependency_err(self, msg: D) -> Result + fn failed_dependency_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_failed_dependency_err_with(|| msg) + self.failed_dependency_context_with(|| msg) } /// Maps the error variant into an [`ApiError::PreconditionRequired`] using the closure to create the message. #[inline] - fn wrap_precondition_required_err_with( + fn precondition_required_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f) - .map_err(ApiError::PreconditionRequired) + self.with_context(f).map_err(ApiError::PreconditionRequired) } /// Maps the error variant into an [`ApiError::PreconditionRequired`] with the given message. #[inline] - fn wrap_precondition_required_err(self, msg: D) -> Result + fn precondition_required_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_precondition_required_err_with(|| msg) + self.precondition_required_context_with(|| msg) } /// Maps the error variant into an [`ApiError::PreconditionFailed`] using the closure to create the message. #[inline] - fn wrap_precondition_failed_err_with( + fn precondition_failed_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::PreconditionFailed) + self.with_context(f).map_err(ApiError::PreconditionFailed) } /// Maps the error variant into an [`ApiError::PreconditionFailed`] with the given message. #[inline] - fn wrap_precondition_failed_err(self, msg: D) -> Result + fn precondition_failed_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_precondition_failed_err_with(|| msg) + self.precondition_failed_context_with(|| msg) } /// Maps the error variant into an [`ApiError::RateLimit`] using the closure to create the message. #[inline] - fn wrap_rate_limit_err_with( + fn rate_limit_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::RateLimit) + self.with_context(f).map_err(ApiError::RateLimit) } /// Maps the error variant into an [`ApiError::RateLimit`] with the given message. #[inline] - fn wrap_rate_limit_err(self, msg: D) -> Result + fn rate_limit_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_rate_limit_err_with(|| msg) + self.rate_limit_context_with(|| msg) } } impl Context for Result where - Self: eyre::WrapErr, + Self: anyhow::Context, { - fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result + fn with_context(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { - eyre::WrapErr::wrap_err_with(self, f) + anyhow::Context::with_context(self, f) } } impl Context for Option { - fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result + fn with_context(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.ok_or_else(|| eyre::Report::msg(f())) + self.ok_or_else(|| anyhow::Error::msg(f())) } } @@ -264,22 +263,23 @@ impl Context for Option { mod tests { use super::*; use actix_web::{ResponseError, http::StatusCode}; + use anyhow::anyhow; #[test] fn test_api_error_display() { - let error = ApiError::Internal(eyre::eyre!("test internal error")); + let error = ApiError::Internal(anyhow!("test internal error")); assert!(error.to_string().contains("test internal error")); - let error = ApiError::Request(eyre::eyre!("test request error")); + let error = ApiError::Request(anyhow!("test request error")); assert!(error.to_string().contains("test request error")); - let error = ApiError::Auth(eyre::eyre!("test auth error")); + let error = ApiError::Auth(anyhow!("test auth error")); assert!(error.to_string().contains("test auth error")); } #[test] fn test_api_error_debug() { - let error = ApiError::Internal(eyre::eyre!("test error")); + let error = ApiError::Internal(anyhow!("test error")); let debug_str = format!("{error:?}"); assert!(debug_str.contains("Internal")); assert!(debug_str.contains("test error")); @@ -287,33 +287,32 @@ mod tests { #[test] fn test_response_error_status_codes() { - let internal_error = ApiError::Internal(eyre::eyre!("internal error")); + let internal_error = ApiError::Internal(anyhow!("internal error")); assert_eq!( internal_error.status_code(), StatusCode::INTERNAL_SERVER_ERROR ); - let request_error = ApiError::Request(eyre::eyre!("request error")); + let request_error = ApiError::Request(anyhow!("request error")); assert_eq!(request_error.status_code(), StatusCode::BAD_REQUEST); - let auth_error = ApiError::Auth(eyre::eyre!("auth error")); + let auth_error = ApiError::Auth(anyhow!("auth error")); assert_eq!(auth_error.status_code(), StatusCode::UNAUTHORIZED); - let not_found_error = - ApiError::NotFound(eyre::eyre!("not found error")); + let not_found_error = ApiError::NotFound(anyhow!("not found error")); assert_eq!(not_found_error.status_code(), StatusCode::NOT_FOUND); - let conflict_error = ApiError::Conflict(eyre::eyre!("conflict error")); + let conflict_error = ApiError::Conflict(anyhow!("conflict error")); assert_eq!(conflict_error.status_code(), StatusCode::CONFLICT); let dependency_error = - ApiError::FailedDependency(eyre::eyre!("dependency error")); + ApiError::FailedDependency(anyhow!("dependency error")); assert_eq!( dependency_error.status_code(), StatusCode::FAILED_DEPENDENCY ); - let required_error = ApiError::PreconditionRequired(eyre::eyre!( + let required_error = ApiError::PreconditionRequired(anyhow!( "precondition required error" )); assert_eq!( @@ -321,13 +320,11 @@ mod tests { StatusCode::PRECONDITION_REQUIRED ); - let failed_error = ApiError::PreconditionFailed(eyre::eyre!( - "precondition failed error" - )); + let failed_error = + ApiError::PreconditionFailed(anyhow!("precondition failed error")); assert_eq!(failed_error.status_code(), StatusCode::PRECONDITION_FAILED); - let rate_limit_error = - ApiError::RateLimit(eyre::eyre!("rate limit error")); + let rate_limit_error = ApiError::RateLimit(anyhow!("rate limit error")); assert_eq!( rate_limit_error.status_code(), StatusCode::TOO_MANY_REQUESTS @@ -336,7 +333,7 @@ mod tests { #[test] fn test_response_error_response() { - let error = ApiError::Request(eyre::eyre!("test request error")); + let error = ApiError::Request(anyhow!("test request error")); let response = error.error_response(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); @@ -348,14 +345,14 @@ mod tests { #[test] fn test_context_trait_result() { let result: Result = Ok(42); - let wrapped = result.wrap_err("context message"); + let wrapped = result.context("context message"); assert_eq!(wrapped.unwrap(), 42); let result: Result = Err(std::io::Error::new( std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_err("context message"); + let wrapped = result.context("context message"); assert!(wrapped.is_err()); assert!(wrapped.unwrap_err().to_string().contains("context message")); } @@ -363,11 +360,11 @@ mod tests { #[test] fn test_context_trait_option() { let option: Option = Some(42); - let wrapped = option.wrap_err("context message"); + let wrapped = option.context("context message"); assert_eq!(wrapped.unwrap(), 42); let option: Option = None; - let wrapped = option.wrap_err("context message"); + let wrapped = option.context("context message"); assert!(wrapped.is_err()); assert_eq!(wrapped.unwrap_err().to_string(), "context message"); } @@ -378,7 +375,7 @@ mod tests { std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_internal_err("internal error context"); + let wrapped = result.internal_context("internal error context"); assert!(wrapped.is_err()); match wrapped.unwrap_err() { @@ -395,7 +392,7 @@ mod tests { std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_request_err("request error context"); + let wrapped = result.request_context("request error context"); assert!(wrapped.is_err()); match wrapped.unwrap_err() { @@ -412,7 +409,7 @@ mod tests { std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_auth_err("auth error context"); + let wrapped = result.auth_context("auth error context"); assert!(wrapped.is_err()); match wrapped.unwrap_err() { @@ -427,20 +424,20 @@ mod tests { fn test_context_trait_status_errors() { let not_found: Option = None; assert!(matches!( - not_found.wrap_not_found_err("missing value").unwrap_err(), + not_found.not_found_context("missing value").unwrap_err(), ApiError::NotFound(_) )); let conflict: Option = None; assert!(matches!( - conflict.wrap_conflict_err("conflicting value").unwrap_err(), + conflict.conflict_context("conflicting value").unwrap_err(), ApiError::Conflict(_) )); let dependency: Option = None; assert!(matches!( dependency - .wrap_failed_dependency_err("dependency failed") + .failed_dependency_context("dependency failed") .unwrap_err(), ApiError::FailedDependency(_) )); @@ -448,7 +445,7 @@ mod tests { let required: Option = None; assert!(matches!( required - .wrap_precondition_required_err("precondition required") + .precondition_required_context("precondition required") .unwrap_err(), ApiError::PreconditionRequired(_) )); @@ -456,7 +453,7 @@ mod tests { let failed: Option = None; assert!(matches!( failed - .wrap_precondition_failed_err("precondition failed") + .precondition_failed_context("precondition failed") .unwrap_err(), ApiError::PreconditionFailed(_) )); @@ -464,7 +461,7 @@ mod tests { let rate_limit: Option = None; assert!(matches!( rate_limit - .wrap_rate_limit_err("rate limit exceeded") + .rate_limit_context("rate limit exceeded") .unwrap_err(), ApiError::RateLimit(_) )); @@ -473,8 +470,8 @@ mod tests { #[test] fn test_api_context_preserves_status_variant() { let result: Result<(), ApiError> = - Err(ApiError::NotFound(eyre::eyre!("missing value"))); - let error = result.wrap_api_err("fetching test value").unwrap_err(); + Err(ApiError::NotFound(anyhow!("missing value"))); + let error = result.api_context("fetching test value").unwrap_err(); match error { ApiError::NotFound(report) => { @@ -492,7 +489,7 @@ mod tests { "not found", )); let wrapped = - result.wrap_err_with(|| format!("context with {}", "dynamic")); + result.with_context(|| format!("context with {}", "dynamic")); assert!(wrapped.is_err()); assert!( diff --git a/apps/labrinth/src/util/gotenberg.rs b/apps/labrinth/src/util/gotenberg.rs index 6fd4f3661b6..1edbb7891ad 100644 --- a/apps/labrinth/src/util/gotenberg.rs +++ b/apps/labrinth/src/util/gotenberg.rs @@ -76,11 +76,11 @@ pub struct GotenbergClient { impl GotenbergClient { /// Initialize the client from environment variables. - pub fn from_env(redis: RedisPool) -> eyre::Result { + pub fn from_env(redis: RedisPool) -> anyhow::Result { let client = reqwest::Client::builder() .user_agent("Modrinth") .build() - .wrap_err("failed to build reqwest client")?; + .context("failed to build reqwest client")?; Ok(Self { client, @@ -115,13 +115,13 @@ impl GotenbergClient { .get(template_url) .send() .await - .wrap_internal_err( + .internal_context( "failed to request payment statement template", )?; - let resp = resp.error_for_status().wrap_internal_err( + let resp = resp.error_for_status().internal_context( "failed to fetch payment statement template (bad status)", )?; - resp.text().await.wrap_internal_err( + resp.text().await.internal_context( "failed to read payment statement template body", )? }; @@ -133,7 +133,7 @@ impl GotenbergClient { reqwest::multipart::Part::text(filled_html) .file_name("index.html") .mime_str("text/html") - .wrap_internal_err("invalid mime type for html part")?, + .internal_context("invalid mime type for html part")?, ); let success_webhook = format!("{}/success", self.callback_base); @@ -165,9 +165,9 @@ impl GotenbergClient { .multipart(form) .send() .await - .wrap_internal_err("failed to submit HTML to Gotenberg")? + .internal_context("failed to submit HTML to Gotenberg")? .error_for_status() - .wrap_internal_err("received an error status from Gotenberg")?; + .internal_context("received an error status from Gotenberg")?; Ok(()) } @@ -193,7 +193,7 @@ impl GotenbergClient { ) -> Result { self.generate_payment_statement(statement) .await - .wrap_api_err("executing `generate_payment_statement`")?; + .api_context("executing `generate_payment_statement`")?; let timeout_ms = ENV.GOTENBERG_TIMEOUT; let redis_timeout_ms = @@ -208,15 +208,15 @@ impl GotenbergClient { .brpop(&response_key, Duration::from_millis(redis_timeout_ms)), ) .await - .wrap_internal_err("timed out generating Gotenberg document")? - .wrap_internal_err("failed to get document over Redis")? - .wrap_internal_err("no document was returned from Redis")?; + .internal_context("timed out generating Gotenberg document")? + .internal_context("failed to get document over Redis")? + .internal_context("no document was returned from Redis")?; let document = postcard::from_bytes::< Result, >(&document) - .wrap_internal_err("failed to deserialize Redis document response")? - .wrap_internal_err("failed to generate Gotenberg document")?; + .internal_context("failed to deserialize Redis document response")? + .internal_context("failed to generate Gotenberg document")?; Ok(document) } diff --git a/apps/labrinth/src/util/img.rs b/apps/labrinth/src/util/img.rs index 688e9bd0a85..c2f99f220ce 100644 --- a/apps/labrinth/src/util/img.rs +++ b/apps/labrinth/src/util/img.rs @@ -5,8 +5,8 @@ use crate::file_hosting::{FileHost, FileHostPublicity}; use crate::models::images::ImageContext; use crate::routes::ApiError; use crate::util::error::Context as _; +use anyhow::{Result, anyhow}; use color_thief::ColorFormat; -use eyre::{Result, eyre}; use hex::ToHex; use image::imageops::FilterType; use image::{ @@ -56,7 +56,7 @@ pub async fn upload_image_optimized( file_host: &dyn FileHost, ) -> Result { let content_type = crate::util::ext::get_image_content_type(file_extension) - .wrap_request_err_with(|| { + .request_context_with(|| { format!("invalid format for image: {file_extension}") })?; @@ -69,9 +69,9 @@ pub async fn upload_image_optimized( target_width, min_aspect_ratio, ) - .wrap_request_err("processing uploaded image")?; + .request_context("processing uploaded image")?; let color = get_color_from_img(&bytes) - .wrap_request_err("extracting color from uploaded image")?; + .request_context("extracting color from uploaded image")?; // Only upload the processed image if it's smaller than the original let processed_upload_data = if processed_image.len() < bytes.len() { @@ -90,7 +90,7 @@ pub async fn upload_image_optimized( processed_image, ) .await - .wrap_internal_err("uploading file to file host")?, + .internal_context("uploading file to file host")?, ) } else { None @@ -104,7 +104,7 @@ pub async fn upload_image_optimized( bytes, ) .await - .wrap_internal_err("uploading file to file host")?; + .internal_context("uploading file to file host")?; let url = format!("{}/{}", cdn_url, upload_data.file_name); Ok(UploadImageResult { @@ -135,11 +135,11 @@ fn process_image( } let mut img = image::load_from_memory(&image_bytes) - .wrap_err("loading image from memory")?; + .context("loading image from memory")?; - let webp_bytes = convert_to_webp(&img).wrap_err("converting to WebP")?; + let webp_bytes = convert_to_webp(&img).context("converting to WebP")?; img = image::load_from_memory(&webp_bytes) - .wrap_err("loading WebP image from memory")?; + .context("loading WebP image from memory")?; // Resize the image let (orig_width, orig_height) = img.dimensions(); @@ -165,7 +165,7 @@ fn process_image( // Optimize and compress let mut output = Vec::new(); img.write_to(&mut Cursor::new(&mut output), ImageFormat::WebP) - .wrap_err("writing image")?; + .context("writing image")?; Ok((bytes::Bytes::from(output), "webp".to_string())) } @@ -176,7 +176,7 @@ fn convert_to_webp(img: &DynamicImage) -> Result> { // Quality factor: 0-100, 75 is a good balance let webp = encoder .encode_simple(false, 75.0) - .map_err(|_| eyre!("encoding image"))?; + .map_err(|_| anyhow!("encoding image"))?; Ok(webp.to_vec()) } @@ -195,7 +195,7 @@ pub async fn delete_old_images( file_host .delete_file(icon_path, publicity) .await - .wrap_internal_err("deleting file from file host")?; + .internal_context("deleting file from file host")?; } } @@ -206,7 +206,7 @@ pub async fn delete_old_images( file_host .delete_file(icon_path, publicity) .await - .wrap_internal_err("deleting file from file host")?; + .internal_context("deleting file from file host")?; } } @@ -225,7 +225,7 @@ pub async fn delete_unused_images( let uploaded_images = database::models::DBImage::get_many_contexted(context, transaction) .await - .wrap_internal_err("fetching images from database")?; + .internal_context("fetching images from database")?; for image in uploaded_images { let mut should_delete = true; @@ -239,10 +239,10 @@ pub async fn delete_unused_images( if should_delete { image_item::DBImage::remove(image.id, transaction, redis) .await - .wrap_internal_err("deleting image from database")?; + .internal_context("deleting image from database")?; image_item::DBImage::clear_cache(image.id, redis) .await - .wrap_internal_err("clearing cached data from Redis")?; + .internal_context("clearing cached data from Redis")?; } } diff --git a/apps/labrinth/src/util/kafka.rs b/apps/labrinth/src/util/kafka.rs index 14d5a82154e..f026a7221ff 100644 --- a/apps/labrinth/src/util/kafka.rs +++ b/apps/labrinth/src/util/kafka.rs @@ -4,8 +4,8 @@ use std::{ }; use crate::env::ENV; +use anyhow::{Context, anyhow, ensure}; use chrono::{DateTime, Utc}; -use eyre::{WrapErr, ensure, eyre}; use rdkafka::{ ClientConfig, Offset, TopicPartitionList, consumer::{Consumer, StreamConsumer}, @@ -28,14 +28,14 @@ pub struct KafkaClientState { } impl KafkaClientState { - pub async fn new() -> eyre::Result { + pub async fn new() -> anyhow::Result { let client = producer_config() .create() - .wrap_err("failed to create Kafka producer")?; + .context("failed to create Kafka producer")?; let incremental_index_search_consumer = create_consumer( INCREMENTAL_INDEX_SEARCH_TASK, ) - .wrap_err("failed to create incremental search Kafka consumer")?; + .context("failed to create incremental search Kafka consumer")?; tracing::info!( kafka.bootstrap_servers = ?ENV.KAFKA_BOOTSTRAP_SERVERS.0, @@ -46,13 +46,13 @@ impl KafkaClientState { let project_flag_run_producer = tokio::task::spawn_blocking(create_project_flag_run_producer) .await - .wrap_err( + .context( "joining project flag run producer initialization", )??; let project_flag_lag_consumer = create_consumer( crate::queue::moderation::project_flag_run::PROJECT_FLAG_RUN_CONSUMER_GROUP, - ).wrap_err("creating project flag lag client")?; + ).context("creating project flag lag client")?; Ok(Self { project_flag_lag_consumer: Arc::new(project_flag_lag_consumer), @@ -65,7 +65,7 @@ impl KafkaClientState { } /// Counts group members assigned partitions of the project scan topic. - pub async fn project_flag_scan_consumers(&self) -> eyre::Result { + pub async fn project_flag_scan_consumers(&self) -> anyhow::Result { let consumer = self.project_flag_lag_consumer.clone(); tokio::task::spawn_blocking(move || { use crate::queue::moderation::project_flag_run::{ @@ -76,7 +76,7 @@ impl KafkaClientState { Some(PROJECT_FLAG_RUN_CONSUMER_GROUP), KAFKA_OPERATION_INTERVAL, ) - .wrap_err("fetching project flag consumer group members")?; + .context("fetching project flag consumer group members")?; let mut count = 0; for group in groups .groups() @@ -104,44 +104,44 @@ impl KafkaClientState { Ok(count) }) .await - .wrap_err("joining project flag consumer group lookup")? + .context("joining project flag consumer group lookup")? } /// Reads topic-wide group lag without subscribing, consuming, or committing offsets. - pub async fn project_flag_scan_lag(&self) -> eyre::Result { + pub async fn project_flag_scan_lag(&self) -> anyhow::Result { let consumer = self.project_flag_lag_consumer.clone(); tokio::task::spawn_blocking(move || { let topic = crate::queue::moderation::project_flag_run::PROJECT_FLAG_RUN_TOPIC; let deadline = Instant::now() + KAFKA_OPERATION_INTERVAL; let remaining = || deadline.checked_duration_since(Instant::now()) - .ok_or_else(|| eyre!("timed out fetching project flag scan lag")); + .ok_or_else(|| anyhow!("timed out fetching project flag scan lag")); let metadata = consumer.fetch_metadata(Some(topic), remaining()?) - .wrap_err("fetching project flag topic metadata")?; + .context("fetching project flag topic metadata")?; let metadata = metadata.topics().iter().find(|metadata| metadata.name() == topic) - .ok_or_else(|| eyre!("project flag topic metadata missing"))?; + .ok_or_else(|| anyhow!("project flag topic metadata missing"))?; if let Some(error) = metadata.error() { - return Err(eyre!("project flag topic metadata error: {error:?}")); + return Err(anyhow!("project flag topic metadata error: {error:?}")); } let mut partitions = TopicPartitionList::new(); for partition in metadata.partitions() { partitions.add_partition(topic, partition.id()); } let committed = consumer.committed_offsets(partitions, remaining()?) - .wrap_err("fetching project flag consumer group offsets")?; + .context("fetching project flag consumer group offsets")?; let mut lag = 0i64; for partition in committed.elements() { - partition.error().wrap_err("fetching project flag partition offset")?; + partition.error().context("fetching project flag partition offset")?; let (low, high) = consumer.fetch_watermarks(topic, partition.partition(), remaining()?) - .wrap_err("fetching project flag partition watermarks")?; + .context("fetching project flag partition watermarks")?; let offset = match partition.offset() { Offset::Offset(offset) => offset.max(low), Offset::Invalid | Offset::Beginning => low, - offset => return Err(eyre!("unexpected project flag consumer offset: {offset:?}")), + offset => return Err(anyhow!("unexpected project flag consumer offset: {offset:?}")), }; lag = lag.saturating_add(high.saturating_sub(offset).max(0)); } Ok(lag) - }).await.wrap_err("joining project flag scan lag lookup")? + }).await.context("joining project flag scan lag lookup")? } } @@ -149,7 +149,7 @@ impl KafkaClientState { fn assignment_has_topic( mut assignment: &[u8], topic: &str, -) -> eyre::Result { +) -> anyhow::Result { if assignment.is_empty() { return Ok(false); } @@ -161,27 +161,27 @@ fn assignment_has_topic( let topics = usize::try_from(i32::from_be_bytes(take_assignment_bytes( &mut assignment, )?)) - .wrap_err("decoding Kafka consumer assignment topic count")?; + .context("decoding Kafka consumer assignment topic count")?; let mut assigned = false; for _ in 0..topics { let name_length = usize::try_from(i16::from_be_bytes( take_assignment_bytes(&mut assignment)?, )) - .wrap_err("decoding Kafka assignment topic length")?; + .context("decoding Kafka assignment topic length")?; let (name, rest) = assignment .split_at_checked(name_length) - .ok_or_else(|| eyre!("truncated Kafka assignment topic"))?; + .ok_or_else(|| anyhow!("truncated Kafka assignment topic"))?; assignment = rest; let partitions = usize::try_from(i32::from_be_bytes( take_assignment_bytes(&mut assignment)?, )) - .wrap_err("decoding Kafka assignment partition count")?; + .context("decoding Kafka assignment partition count")?; let length = partitions.checked_mul(4).ok_or_else(|| { - eyre!("Kafka assignment partition count overflow") + anyhow!("Kafka assignment partition count overflow") })?; let (_, rest) = assignment .split_at_checked(length) - .ok_or_else(|| eyre!("truncated Kafka assignment partitions"))?; + .ok_or_else(|| anyhow!("truncated Kafka assignment partitions"))?; assignment = rest; assigned |= name == topic.as_bytes() && partitions > 0; } @@ -190,15 +190,15 @@ fn assignment_has_topic( fn take_assignment_bytes( input: &mut &[u8], -) -> eyre::Result<[u8; N]> { +) -> anyhow::Result<[u8; N]> { let (bytes, rest) = input .split_first_chunk::() - .ok_or_else(|| eyre!("truncated Kafka consumer assignment"))?; + .ok_or_else(|| anyhow!("truncated Kafka consumer assignment"))?; *input = rest; Ok(*bytes) } -pub fn create_project_flag_run_producer() -> eyre::Result { +pub fn create_project_flag_run_producer() -> anyhow::Result { let producer: FutureProducer = producer_config() .set("enable.idempotence", "true") .set( @@ -207,10 +207,10 @@ pub fn create_project_flag_run_producer() -> eyre::Result { ) .set("transaction.timeout.ms", "60000") .create() - .wrap_err("creating project flag run Kafka producer")?; + .context("creating project flag run Kafka producer")?; producer .init_transactions(KAFKA_DELIVERY_TIMEOUT) - .wrap_err("initializing project flag run Kafka transaction")?; + .context("initializing project flag run Kafka transaction")?; Ok(producer) } @@ -228,10 +228,10 @@ pub fn producer_config() -> ClientConfig { config } -pub fn create_consumer(group_id: &str) -> eyre::Result { +pub fn create_consumer(group_id: &str) -> anyhow::Result { consumer_config(group_id) .create() - .wrap_err("failed to create Kafka consumer") + .context("failed to create Kafka consumer") } pub fn consumer_config(group_id: &str) -> ClientConfig { diff --git a/apps/labrinth/src/util/minecraft_meta.rs b/apps/labrinth/src/util/minecraft_meta.rs index 422408cc40e..ab1ff0afccc 100644 --- a/apps/labrinth/src/util/minecraft_meta.rs +++ b/apps/labrinth/src/util/minecraft_meta.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use std::time::Duration; +use anyhow::{Context, Result, anyhow}; use chrono::{DateTime, Utc}; -use eyre::{Result, WrapErr}; use minecraft_meta_model::model::{MinecraftVersion, MinecraftVersionName}; use minecraft_meta_model::upstream::mojang::VersionType; @@ -66,7 +66,7 @@ impl MinecraftMeta { }) .map(|name| format!("`{}`", name.0)) .collect::>(); - eyre::ensure!( + anyhow::ensure!( invalid_versions.is_empty(), "invalid game versions: {}", invalid_versions.join(", ") @@ -80,11 +80,11 @@ impl MinecraftMeta { let mut connection = db .connection() .await - .wrap_err("acquiring minecraft-meta connection")?; + .context("acquiring minecraft-meta connection")?; let versions = MinecraftVersion::all() .exec(&mut connection) .await - .wrap_err("loading Minecraft game versions")?; + .context("loading Minecraft game versions")?; let mut versions = versions .into_iter() @@ -95,9 +95,7 @@ impl MinecraftMeta { entry.release_time.subsec_nanosecond() as u32, ) .ok_or_else(|| { - eyre::eyre!( - "minecraft-meta release timestamp is out of range" - ) + anyhow!("minecraft-meta release timestamp is out of range") })?; Ok(MinecraftVersionEntry { name: MinecraftVersionName( diff --git a/apps/labrinth/src/util/neverbounce.rs b/apps/labrinth/src/util/neverbounce.rs index e8236edd343..5686a6d672e 100644 --- a/apps/labrinth/src/util/neverbounce.rs +++ b/apps/labrinth/src/util/neverbounce.rs @@ -1,6 +1,6 @@ use std::time::Instant; -use eyre::{WrapErr, eyre}; +use anyhow::{Context, anyhow}; use neverbounce::{ ReqwestErrorReason, ResponseStatus, SingleCheckParams, SingleCheckResponse, VerificationResult, @@ -21,7 +21,7 @@ const CACHE_EXPIRY_SECONDS: i64 = 60 * 60; pub async fn check_email( redis: &RedisPool, email: &str, -) -> eyre::Result { +) -> anyhow::Result { if ENV.NEVERBOUNCE_API_KEY.is_empty() { debug!( result = "unknown", @@ -74,7 +74,7 @@ pub async fn check_email( return Ok(VerificationResult::Unknown); } - return Err(eyre!(source)).wrap_err("failed to check email"); + return Err(anyhow!(source)).context("failed to check email"); } }; @@ -86,7 +86,7 @@ pub async fn check_email( ResponseStatus::Success => { let result = result.ok_or_else(|| { error!(result = "unknown", "NeverBounce email check failed",); - eyre!("") + anyhow!("") })?; if matches!(result, VerificationResult::Unrecognized(_)) { @@ -131,8 +131,8 @@ pub async fn check_email( } } -pub fn email_check_error_generic() -> eyre::Error { - eyre!("Please try a different email address!") +pub fn email_check_error_generic() -> anyhow::Error { + anyhow!("Please try a different email address!") } fn response_failure_type(status: &ResponseStatus) -> &str { diff --git a/apps/labrinth/src/util/ratelimit.rs b/apps/labrinth/src/util/ratelimit.rs index a1d5cdd4e39..e974d0e6034 100644 --- a/apps/labrinth/src/util/ratelimit.rs +++ b/apps/labrinth/src/util/ratelimit.rs @@ -13,6 +13,7 @@ use actix_web::{ middleware::Next, web, }; +use anyhow::anyhow; use chrono::Utc; use redis::Script; use std::str::FromStr; @@ -180,7 +181,7 @@ impl AsyncRateLimiter { /// valid tokens. OAuth tokens are skipped because their lookup is not cached. async fn get_user_rate_limit( req: &ServiceRequest, -) -> eyre::Result> { +) -> anyhow::Result> { let Ok(token) = extract_authorization_header(req.request()) else { return Ok(None); }; @@ -300,7 +301,7 @@ pub async fn rate_limit_middleware( Ok(service_response.map_into_left_body()) } else { let retry_after_ms = decision.retry_after_ms.unwrap_or(0); - let mut response = ApiError::RateLimit(eyre::eyre!( + let mut response = ApiError::RateLimit(anyhow!( "rate limit exceeded; retry after {retry_after_ms} milliseconds" )) .error_response(); @@ -342,7 +343,7 @@ pub async fn rate_limit_middleware( } } else { let response = - ApiError::Auth(eyre::eyre!("Unable to obtain user IP address!",)) + ApiError::Auth(anyhow!("Unable to obtain user IP address!",)) .error_response(); Ok(req.into_response(response.map_into_right_body())) diff --git a/apps/labrinth/src/util/refreshed_data.rs b/apps/labrinth/src/util/refreshed_data.rs index 2aca189b30d..7009baf976f 100644 --- a/apps/labrinth/src/util/refreshed_data.rs +++ b/apps/labrinth/src/util/refreshed_data.rs @@ -3,7 +3,7 @@ use std::pin::Pin; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; -use eyre::Result; +use anyhow::Result; use rand::RngExt; use tokio::sync::{Mutex, RwLock}; diff --git a/apps/labrinth/src/util/routes.rs b/apps/labrinth/src/util/routes.rs index 708a076e53e..a582531a27d 100644 --- a/apps/labrinth/src/util/routes.rs +++ b/apps/labrinth/src/util/routes.rs @@ -3,6 +3,7 @@ use crate::routes::v3::project_creation::CreateError; use crate::util::error::Context as _; use actix_multipart::Field; use actix_web::web::Payload; +use anyhow::anyhow; use bytes::BytesMut; use futures::StreamExt; use serde::de::DeserializeOwned; @@ -16,12 +17,12 @@ pub async fn read_limited_from_payload( let mut bytes = BytesMut::new(); while let Some(item) = payload.next().await { if bytes.len() >= cap { - return Err(ApiError::Request(eyre::eyre!(Into::::into( + return Err(ApiError::Request(anyhow!(Into::::into( err_msg )))); } else { bytes.extend_from_slice( - &item.map_err(|err| eyre::eyre!(err)).wrap_request_err( + &item.map_err(|err| anyhow!(err)).request_context( "unable to parse bytes in payload sent!".to_string(), )?, ); @@ -39,18 +40,18 @@ where let mut bytes = BytesMut::new(); while let Some(item) = payload.next().await { bytes.extend_from_slice( - &item.map_err(|err| eyre::eyre!(err)).wrap_request_err( + &item.map_err(|err| anyhow!(err)).request_context( "unable to parse bytes in payload sent!".to_string(), )?, ); } let parsed: T = serde_json::from_slice(&bytes) - .wrap_request_err("deserializing JSON data")?; + .request_context("deserializing JSON data")?; parsed .validate() - .map_err(|err| eyre::eyre!(err)) - .wrap_request_err("validating request")?; + .map_err(|err| anyhow!(err)) + .request_context("validating request")?; Ok(parsed) } diff --git a/apps/labrinth/src/util/stripe.rs b/apps/labrinth/src/util/stripe.rs index 09b4f1ca263..c74c9f337c3 100644 --- a/apps/labrinth/src/util/stripe.rs +++ b/apps/labrinth/src/util/stripe.rs @@ -1,3 +1,4 @@ +use anyhow::anyhow; use std::fmt::{Debug, Display, Write as _}; use crate::routes::ApiError; @@ -9,9 +10,9 @@ use crate::util::error::Context as _; /// returned, which can include the payment intent, payment method and client /// secret involved. Error chains end up in logs and in the `details` of API /// error responses, so only the type, codes and message are kept. -pub fn stripe_error_report(error: ::stripe::StripeError) -> eyre::Report { +pub fn stripe_error_report(error: ::stripe::StripeError) -> anyhow::Error { let ::stripe::StripeError::Stripe(error, status) = error else { - return eyre::Report::new(error); + return anyhow::Error::new(error); }; let mut message = format!("Stripe returned {} ({status})", error.type_); @@ -28,7 +29,7 @@ pub fn stripe_error_report(error: ::stripe::StripeError) -> eyre::Report { let _ = write!(message, ": {text}"); } - eyre::eyre!(message) + anyhow!(message) } /// Adds context to the result of a Stripe request. @@ -39,17 +40,17 @@ pub fn stripe_error_report(error: ::stripe::StripeError) -> eyre::Report { pub trait StripeContext: Sized { /// Maps the error variant into an [`ApiError::FailedDependency`] with the /// given message, describing the Stripe error concisely. - fn wrap_stripe_err(self, msg: D) -> Result + fn stripe_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static; } impl StripeContext for Result { - fn wrap_stripe_err(self, msg: D) -> Result + fn stripe_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { self.map_err(stripe_error_report) - .wrap_failed_dependency_err(msg) + .failed_dependency_context(msg) } } diff --git a/apps/labrinth/src/util/tags.rs b/apps/labrinth/src/util/tags.rs index b3fbd858eed..df85b7ad40a 100644 --- a/apps/labrinth/src/util/tags.rs +++ b/apps/labrinth/src/util/tags.rs @@ -55,7 +55,7 @@ pub async fn valid_download_tags( let loaders = Loader::list(pool, redis) .await - .wrap_internal_err("failed to fetch loaders")? + .internal_context("failed to fetch loaders")? .into_iter() .map(|loader| loader.loader) .collect(); diff --git a/apps/labrinth/src/util/tiltify.rs b/apps/labrinth/src/util/tiltify.rs index 434a5804862..900208e1982 100644 --- a/apps/labrinth/src/util/tiltify.rs +++ b/apps/labrinth/src/util/tiltify.rs @@ -1,6 +1,6 @@ use std::time::{Duration, Instant}; -use eyre::{Result, eyre}; +use anyhow::{Result, anyhow}; use serde::Deserialize; use serde_json::json; use tokio::sync::Mutex; @@ -70,7 +70,7 @@ impl TiltifyClient { } if state.rate_limited_until > Instant::now() { - return Err(eyre!( + return Err(anyhow!( "waiting for rate limit to reset at {:.0?} (backoff {:.0?})", state.rate_limited_until, state.rate_limit_backoff @@ -80,7 +80,7 @@ impl TiltifyClient { if ENV.TILTIFY_CLIENT_ID.is_empty() || ENV.TILTIFY_CLIENT_SECRET.is_empty() { - return Err(eyre!( + return Err(anyhow!( "TILTIFY_CLIENT_ID and TILTIFY_CLIENT_SECRET must be set" )); } @@ -97,20 +97,20 @@ impl TiltifyClient { .send() .await .inspect_err(|_| state.set_fetch_backoff()) - .wrap_err("fetching OAuth token")?; + .context("fetching OAuth token")?; let response = match response.error_for_status() { Ok(response) => response, Err(error) => { state.set_fetch_backoff(); - return Err(error).wrap_err("fetching OAuth token"); + return Err(error).context("fetching OAuth token"); } }; let response = response .json::() .await - .wrap_err("parsing OAuth token response")?; + .context("parsing OAuth token response")?; let expires_at = Instant::now() + Duration::from_secs(response.expires_in) diff --git a/apps/labrinth/src/util/usercheck.rs b/apps/labrinth/src/util/usercheck.rs index e05942040d9..4d2e52628fa 100644 --- a/apps/labrinth/src/util/usercheck.rs +++ b/apps/labrinth/src/util/usercheck.rs @@ -1,6 +1,6 @@ use std::time::{Duration, Instant}; -use eyre::{WrapErr, eyre}; +use anyhow::{Context, anyhow}; use reqwest::StatusCode; use serde::{Deserialize, Deserializer, Serialize}; use tracing::{debug, error, warn}; @@ -98,7 +98,7 @@ struct DecisionRequest<'a> { pub async fn check_email_gate( redis: &RedisPool, email: &str, -) -> eyre::Result { +) -> anyhow::Result { if ENV.USERCHECK_API_KEY.is_empty() || ENV.USERCHECK_GATE_ID.is_empty() { debug!( action = "allow", @@ -148,7 +148,7 @@ pub async fn check_email_gate( return Ok(DecisionAction::Allow); } - return Err(eyre!(source)).wrap_err("failed to check email"); + return Err(anyhow!(source)).context("failed to check email"); } }; @@ -208,8 +208,8 @@ pub async fn check_email_gate( Ok(action) } -pub fn gate_block_error() -> eyre::Error { - eyre!( +pub fn gate_block_error() -> anyhow::Error { + anyhow!( "Please try a different email address, or turn off any VPN or proxy services!" ) } diff --git a/apps/labrinth/src/util/webhook.rs b/apps/labrinth/src/util/webhook.rs index 4a155b592e6..7a0f67c2cac 100644 --- a/apps/labrinth/src/util/webhook.rs +++ b/apps/labrinth/src/util/webhook.rs @@ -6,6 +6,7 @@ use crate::util::error::ApiContext as _; use crate::util::error::Context as _; use crate::util::minecraft_meta::MinecraftVersionEntry; use crate::{database::PgPool, env::ENV}; +use anyhow::anyhow; use ariadne::ids::base62_impl::to_base62; use chrono::{DateTime, Utc}; use minecraft_meta_model::upstream::mojang::VersionType; @@ -58,7 +59,7 @@ async fn get_webhook_metadata( redis, ) .await - .wrap_internal_err("fetching webhook project")?; + .internal_context("fetching webhook project")?; if let Some(mut project) = project { let mut owner = None; @@ -69,7 +70,7 @@ async fn get_webhook_metadata( pool, redis, ) - .await.wrap_internal_err("fetching organization from database")?; + .await.internal_context("fetching organization from database")?; if let Some(organization) = organization { owner = Some(WebhookAuthor { @@ -88,7 +89,7 @@ async fn get_webhook_metadata( pool, redis, ) - .await.wrap_internal_err("fetching team member from database")?; + .await.internal_context("fetching team member from database")?; if let Some(member) = team.into_iter().find(|x| x.is_owner) { let user = crate::database::models::user_item::DBUser::get_id( @@ -97,7 +98,7 @@ async fn get_webhook_metadata( redis, ) .await - .wrap_internal_err("fetching user from database")?; + .internal_context("fetching user from database")?; if let Some(user) = user { owner = Some(WebhookAuthor { @@ -202,7 +203,7 @@ pub async fn send_slack_project_webhook( let metadata = get_webhook_metadata(minecraft_meta, project_id, pool, redis) .await - .wrap_api_err("fetching webhook metadata")?; + .api_context("fetching webhook metadata")?; if let Some(metadata) = metadata { let mut blocks = vec![]; @@ -304,8 +305,8 @@ pub async fn send_slack_project_webhook( })) .send() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_internal_err( + .map_err(|err| anyhow!(err)) + .internal_context( "error while sending projects webhook".to_string(), )?; } @@ -376,7 +377,7 @@ pub async fn send_discord_webhook( let metadata = get_webhook_metadata(minecraft_meta, project_id, pool, redis) .await - .wrap_api_err("fetching webhook metadata")?; + .api_context("fetching webhook metadata")?; if let Some(project) = metadata { let mut fields = vec![]; @@ -445,8 +446,8 @@ pub async fn send_discord_webhook( }) .send() .await - .map_err(|err| eyre::eyre!(err)) - .wrap_failed_dependency_err( + .map_err(|err| anyhow!(err)) + .failed_dependency_context( "error while sending projects webhook".to_string(), )?; } diff --git a/apps/labrinth/src/validate/fabric.rs b/apps/labrinth/src/validate/fabric.rs index cb17e6c9706..fc34c2b18d4 100644 --- a/apps/labrinth/src/validate/fabric.rs +++ b/apps/labrinth/src/validate/fabric.rs @@ -5,7 +5,7 @@ use crate::validate::{ SupportedGameVersions, ValidationError, ValidationResult, validate_pack_formats, }; -use eyre::eyre; +use anyhow::anyhow; use std::io::Cursor; use zip::ZipArchive; @@ -88,7 +88,7 @@ pub(super) fn validate_game_versions( .find(|version| version.name.0 == name) .map(minecraft_version_date) .ok_or_else(|| { - eyre!( + anyhow!( "missing minecraft game version `{name}` required for loader validation" ) }) diff --git a/apps/labrinth/src/validate/mod.rs b/apps/labrinth/src/validate/mod.rs index d7e20f14ecc..1055c2cf005 100644 --- a/apps/labrinth/src/validate/mod.rs +++ b/apps/labrinth/src/validate/mod.rs @@ -22,6 +22,7 @@ use crate::validate::shader::{ CanvasShaderValidator, CoreShaderValidator, ShaderValidator, }; use actix_web::web; +use anyhow::anyhow; use bytes::Bytes; use chrono::{DateTime, Utc}; @@ -64,7 +65,7 @@ pub enum ValidationError { #[error("Error while managing threads")] Blocking(#[from] actix_web::error::BlockingError), #[error("internal error while validating uploaded file")] - Internal(#[from] eyre::Report), + Internal(#[from] anyhow::Error), } #[derive(Eq, PartialEq, Debug)] @@ -210,7 +211,7 @@ pub async fn validate_file( let name = crate::models::minecraft::legacy_game_version_name(&name.0); all_game_versions.iter().find(|version| version.name.0 == name) .cloned() - .ok_or_else(|| eyre::eyre!("missing minecraft game version `{name}` required for validation")) + .ok_or_else(|| anyhow!("missing minecraft game version `{name}` required for validation")) }).collect::, _>>()?; let available_loaders = DBLoader::list(&mut *transaction, redis).await?; diff --git a/apps/labrinth/src/validate/project/mod.rs b/apps/labrinth/src/validate/project/mod.rs index b23755bff49..6b04522581e 100644 --- a/apps/labrinth/src/validate/project/mod.rs +++ b/apps/labrinth/src/validate/project/mod.rs @@ -191,7 +191,7 @@ pub async fn validate_with_context( ) }) .await - .wrap_internal_err("validating project")?; + .internal_context("validating project")?; nags.extend(server_nags); Ok(nags) } diff --git a/apps/labrinth/src/validate/project/server_settings.rs b/apps/labrinth/src/validate/project/server_settings.rs index 7f765ae146f..caad4c97c9e 100644 --- a/apps/labrinth/src/validate/project/server_settings.rs +++ b/apps/labrinth/src/validate/project/server_settings.rs @@ -102,7 +102,7 @@ pub(super) async fn validate_server_modpack( } let version = DBVersion::get((*version_id).into(), pool, redis) .await - .wrap_internal_err("fetching server modpack version")?; + .internal_context("fetching server modpack version")?; let visible = if let Some(version) = version { is_visible_version(&version.inner, &None, pool, redis).await? } else { diff --git a/apps/labrinth/tests/redis.rs b/apps/labrinth/tests/redis.rs index 607a3836a0c..388ff24195a 100644 --- a/apps/labrinth/tests/redis.rs +++ b/apps/labrinth/tests/redis.rs @@ -1,3 +1,4 @@ +use anyhow::anyhow; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -5,13 +6,13 @@ use std::time::Duration; use actix_http::StatusCode; use actix_web::test; +use anyhow::Result; use ariadne::ids::base62_impl::parse_base62; use common::api_common::models::{CommonProject, CommonVersion}; use common::api_common::{ApiProject, ApiVersion}; use common::database::{ENEMY_USER_PAT, USER_USER_PAT}; use common::environment::{TestEnvironment, with_test_environment}; use dashmap::DashMap; -use eyre::Result; use labrinth::database::models::project_item::{ PROJECTS_NAMESPACE, PROJECTS_SLUGS_NAMESPACE, }; @@ -259,7 +260,7 @@ async fn cache_lock_coalesces_concurrent_misses_for_one_key() { for key in keys { values.insert(key.clone(), format!("value-{key}")); } - eyre::Ok(values) + anyhow::Ok(values) }, ) .await @@ -304,7 +305,7 @@ async fn cache_lock_coalesces_only_overlapping_keys() { .or_insert(1); values.insert(key.clone(), format!("value-{key}")); } - eyre::Ok(values) + anyhow::Ok(values) }, ) .await @@ -340,7 +341,7 @@ async fn cache_lock_does_not_block_independent_keys() { slow_release.notified().await; let values = DashMap::new(); values.insert(keys[0].clone(), "slow-value".to_string()); - eyre::Ok(values) + anyhow::Ok(values) }, ) .await @@ -355,7 +356,7 @@ async fn cache_lock_does_not_block_independent_keys() { |keys| async move { let values = DashMap::new(); values.insert(keys[0].clone(), "fast-value".to_string()); - eyre::Ok(values) + anyhow::Ok(values) }, ), ) @@ -382,7 +383,7 @@ async fn cache_lock_is_released_after_error_and_cancellation() { "error_recovery:v4", &["key".to_string()], |_| async { - Err::, _>(eyre::eyre!( + Err::, _>(anyhow!( "intentional cache fill failure" )) }, @@ -398,7 +399,7 @@ async fn cache_lock_is_released_after_error_and_cancellation() { |keys| async move { let values = DashMap::new(); values.insert(keys[0].clone(), "recovered".to_string()); - eyre::Ok(values) + anyhow::Ok(values) }, ), ) @@ -435,7 +436,7 @@ async fn cache_lock_is_released_after_error_and_cancellation() { |keys| async move { let values = DashMap::new(); values.insert(keys[0].clone(), "recovered".to_string()); - eyre::Ok(values) + anyhow::Ok(values) }, ), ) @@ -483,7 +484,7 @@ async fn expired_cache_value_serves_waiter_while_writer_refreshes() { writer_release.notified().await; let values = DashMap::new(); values.insert(keys[0].clone(), "fresh".to_string()); - eyre::Ok(values) + anyhow::Ok(values) }, ) .await @@ -493,7 +494,7 @@ async fn expired_cache_value_serves_waiter_while_writer_refreshes() { let stale = timeout( Duration::from_secs(1), pool.get_cached_keys_raw(namespace, &["key".to_string()], |_| async { - Err::, _>(eyre::eyre!( + Err::, _>(anyhow!( "stale waiter unexpectedly became writer" )) }), @@ -510,7 +511,7 @@ async fn expired_cache_value_serves_waiter_while_writer_refreshes() { ); let fresh = pool .get_cached_keys_raw(namespace, &["key".to_string()], |_| async { - Err::, _>(eyre::eyre!( + Err::, _>(anyhow!( "fresh value unexpectedly missed cache" )) }) @@ -549,7 +550,7 @@ async fn case_insensitive_slug_requests_share_one_cache_lock() { canonical_id.to_string(), (Some("MiXeD-Slug".to_string()), "value".to_string()), ); - eyre::Ok(values) + anyhow::Ok(values) }, ) .await diff --git a/packages/modrinth-log/Cargo.toml b/packages/modrinth-log/Cargo.toml index eb8e53306de..1030ebb1846 100644 --- a/packages/modrinth-log/Cargo.toml +++ b/packages/modrinth-log/Cargo.toml @@ -5,8 +5,8 @@ rust-version.workspace = true repository.workspace = true [dependencies] +anyhow = { workspace = true } dotenvy = { workspace = true } -eyre = { workspace = true } sentry = { workspace = true, features = ["tracing"], optional = true } tracing = { workspace = true } tracing-ecs = { workspace = true } diff --git a/packages/modrinth-log/src/lib.rs b/packages/modrinth-log/src/lib.rs index e463e2ad89e..640c14a7e6f 100644 --- a/packages/modrinth-log/src/lib.rs +++ b/packages/modrinth-log/src/lib.rs @@ -2,7 +2,7 @@ use std::str::FromStr; -use eyre::{Result, WrapErr, eyre}; +use anyhow::{Context, Result, anyhow}; #[cfg(feature = "sentry")] use tracing::Level; use tracing::level_filters::LevelFilter; @@ -65,7 +65,7 @@ pub fn init_with_config(compact: bool) -> Result<()> { let output_format = match env_var(OUTPUT_FORMAT_ENV_VAR) { Ok(format) => format .parse::() - .map_err(|_| eyre!("invalid output format '{format}'"))?, + .map_err(|_| anyhow!("invalid output format '{format}'"))?, Err(_) => OutputFormat::Human, }; @@ -116,16 +116,16 @@ pub fn init_with_config(compact: bool) -> Result<()> { registry .try_init() - .wrap_err("failed to initialize tracing registry")?; + .context("failed to initialize tracing registry")?; Ok(()) } fn env_var(key: &str) -> Result { let value = dotenvy::var(key) - .wrap_err_with(|| eyre!("missing environment variable `{key}`"))?; + .with_context(|| anyhow!("missing environment variable `{key}`"))?; if value.is_empty() { - Err(eyre!("environment variable `{key}` is empty")) + Err(anyhow!("environment variable `{key}` is empty")) } else { Ok(value) } diff --git a/packages/modrinth-util/Cargo.toml b/packages/modrinth-util/Cargo.toml index 6bd3992ecd9..81b2aec8e74 100644 --- a/packages/modrinth-util/Cargo.toml +++ b/packages/modrinth-util/Cargo.toml @@ -5,10 +5,10 @@ rust-version.workspace = true repository.workspace = true [dependencies] +anyhow = { workspace = true } actix-web = { workspace = true } derive_more = { workspace = true, features = ["display", "error", "from"] } dotenvy = { workspace = true } -eyre = { workspace = true } modrinth-log = { workspace = true } rust_decimal = { workspace = true, features = ["macros"], optional = true } serde = { workspace = true, features = ["derive"] } diff --git a/packages/modrinth-util/src/error.rs b/packages/modrinth-util/src/error.rs index 023104a6d9c..964d7721f91 100644 --- a/packages/modrinth-util/src/error.rs +++ b/packages/modrinth-util/src/error.rs @@ -11,11 +11,11 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Display, Error)] pub enum ApiError { /// Error occurred on the server side, which the caller has no fault in. - Internal(eyre::Report), + Internal(anyhow::Error), /// Caller made an invalid or malformed request. - Request(eyre::Report), + Request(anyhow::Error), /// Caller attempted a request which they are not allowed to make. - Auth(eyre::Report), + Auth(anyhow::Error), } impl ResponseError for ApiError { @@ -54,149 +54,124 @@ pub struct ErrorResponse { reason = "this trait's purpose is improving error handling" )] pub trait Context: Sized { - /// Maps the error variant into an [`eyre::Report`], creating the message + /// Maps the error variant into an [`anyhow::Error`], creating the message /// using `f`. - fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result + fn with_context(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static; - /// Maps the error variant into an [`eyre::Report`] with the given message. - /// Maps the error variant into an [`eyre::Report`] with the given message. + /// Maps the error variant into an [`anyhow::Error`] with the given message. #[inline] - fn wrap_err(self, msg: D) -> Result + fn context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(|| msg) + self.with_context(|| msg) } /// Maps the error variant into an [`ApiError::Internal`] using the closure to create the message. #[inline] - fn wrap_internal_err_with( + fn internal_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::Internal) + self.with_context(f).map_err(ApiError::Internal) } /// Maps the error variant into an [`ApiError::Internal`] with the given message. #[inline] - fn wrap_internal_err(self, msg: D) -> Result + fn internal_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_internal_err_with(|| msg) + self.internal_context_with(|| msg) } /// Maps the error variant into an [`ApiError::Request`] using the closure to create the message. #[inline] - fn wrap_request_err_with( + fn request_context_with( self, f: impl FnOnce() -> D, ) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::Request) + self.with_context(f).map_err(ApiError::Request) } /// Maps the error variant into an [`ApiError::Request`] with the given message. #[inline] - fn wrap_request_err(self, msg: D) -> Result + fn request_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_request_err_with(|| msg) + self.request_context_with(|| msg) } /// Maps the error variant into an [`ApiError::Auth`] using the closure to create the message. #[inline] - fn wrap_auth_err_with(self, f: impl FnOnce() -> D) -> Result + fn auth_context_with(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_err_with(f).map_err(ApiError::Auth) + self.with_context(f).map_err(ApiError::Auth) } /// Maps the error variant into an [`ApiError::Auth`] with the given message. #[inline] - fn wrap_auth_err(self, msg: D) -> Result + fn auth_context(self, msg: D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.wrap_auth_err_with(|| msg) + self.auth_context_with(|| msg) } } impl Context for Result where - Self: eyre::WrapErr, + Self: anyhow::Context, { - fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result + fn with_context(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { - eyre::WrapErr::wrap_err_with(self, f) + anyhow::Context::with_context(self, f) } } impl Context for Option { - fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result + fn with_context(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { - self.ok_or_else(|| eyre::Report::msg(f())) + self.ok_or_else(|| anyhow::Error::msg(f())) } } -// impl Context for Ty where Ty: eyre::WrapErr {} - -// impl Context for Ty where Ty: eyre::OptionExt {} - -// impl Context for Result -// where -// Self: eyre::WrapErr, -// { -// fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result -// where -// D: Send + Sync + Debug + Display + 'static, -// { -// self.map_err(|err| eyre::Report::new(err).wrap_err(f())) -// } -// } - -// impl Context for Option { -// fn wrap_err_with(self, f: impl FnOnce() -> D) -> Result -// where -// D: Send + Sync + Debug + Display + 'static, -// { -// self.ok_or_else(|| eyre::Report::msg(f())) -// } -// } - #[cfg(test)] mod tests { use super::*; use actix_web::http::StatusCode; + use anyhow::anyhow; #[test] fn test_api_error_display() { - let error = ApiError::Internal(eyre::eyre!("test internal error")); + let error = ApiError::Internal(anyhow!("test internal error")); assert!(error.to_string().contains("test internal error")); - let error = ApiError::Request(eyre::eyre!("test request error")); + let error = ApiError::Request(anyhow!("test request error")); assert!(error.to_string().contains("test request error")); - let error = ApiError::Auth(eyre::eyre!("test auth error")); + let error = ApiError::Auth(anyhow!("test auth error")); assert!(error.to_string().contains("test auth error")); } #[test] fn test_api_error_debug() { - let error = ApiError::Internal(eyre::eyre!("test error")); + let error = ApiError::Internal(anyhow!("test error")); let debug_str = format!("{error:?}"); assert!(debug_str.contains("Internal")); assert!(debug_str.contains("test error")); @@ -204,22 +179,22 @@ mod tests { #[test] fn test_response_error_status_codes() { - let internal_error = ApiError::Internal(eyre::eyre!("internal error")); + let internal_error = ApiError::Internal(anyhow!("internal error")); assert_eq!( internal_error.status_code(), StatusCode::INTERNAL_SERVER_ERROR ); - let request_error = ApiError::Request(eyre::eyre!("request error")); + let request_error = ApiError::Request(anyhow!("request error")); assert_eq!(request_error.status_code(), StatusCode::BAD_REQUEST); - let auth_error = ApiError::Auth(eyre::eyre!("auth error")); + let auth_error = ApiError::Auth(anyhow!("auth error")); assert_eq!(auth_error.status_code(), StatusCode::UNAUTHORIZED); } #[test] fn test_response_error_response() { - let error = ApiError::Request(eyre::eyre!("test request error")); + let error = ApiError::Request(anyhow!("test request error")); let response = error.error_response(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); @@ -231,14 +206,14 @@ mod tests { #[test] fn test_context_trait_result() { let result: Result = Ok(42); - let wrapped = result.wrap_err("context message"); + let wrapped = result.context("context message"); assert_eq!(wrapped.unwrap(), 42); let result: Result = Err(std::io::Error::new( std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_err("context message"); + let wrapped = result.context("context message"); assert!(wrapped.is_err()); assert!(wrapped.unwrap_err().to_string().contains("context message")); } @@ -246,11 +221,11 @@ mod tests { #[test] fn test_context_trait_option() { let option: Option = Some(42); - let wrapped = option.wrap_err("context message"); + let wrapped = option.context("context message"); assert_eq!(wrapped.unwrap(), 42); let option: Option = None; - let wrapped = option.wrap_err("context message"); + let wrapped = option.context("context message"); assert!(wrapped.is_err()); assert_eq!(wrapped.unwrap_err().to_string(), "context message"); } @@ -261,7 +236,7 @@ mod tests { std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_internal_err("internal error context"); + let wrapped = result.internal_context("internal error context"); assert!(wrapped.is_err()); match wrapped.unwrap_err() { @@ -278,7 +253,7 @@ mod tests { std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_request_err("request error context"); + let wrapped = result.request_context("request error context"); assert!(wrapped.is_err()); match wrapped.unwrap_err() { @@ -295,7 +270,7 @@ mod tests { std::io::ErrorKind::NotFound, "not found", )); - let wrapped = result.wrap_auth_err("auth error context"); + let wrapped = result.auth_context("auth error context"); assert!(wrapped.is_err()); match wrapped.unwrap_err() { @@ -313,7 +288,7 @@ mod tests { "not found", )); let wrapped = - result.wrap_err_with(|| format!("context with {}", "dynamic")); + result.with_context(|| format!("context with {}", "dynamic")); assert!(wrapped.is_err()); assert!( diff --git a/packages/modrinth-util/src/lib.rs b/packages/modrinth-util/src/lib.rs index e0502913c3d..70db6e5696c 100644 --- a/packages/modrinth-util/src/lib.rs +++ b/packages/modrinth-util/src/lib.rs @@ -8,7 +8,7 @@ pub mod decimal; pub use error::*; pub use modrinth_log as log; -use eyre::{Result, eyre}; +use anyhow::{Result, anyhow}; /// Fetches an environment variable, possibly loading it using [`dotenvy`]. /// @@ -19,9 +19,9 @@ use eyre::{Result, eyre}; #[track_caller] pub fn env_var(key: &str) -> Result { let value = dotenvy::var(key) - .wrap_err_with(|| eyre!("missing environment variable `{key}`"))?; + .with_context(|| anyhow!("missing environment variable `{key}`"))?; if value.is_empty() { - Err(eyre!("environment variable `{key}` is empty")) + Err(anyhow!("environment variable `{key}` is empty")) } else { Ok(value) } diff --git a/packages/xredis/Cargo.toml b/packages/xredis/Cargo.toml index 14a698c047b..fca842133b4 100644 --- a/packages/xredis/Cargo.toml +++ b/packages/xredis/Cargo.toml @@ -6,11 +6,11 @@ rust-version.workspace = true repository.workspace = true [dependencies] +anyhow = { workspace = true } ariadne = { workspace = true } chrono = { workspace = true } dashmap = { workspace = true } deadpool-redis = { workspace = true, features = ["cluster-async"] } -eyre = { workspace = true } futures = { workspace = true } lz4_flex = { workspace = true } postcard = { workspace = true } diff --git a/packages/xredis/src/blocking.rs b/packages/xredis/src/blocking.rs index 5aaf62d7721..a76aafa9fca 100644 --- a/packages/xredis/src/blocking.rs +++ b/packages/xredis/src/blocking.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use eyre::{Result, WrapErr, bail}; +use anyhow::{Context, Result, bail}; use prometheus::Registry; use super::RedisPool; @@ -38,7 +38,7 @@ impl RedisBlockingPool { config.seed_urls()[0].clone(), connection_config, ) - .wrap_err("configuring standalone blocking Redis client")?; + .context("configuring standalone blocking Redis client")?; let pool = deadpool_redis::Pool::builder(manager) .max_size(pool_size.max()) .wait_timeout(Some(Duration::from_millis( @@ -46,7 +46,7 @@ impl RedisBlockingPool { ))) .runtime(deadpool_redis::Runtime::Tokio1) .build() - .wrap_err("building standalone blocking Redis pool")?; + .context("building standalone blocking Redis pool")?; retain_standalone_pool(pool.clone()); RedisBlockingPoolInner::Standalone(pool) } @@ -55,7 +55,7 @@ impl RedisBlockingPool { config.seed_urls().to_vec(), false, ) - .wrap_err("configuring clustered blocking Redis client")?; + .context("configuring clustered blocking Redis client")?; let pool = deadpool_redis::cluster::Pool::builder(manager) .max_size(pool_size.max()) .wait_timeout(Some(Duration::from_millis( @@ -63,7 +63,7 @@ impl RedisBlockingPool { ))) .runtime(deadpool_redis::Runtime::Tokio1) .build() - .wrap_err("building clustered blocking Redis pool")?; + .context("building clustered blocking Redis pool")?; retain_cluster_pool(pool.clone()); RedisBlockingPoolInner::Cluster(pool) } @@ -91,18 +91,18 @@ impl RedisBlockingPool { let response: Option<(Vec, Vec)> = match &self.inner { RedisBlockingPoolInner::Standalone(pool) => { - let mut connection = pool.get().await.wrap_err( + let mut connection = pool.get().await.context( "fetching standalone blocking Redis connection", )?; - command.query_async(&mut connection).await.wrap_err( + command.query_async(&mut connection).await.context( "reading from standalone Redis blocking queue", )? } RedisBlockingPoolInner::Cluster(pool) => { - let mut connection = pool.get().await.wrap_err( + let mut connection = pool.get().await.context( "fetching clustered blocking Redis connection", )?; - command.query_async(&mut connection).await.wrap_err( + command.query_async(&mut connection).await.context( "reading from clustered Redis blocking queue", )? } diff --git a/packages/xredis/src/cache.rs b/packages/xredis/src/cache.rs index d7d10025d8a..1a65547bb2e 100644 --- a/packages/xredis/src/cache.rs +++ b/packages/xredis/src/cache.rs @@ -5,10 +5,10 @@ use std::future::Future; use std::hash::Hash; use std::str::FromStr; +use anyhow::{Context, Result, anyhow}; use ariadne::ids::base62_impl::{parse_base62, to_base62}; use chrono::{TimeZone, Utc}; use dashmap::DashMap; -use eyre::{Result, WrapErr, eyre}; use futures::stream::{FuturesUnordered, StreamExt}; use redis::aio::ConnectionLike; use serde::de::DeserializeOwned; @@ -114,7 +114,7 @@ impl CacheSettings { pub fn encode_value(&self, value: &T) -> Result> { let mut value = match self.encoding_format { EncodingFormat::Postcard => postcard::to_allocvec(value) - .wrap_err("serializing Redis cache value with postcard")?, + .context("serializing Redis cache value with postcard")?, }; if self.compression_level > 0 @@ -215,7 +215,7 @@ impl CacheManager { P: ConnectionProvider, F: FnOnce(Vec) -> Fut, Fut: Future, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, K: Display + Hash @@ -229,7 +229,7 @@ impl CacheManager { Ok(self .get_cached_keys_raw(provider, namespace, keys, closure) .await - .wrap_err("fetching Redis cache values")? + .context("fetching Redis cache values")? .into_values() .collect()) } @@ -246,7 +246,7 @@ impl CacheManager { P: ConnectionProvider, F: FnOnce(Vec) -> Fut, Fut: Future, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, K: Display + Hash @@ -293,7 +293,7 @@ impl CacheManager { P: ConnectionProvider, F: FnOnce(Vec) -> Fut, Fut: Future, T)>, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, I: Display + Hash + Eq + PartialEq + Clone + Debug, K: Display @@ -315,7 +315,7 @@ impl CacheManager { closure, ) .await - .wrap_err("fetching Redis cache values by slug")? + .context("fetching Redis cache values by slug")? .into_values() .collect()) } @@ -334,7 +334,7 @@ impl CacheManager { P: ConnectionProvider, F: FnOnce(Vec) -> Fut, Fut: Future, T)>, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, I: Display + Hash + Eq + PartialEq + Clone + Debug, K: Display @@ -375,7 +375,7 @@ impl CacheManager { }) .collect::>(); let mut connection = - provider.connect().await.wrap_err( + provider.connect().await.context( "connecting to Redis for slug lookup", )?; let values = match routing { @@ -394,8 +394,8 @@ impl CacheManager { .await } } - .wrap_err("fetching Redis cache slug values")?; - eyre::Ok( + .context("fetching Redis cache slug values")?; + anyhow::Ok( values .into_iter() .flatten() @@ -404,7 +404,7 @@ impl CacheManager { } .instrument(info_span!("get slug ids")) .await - .wrap_err("resolving Redis cache slugs")? + .context("resolving Redis cache slugs")? } else { Vec::new() }; @@ -424,7 +424,7 @@ impl CacheManager { let mut connection = provider .connect() .await - .wrap_err("connecting to Redis for cache lookup")?; + .context("connecting to Redis for cache lookup")?; let mut cached_values = HashMap::new(); let values = match routing { CacheReadRouting::ReplicaOptional => { @@ -435,7 +435,7 @@ impl CacheManager { .await } } - .wrap_err("fetching Redis cache values")?; + .context("fetching Redis cache values")?; for value in values { if let Some(value) = value.and_then(|value| { self.settings @@ -445,7 +445,7 @@ impl CacheManager { } } - eyre::Ok((cached_values, ids)) + anyhow::Ok((cached_values, ids)) } .instrument(info_span!("get_cached_values_closure")) }; @@ -459,7 +459,7 @@ impl CacheManager { let (cached_values_raw, ids) = get_cached_values(ids, CacheReadRouting::ReplicaOptional) .await - .wrap_err("reading Redis cache")?; + .context("reading Redis cache")?; let mut cached_values = cached_values_raw .into_iter() .filter_map(|(key, value)| { @@ -531,10 +531,10 @@ impl CacheManager { let values = timeout_at(fill_deadline, closure(fetch_ids)) .await .map_err(|_| lock_timeout_error(0, waiters.len())) - .wrap_err("waiting to fill Redis cache")?; + .context("waiting to fill Redis cache")?; let values = values - .map_err(Into::::into) - .wrap_err("fetching values to fill Redis cache")?; + .map_err(Into::::into) + .context("fetching values to fill Redis cache")?; let mut return_values = HashMap::new(); let mut encoded_values = Vec::with_capacity(values.len()); @@ -549,14 +549,14 @@ impl CacheManager { let encoded = self .settings .encode_value(&value) - .wrap_err("encoding Redis cache value")?; + .context("encoding Redis cache value")?; encoded_values.push((key, slug, value, encoded)); } let mut connection = provider .connect() .await - .wrap_err("connecting to Redis to fill cache")?; + .context("connecting to Redis to fill cache")?; for (key, slug, _, encoded) in &encoded_values { let redis_key = self.key_builder.entity(namespace, key.to_string()); @@ -567,7 +567,7 @@ impl CacheManager { default_expiry, ) .await - .wrap_err("writing Redis cache value")?; + .context("writing Redis cache value")?; if let Some(slug) = slug && let Some(slug_namespace) = slug_namespace { @@ -584,7 +584,7 @@ impl CacheManager { default_expiry, ) .await - .wrap_err("writing Redis cache slug")?; + .context("writing Redis cache slug")?; } } @@ -641,7 +641,7 @@ impl CacheManager { Err(error) => Err(error), }; cached_values - .extend(operation_result.wrap_err("populating Redis cache")?); + .extend(operation_result.context("populating Redis cache")?); Ok(cached_values .into_iter() @@ -730,7 +730,7 @@ async fn wait_for_locks( return Err(lock_timeout_error(released.len(), total)); } Err(error) => { - return Err(error).wrap_err("waiting for Redis cache lock"); + return Err(error).context("waiting for Redis cache lock"); } } } @@ -740,8 +740,8 @@ async fn wait_for_locks( fn lock_timeout_error( locks_released: usize, locks_waiting: usize, -) -> eyre::Report { - eyre!( +) -> anyhow::Error { + anyhow!( "timeout waiting on local Redis cache lock ({locks_released}/{locks_waiting} released)" ) } diff --git a/packages/xredis/src/cache/locking/local.rs b/packages/xredis/src/cache/locking/local.rs index 001a64f72b2..d8424bd07a0 100644 --- a/packages/xredis/src/cache/locking/local.rs +++ b/packages/xredis/src/cache/locking/local.rs @@ -1,9 +1,9 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use anyhow::{Context, Result}; use dashmap::DashMap; use dashmap::mapref::entry::Entry; -use eyre::{Result, WrapErr}; use tokio::sync::Notify; use tokio::time::{Instant, timeout_at}; @@ -90,7 +90,7 @@ impl LockWaiter { timeout_at(deadline, notified) .await - .wrap_err("waiting for local Redis cache lock")?; + .context("waiting for local Redis cache lock")?; } } } diff --git a/packages/xredis/src/commands.rs b/packages/xredis/src/commands.rs index 744e158a894..d4b6c0a2552 100644 --- a/packages/xredis/src/commands.rs +++ b/packages/xredis/src/commands.rs @@ -1,6 +1,6 @@ use std::fmt::Debug; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use redis::aio::ConnectionLike; use redis::{FromRedisValue, ToRedisArgs}; @@ -29,7 +29,7 @@ where .arg(expiry) .query_async::<()>(connection) .await - .wrap_err("writing to Redis")?; + .context("writing to Redis")?; Ok(()) } @@ -50,7 +50,7 @@ where key, settings .encode_value(&data) - .wrap_err("serializing Redis value")?, + .context("serializing Redis value")?, expiry.unwrap_or(settings.default_expiry), ) .await @@ -65,7 +65,7 @@ where .arg(key) .query_async(connection) .await - .wrap_err("fetching from Redis") + .context("fetching from Redis") } /// Issues ordinary `MGET` commands in bounded chunks. Cluster routing and @@ -127,7 +127,7 @@ where .arg(chunk) .query_async::>>(connection) .await - .wrap_err("fetching multiple values from Redis")?; + .context("fetching multiple values from Redis")?; values.extend(part); } Ok(values) @@ -148,13 +148,12 @@ where let value = connection .route_command(command, primary_mget_routing(chunk)) .await - .wrap_err("fetching multiple values from primary Redis nodes")?; - let value = value - .extract_error() - .wrap_err("extracting Redis response")?; + .context("fetching multiple values from primary Redis nodes")?; + let value = + value.extract_error().context("extracting Redis response")?; let part = redis::from_redis_value::>>(value) .map_err(redis::RedisError::from) - .wrap_err("decoding Redis response")?; + .context("decoding Redis response")?; values.extend(part); } Ok(values) @@ -174,7 +173,7 @@ where .arg(key) .query_async(connection) .await - .wrap_err("fetching serialized value from Redis")?; + .context("fetching serialized value from Redis")?; Ok(value.and_then(|value| settings.decode_value(&value))) } @@ -190,7 +189,7 @@ where { Ok(get_many(connection, keys) .await - .wrap_err("fetching serialized values from Redis")? + .context("fetching serialized values from Redis")? .into_iter() .map(|value| value.and_then(|value| settings.decode_value(&value))) .collect()) @@ -205,7 +204,7 @@ where .arg(key) .query_async::<()>(connection) .await - .wrap_err("deleting from Redis")?; + .context("deleting from Redis")?; Ok(()) } @@ -219,7 +218,7 @@ where .arg(keys) .query_async::<()>(connection) .await - .wrap_err("deleting multiple values from Redis")?; + .context("deleting multiple values from Redis")?; } Ok(()) } @@ -235,7 +234,7 @@ where .arg(value) .query_async::<()>(connection) .await - .wrap_err("pushing to Redis list")?; + .context("pushing to Redis list")?; Ok(()) } @@ -248,5 +247,5 @@ where .arg(key) .query_async(connection) .await - .wrap_err("incrementing Redis value") + .context("incrementing Redis value") } diff --git a/packages/xredis/src/config.rs b/packages/xredis/src/config.rs index d63b3b7f893..fa98d6eb72b 100644 --- a/packages/xredis/src/config.rs +++ b/packages/xredis/src/config.rs @@ -1,6 +1,6 @@ use std::{fmt, str::FromStr}; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use thiserror::Error; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] @@ -222,7 +222,7 @@ impl RedisConfig { standalone_pool_size.0, standalone_pool_size.1, ) - .wrap_err("validating standalone Redis pool size")?, + .context("validating standalone Redis pool size")?, ) } (RedisTopology::Cluster, RedisConnectionType::Pooled) => { @@ -232,7 +232,7 @@ impl RedisConfig { cluster_pool_size.0, cluster_pool_size.1, ) - .wrap_err("validating clustered Redis pool size")?, + .context("validating clustered Redis pool size")?, ) } (RedisTopology::Cluster, RedisConnectionType::Multiplexed) => { @@ -257,7 +257,7 @@ impl RedisConfig { blocking_pool_size.0, blocking_pool_size.1, ) - .wrap_err("validating blocking Redis pool size")?, + .context("validating blocking Redis pool size")?, cache_locking_strategy, read_replica_strategy, }) diff --git a/packages/xredis/src/connection.rs b/packages/xredis/src/connection.rs index a02c9f2991f..764736d11f5 100644 --- a/packages/xredis/src/connection.rs +++ b/packages/xredis/src/connection.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use futures::future::try_join_all; use prometheus::Registry; use redis::aio::ConnectionLike; @@ -80,7 +80,7 @@ impl RedisBackend { config.seed_urls()[0].clone(), connection_config, ) - .wrap_err("configuring standalone Redis client")?; + .context("configuring standalone Redis client")?; let pool = deadpool_redis::Pool::builder(manager) .max_size(pool_size.max()) .wait_timeout(Some(Duration::from_millis(config.wait_timeout_ms()))) @@ -88,11 +88,11 @@ impl RedisBackend { .recycle_timeout(Some(CONNECT_TIMEOUT)) .runtime(deadpool_redis::Runtime::Tokio1) .build() - .wrap_err("building standalone Redis pool")?; + .context("building standalone Redis pool")?; warm_standalone_pool(&pool, pool_size.min()) .await - .wrap_err("warming standalone Redis pool")?; + .context("warming standalone Redis pool")?; retain_standalone_pool(pool.clone()); Ok(Self::StandalonePooled(pool)) @@ -106,7 +106,7 @@ impl RedisBackend { config.seed_urls().to_vec(), false, ) - .wrap_err("configuring clustered Redis client")?; + .context("configuring clustered Redis client")?; let pool = deadpool_redis::cluster::Pool::builder(manager) .max_size(pool_size.max()) .wait_timeout(Some(Duration::from_millis(config.wait_timeout_ms()))) @@ -114,7 +114,7 @@ impl RedisBackend { .recycle_timeout(Some(CONNECT_TIMEOUT)) .runtime(deadpool_redis::Runtime::Tokio1) .build() - .wrap_err("building clustered Redis pool")?; + .context("building clustered Redis pool")?; if config.read_replica_strategy() != ReadReplicaStrategy::Primary { warn!( @@ -124,7 +124,7 @@ impl RedisBackend { warm_cluster_pool(&pool, pool_size.min()) .await - .wrap_err("warming clustered Redis pool")?; + .context("warming clustered Redis pool")?; retain_cluster_pool(pool.clone()); Ok(Self::ClusterPooled(pool)) @@ -157,11 +157,11 @@ impl RedisBackend { let client = builder .build() - .wrap_err("building multiplexed Redis client")?; + .context("building multiplexed Redis client")?; let connection = client .get_async_connection() .await - .wrap_err("connecting multiplexed Redis client")?; + .context("connecting multiplexed Redis client")?; Ok(Self::ClusterMultiplexed(connection)) } @@ -171,7 +171,7 @@ impl RedisBackend { pub(crate) async fn connect(&self) -> Result { tokio::time::timeout(CONNECT_TIMEOUT, self.checkout()) .await - .wrap_err("timed out fetching Redis connection")? + .context("timed out fetching Redis connection")? } async fn checkout(&self) -> Result { @@ -180,13 +180,13 @@ impl RedisBackend { RedisConnectionInner::StandalonePooled( pool.get() .await - .wrap_err("fetching standalone Redis connection")?, + .context("fetching standalone Redis connection")?, ) } Self::ClusterPooled(pool) => RedisConnectionInner::ClusterPooled( pool.get() .await - .wrap_err("fetching clustered Redis connection")?, + .context("fetching clustered Redis connection")?, ), Self::ClusterMultiplexed(connection) => { RedisConnectionInner::ClusterMultiplexed(connection.clone()) @@ -327,7 +327,7 @@ async fn warm_standalone_pool( ) -> Result<()> { let connections = try_join_all((0..min).map(|_| pool.get())) .await - .wrap_err("fetching initial standalone Redis connections")?; + .context("fetching initial standalone Redis connections")?; drop(connections); Ok(()) } @@ -338,7 +338,7 @@ async fn warm_cluster_pool( ) -> Result<()> { let connections = try_join_all((0..min).map(|_| pool.get())) .await - .wrap_err("fetching initial clustered Redis connections")?; + .context("fetching initial clustered Redis connections")?; drop(connections); Ok(()) } diff --git a/packages/xredis/src/lib.rs b/packages/xredis/src/lib.rs index 55f066f28b5..e0ff22ece19 100644 --- a/packages/xredis/src/lib.rs +++ b/packages/xredis/src/lib.rs @@ -5,8 +5,8 @@ use std::future::Future; use std::hash::Hash; use std::sync::Arc; +use anyhow::{Context, Result}; use dashmap::DashMap; -use eyre::{Result, WrapErr}; use prometheus::Registry; use redis::aio::ConnectionLike; use redis::{FromRedisValue, ToRedisArgs}; @@ -66,11 +66,11 @@ impl RedisPool { let backend = RedisBackend::new(&config) .await - .wrap_err("creating Redis command backend")?; + .context("creating Redis command backend")?; let blocking = blocking::RedisBlockingPool::new(&config) .await - .wrap_err("creating Redis blocking pool")?; + .context("creating Redis blocking pool")?; let key_builder = KeyBuilder::new(meta_namespace, config.topology()); let cache = CacheManager::new(key_builder.clone(), cache_settings); @@ -95,7 +95,7 @@ impl RedisPool { .backend .connect() .await - .wrap_err("connecting to Redis")?, + .context("connecting to Redis")?, key_builder: self.key_builder.clone(), settings: self.cache.settings().clone(), }) @@ -107,10 +107,10 @@ impl RedisPool { ) -> Result<()> { self.backend .register_metrics(registry) - .wrap_err("registering Redis command pool metrics")?; + .context("registering Redis command pool metrics")?; self.blocking .register_metrics(registry) - .wrap_err("registering Redis blocking pool metrics") + .context("registering Redis blocking pool metrics") } pub async fn get_keys_with_cache( @@ -123,7 +123,7 @@ impl RedisPool { where F: FnOnce(Vec) -> Fut, Fut: Future, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, K: Display + Hash @@ -139,8 +139,8 @@ impl RedisPool { } else { Ok(closure(keys.to_vec()) .await - .map_err(Into::::into) - .wrap_err("fetching uncached values")? + .map_err(Into::::into) + .context("fetching uncached values")? .into_iter() .map(|(_, value)| value) .collect()) @@ -156,7 +156,7 @@ impl RedisPool { where F: FnOnce(Vec) -> Fut, Fut: Future, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, K: Display + Hash @@ -181,7 +181,7 @@ impl RedisPool { where F: FnOnce(Vec) -> Fut, Fut: Future, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, K: Display + Hash @@ -209,7 +209,7 @@ impl RedisPool { where F: FnOnce(Vec) -> Fut, Fut: Future, T)>, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, I: Display + Hash + Eq + PartialEq + Clone + Debug, K: Display @@ -233,8 +233,8 @@ impl RedisPool { } else { Ok(closure(keys.to_vec()) .await - .map_err(Into::::into) - .wrap_err("fetching uncached values by slug")? + .map_err(Into::::into) + .context("fetching uncached values by slug")? .into_iter() .map(|(_, (_, value))| value) .collect()) @@ -252,7 +252,7 @@ impl RedisPool { where F: FnOnce(Vec) -> Fut, Fut: Future, T)>, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, I: Display + Hash + Eq + PartialEq + Clone + Debug, K: Display @@ -287,7 +287,7 @@ impl RedisPool { where F: FnOnce(Vec) -> Fut, Fut: Future, T)>, E>>, - E: Into, + E: Into, T: Serialize + DeserializeOwned, I: Display + Hash + Eq + PartialEq + Clone + Debug, K: Display diff --git a/packages/xredis/src/metrics.rs b/packages/xredis/src/metrics.rs index fafd5dccbe3..b4071025856 100644 --- a/packages/xredis/src/metrics.rs +++ b/packages/xredis/src/metrics.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use prometheus::{IntGauge, Registry}; const METRICS_UPDATE_INTERVAL: Duration = Duration::from_secs(5); @@ -82,39 +82,39 @@ impl RedisPoolMetrics { "Maximum logical connection count for the {description}; clustered logical connections may own multiple physical sockets" ), ) - .wrap_err("creating Redis pool maximum size metric")?; + .context("creating Redis pool maximum size metric")?; let size = IntGauge::new( format!("{prefix}_size"), format!( "Current logical connection count for the {description}; clustered logical connections may own multiple physical sockets" ), ) - .wrap_err("creating Redis pool size metric")?; + .context("creating Redis pool size metric")?; let available = IntGauge::new( format!("{prefix}_available"), format!("Available logical connections in the {description}"), ) - .wrap_err("creating Redis pool availability metric")?; + .context("creating Redis pool availability metric")?; let waiting = IntGauge::new( format!("{prefix}_waiting"), format!( "Number of futures waiting for a logical connection from the {description}" ), ) - .wrap_err("creating Redis pool waiters metric")?; + .context("creating Redis pool waiters metric")?; registry .register(Box::new(max_size.clone())) - .wrap_err("registering Redis pool maximum size metric")?; + .context("registering Redis pool maximum size metric")?; registry .register(Box::new(size.clone())) - .wrap_err("registering Redis pool size metric")?; + .context("registering Redis pool size metric")?; registry .register(Box::new(available.clone())) - .wrap_err("registering Redis pool availability metric")?; + .context("registering Redis pool availability metric")?; registry .register(Box::new(waiting.clone())) - .wrap_err("registering Redis pool waiters metric")?; + .context("registering Redis pool waiters metric")?; Ok(Self { max_size, @@ -161,7 +161,7 @@ where P: LogicalPoolStatusProvider, { let metrics = RedisPoolMetrics::register(registry, kind) - .wrap_err("registering Redis pool metrics")?; + .context("registering Redis pool metrics")?; metrics.set(provider.logical_pool_status()); tokio::spawn(async move { diff --git a/packages/xredis/src/pubsub.rs b/packages/xredis/src/pubsub.rs index c4986ce0433..fb1a6a68b69 100644 --- a/packages/xredis/src/pubsub.rs +++ b/packages/xredis/src/pubsub.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use eyre::{Result, WrapErr}; +use anyhow::{Context, Result}; use futures::StreamExt; use redis::ToRedisArgs; use tokio::sync::mpsc; @@ -43,13 +43,13 @@ impl RedisPool { let mut connection = self .connect() .await - .wrap_err("connecting to Redis for publishing")?; + .context("connecting to Redis for publishing")?; let _: usize = redis::cmd("PUBLISH") .arg(channel) .arg(message) .query_async(&mut connection) .await - .wrap_err("publishing to Redis channel")?; + .context("publishing to Redis channel")?; Ok(()) } } @@ -113,15 +113,15 @@ async fn forward_from_seed( sender: &mpsc::Sender>, ) -> Result { let client = redis::Client::open(seed_url) - .wrap_err("configuring Redis Pub/Sub client")?; + .context("configuring Redis Pub/Sub client")?; let mut pubsub = client .get_async_pubsub() .await - .wrap_err("connecting to Redis Pub/Sub")?; + .context("connecting to Redis Pub/Sub")?; pubsub .subscribe(channel) .await - .wrap_err("subscribing to Redis channel")?; + .context("subscribing to Redis channel")?; info!(channel, "Established Redis Pub/Sub subscription"); let mut stream = pubsub.into_on_message(); From cbec63b2c0dad9a7895c63710f81ff265ef3d57d Mon Sep 17 00:00:00 2001 From: aecsocket <43144841+aecsocket@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:28:09 +0000 Subject: [PATCH 4/7] fix --- apps/labrinth/Cargo.toml | 2 +- packages/modrinth-util/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/labrinth/Cargo.toml b/apps/labrinth/Cargo.toml index 4f2c7b3f441..5f20d208c95 100644 --- a/apps/labrinth/Cargo.toml +++ b/apps/labrinth/Cargo.toml @@ -11,7 +11,6 @@ name = "labrinth" path = "src/main.rs" [dependencies] -anyhow = { workspace = true } actix-cors = { workspace = true } actix-files = { workspace = true } actix-http = { workspace = true } @@ -20,6 +19,7 @@ actix-rt = { workspace = true } actix-web = { workspace = true } actix-web-prom = { workspace = true, features = ["process"] } actix-ws = { workspace = true } +anyhow = { workspace = true } arc-swap = { workspace = true } argon2 = { workspace = true } ariadne = { workspace = true } diff --git a/packages/modrinth-util/Cargo.toml b/packages/modrinth-util/Cargo.toml index 81b2aec8e74..04495e8d91d 100644 --- a/packages/modrinth-util/Cargo.toml +++ b/packages/modrinth-util/Cargo.toml @@ -5,8 +5,8 @@ rust-version.workspace = true repository.workspace = true [dependencies] -anyhow = { workspace = true } actix-web = { workspace = true } +anyhow = { workspace = true } derive_more = { workspace = true, features = ["display", "error", "from"] } dotenvy = { workspace = true } modrinth-log = { workspace = true } From 71be930d056678caedb71761012c598fd0d93798 Mon Sep 17 00:00:00 2001 From: aecsocket <43144841+aecsocket@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:36:44 +0000 Subject: [PATCH 5/7] merge main --- Cargo.toml | 1 + packages/app-lib/Cargo.toml | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 9feb67aad55..c17518079ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -221,6 +221,7 @@ strum = "0.28.0" subtle = "2.6.1" syn = { version = "3.0" } sysinfo = { version = "0.38.4", default-features = false } +tar = "0.4.46" tauri = "=2.11.5" tauri-build = "=2.6.3" tauri-plugin-deep-link = "=2.4.3" diff --git a/packages/app-lib/Cargo.toml b/packages/app-lib/Cargo.toml index 816d7ee487e..38bf3d0069d 100644 --- a/packages/app-lib/Cargo.toml +++ b/packages/app-lib/Cargo.toml @@ -17,7 +17,6 @@ async-recursion = { workspace = true } async-trait = { workspace = true } async-tungstenite = { workspace = true, features = ["tokio-runtime", "tokio-rustls-webpki-roots"] } async-walkdir = { workspace = true } - base64 = { workspace = true } bon = { workspace = true } bytemuck = { workspace = true, features = ["extern_crate_alloc"] } From b59ce3b9fe34f4c45062e9c41128e99ba3f0bcdf Mon Sep 17 00:00:00 2001 From: aecsocket <43144841+aecsocket@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:36:46 +0000 Subject: [PATCH 6/7] ci AGAIN --- apps/labrinth/src/routes/internal/flows.rs | 18 +++++++++--------- apps/labrinth/src/routes/internal/pats.rs | 6 +++--- apps/labrinth/src/routes/mod.rs | 4 ++-- apps/labrinth/src/routes/v3/payouts.rs | 2 +- apps/labrinth/src/routes/v3/projects/mod.rs | 2 +- apps/labrinth/src/routes/v3/users.rs | 4 ++-- apps/labrinth/src/util/error.rs | 6 +++--- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/apps/labrinth/src/routes/internal/flows.rs b/apps/labrinth/src/routes/internal/flows.rs index 32ad031b458..68ddee5e809 100644 --- a/apps/labrinth/src/routes/internal/flows.rs +++ b/apps/labrinth/src/routes/internal/flows.rs @@ -1893,7 +1893,7 @@ pub async fn delete_auth_provider( ) -> Result { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let user = get_user_from_headers( &req, @@ -2651,7 +2651,7 @@ pub async fn begin_2fa_flow( ) -> Result { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let user = get_user_from_headers( &req, @@ -2709,7 +2709,7 @@ pub async fn finish_2fa_flow( ) -> Result { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let flow = DBFlow::get(&login.flow, &redis) .await @@ -2865,7 +2865,7 @@ pub async fn remove_2fa( ) -> Result { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let (scopes, user) = get_user_record_from_bearer_token( &req, @@ -3131,7 +3131,7 @@ pub async fn change_password( } else { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let (scopes, user) = get_user_record_from_bearer_token( &req, @@ -3325,7 +3325,7 @@ pub async fn set_email( if user.email.is_some() { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; } if !crate::database::models::DBUser::get_by_case_insensitive_email( @@ -3712,7 +3712,7 @@ pub async fn register_passkey_start( ) -> Result, ApiError> { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let user = get_user_from_headers( &req, @@ -3819,7 +3819,7 @@ pub async fn register_passkey_finish( ) -> Result<(web::Json, StatusCode), ApiError> { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let user = get_user_from_headers( &req, @@ -4211,7 +4211,7 @@ pub async fn delete_passkey( ) -> Result { require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let user = get_user_from_headers( &req, diff --git a/apps/labrinth/src/routes/internal/pats.rs b/apps/labrinth/src/routes/internal/pats.rs index 8f9bdab11ae..8610a238607 100644 --- a/apps/labrinth/src/routes/internal/pats.rs +++ b/apps/labrinth/src/routes/internal/pats.rs @@ -142,7 +142,7 @@ pub async fn create_pat( require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let mut transaction = pool .begin() @@ -265,7 +265,7 @@ pub async fn edit_pat( require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let id = id.into_inner().0; let pat = database::models::pat_item::DBPersonalAccessToken::get( @@ -386,7 +386,7 @@ pub async fn delete_pat( .user; require_privileged_token(&req, &**pool, &redis) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let id = id.into_inner().0; let pat = database::models::pat_item::DBPersonalAccessToken::get( &id, &**pool, &redis, diff --git a/apps/labrinth/src/routes/mod.rs b/apps/labrinth/src/routes/mod.rs index f090441903b..d40ca5c94d5 100644 --- a/apps/labrinth/src/routes/mod.rs +++ b/apps/labrinth/src/routes/mod.rs @@ -726,9 +726,9 @@ mod tests { let result: Result<(), AuthenticationError> = Err(AuthenticationError::PrivilegedTokenExpired); let error = result - .wrap_api_err("checking privileged token age") + .api_context("checking privileged token age") .unwrap_err() - .wrap_err("performing sensitive action"); + .context("performing sensitive action"); assert_eq!(error.status_code(), StatusCode::UNAUTHORIZED); assert_eq!(error.error_response().status(), StatusCode::UNAUTHORIZED); diff --git a/apps/labrinth/src/routes/v3/payouts.rs b/apps/labrinth/src/routes/v3/payouts.rs index 092d714bfa6..4acf56a4636 100644 --- a/apps/labrinth/src/routes/v3/payouts.rs +++ b/apps/labrinth/src/routes/v3/payouts.rs @@ -587,7 +587,7 @@ pub async fn create_payout( &redis, ) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let balance = get_user_balance(user.id, &pool) .await diff --git a/apps/labrinth/src/routes/v3/projects/mod.rs b/apps/labrinth/src/routes/v3/projects/mod.rs index 97f516288ba..8e35cc4fa25 100644 --- a/apps/labrinth/src/routes/v3/projects/mod.rs +++ b/apps/labrinth/src/routes/v3/projects/mod.rs @@ -3539,7 +3539,7 @@ pub async fn project_delete_internal( &redis, ) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; } delphi::tech_review_queue::remove_projects( diff --git a/apps/labrinth/src/routes/v3/users.rs b/apps/labrinth/src/routes/v3/users.rs index ea82411ce03..1d03c6ec91d 100644 --- a/apps/labrinth/src/routes/v3/users.rs +++ b/apps/labrinth/src/routes/v3/users.rs @@ -1032,7 +1032,7 @@ pub async fn user_edit( &redis, ) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let existing_user_id_option = DBUser::get(username, &**pool, &redis) @@ -1429,7 +1429,7 @@ pub async fn user_delete( &redis, ) .await - .wrap_api_err("checking privileged token age")?; + .api_context("checking privileged token age")?; let result = DBUser::remove(id, &mut transaction, &redis) .await diff --git a/apps/labrinth/src/util/error.rs b/apps/labrinth/src/util/error.rs index e39dc1a7837..a36fb7eda70 100644 --- a/apps/labrinth/src/util/error.rs +++ b/apps/labrinth/src/util/error.rs @@ -31,12 +31,12 @@ impl ApiContext for Result { } impl ApiContext for Result { - fn wrap_api_err_with(self, f: impl FnOnce() -> D) -> Result + fn api_context_with(self, f: impl FnOnce() -> D) -> Result where D: Send + Sync + Debug + Display + 'static, { self.map_err(|error| { - ApiError::Auth(eyre::Report::new(error).wrap_err(f())) + ApiError::Auth(anyhow::Error::new(error).context(f())) }) } } @@ -493,7 +493,7 @@ mod tests { let description = source.to_string(); let result: Result<(), AuthenticationError> = Err(source); let error = - result.wrap_api_err("checking authentication").unwrap_err(); + result.api_context("checking authentication").unwrap_err(); assert_eq!(error.status_code(), status); assert_eq!(error.as_api_error().error, name); From b777da642416d412761a56dad3923434c921a6f2 Mon Sep 17 00:00:00 2001 From: aecsocket <43144841+aecsocket@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:18:53 +0000 Subject: [PATCH 7/7] fix migration --- apps/labrinth/src/routes/internal/flows.rs | 30 +++++++++---------- apps/labrinth/src/routes/v3/projects/mod.rs | 2 +- .../src/routes/v3/projects/mutation.rs | 4 +-- 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/apps/labrinth/src/routes/internal/flows.rs b/apps/labrinth/src/routes/internal/flows.rs index 3eb16eed5cc..d9f4afae764 100644 --- a/apps/labrinth/src/routes/internal/flows.rs +++ b/apps/labrinth/src/routes/internal/flows.rs @@ -1537,7 +1537,7 @@ pub async fn auth_callback( .append_header((LOCATION, redirect_url.as_str())) .json(serde_json::json!({ "url": redirect_url }))) } else { - transaction.rollback().await.wrap_err( + transaction.rollback().await.context( "rolling back authentication transaction before login code", )?; @@ -1649,7 +1649,7 @@ pub async fn exchange_login_code( ) -> Result, ApiError> { let pending = take_pending_login_code(&redis, &body.code) .await - .wrap_internal_err("taking sign-in code")?; + .internal_context("taking sign-in code")?; let Some(pending) = pending else { return Err(ApiError::Auth(anyhow!( AuthenticationError::InvalidCredentials @@ -1670,7 +1670,7 @@ pub async fn exchange_login_code( let mut transaction = pool .begin() .await - .wrap_internal_err("starting database transaction")?; + .internal_context("starting database transaction")?; let session = issue_auth_sessions( req, pending.user_id, @@ -1679,11 +1679,11 @@ pub async fn exchange_login_code( pending.include_app_session, ) .await - .wrap_auth_err("exchanging sign-in code")?; + .auth_context("exchanging sign-in code")?; transaction .commit() .await - .wrap_internal_err("committing database transaction")?; + .internal_context("committing database transaction")?; Ok(web::Json(session)) } @@ -1751,12 +1751,12 @@ async fn store_oauth_code_challenge( let mut connection = redis .connect() .await - .wrap_err("connecting to redis to store oauth code challenge")?; + .context("connecting to redis to store oauth code challenge")?; let key = connection.key().entity(OAUTH_PKCE_NAMESPACE, state); connection .set(&key, challenge, Some(OAUTH_FLOW_TTL_SECONDS)) .await - .wrap_err("storing oauth code challenge")?; + .context("storing oauth code challenge")?; Ok(()) } @@ -1767,13 +1767,13 @@ async fn take_oauth_code_challenge( let mut connection = redis .connect() .await - .wrap_err("connecting to redis to take oauth code challenge")?; + .context("connecting to redis to take oauth code challenge")?; let key = connection.key().entity(OAUTH_PKCE_NAMESPACE, state); let challenge: Option = redis::cmd("GETDEL") .arg(&key) .query_async(&mut connection) .await - .wrap_err("taking oauth code challenge")?; + .context("taking oauth code challenge")?; Ok(challenge.filter(|challenge| is_s256_code_challenge(challenge))) } @@ -1789,16 +1789,16 @@ async fn insert_pending_login_code( code_challenge: code_challenge.to_string(), include_app_session, }) - .wrap_err("encoding pending login code")?; + .context("encoding pending login code")?; let mut connection = redis .connect() .await - .wrap_err("connecting to redis to store login code")?; + .context("connecting to redis to store login code")?; let key = connection.key().entity(LOGIN_CODE_NAMESPACE, &code); connection .set(&key, payload, Some(LOGIN_CODE_TTL_SECONDS)) .await - .wrap_err("storing login code")?; + .context("storing login code")?; Ok(code) } @@ -1813,19 +1813,19 @@ async fn take_pending_login_code( let mut connection = redis .connect() .await - .wrap_err("connecting to redis to take login code")?; + .context("connecting to redis to take login code")?; let key = connection.key().entity(LOGIN_CODE_NAMESPACE, code); let payload: Option = redis::cmd("GETDEL") .arg(&key) .query_async(&mut connection) .await - .wrap_err("taking login code")?; + .context("taking login code")?; let Some(payload) = payload else { return Ok(None); }; serde_json::from_str(&payload) - .wrap_err("decoding pending login code") + .context("decoding pending login code") .map(Some) } diff --git a/apps/labrinth/src/routes/v3/projects/mod.rs b/apps/labrinth/src/routes/v3/projects/mod.rs index fef31763fd4..c4f9c704c9e 100644 --- a/apps/labrinth/src/routes/v3/projects/mod.rs +++ b/apps/labrinth/src/routes/v3/projects/mod.rs @@ -734,7 +734,7 @@ pub async fn project_edit_internal( { let reason = serde_json::to_value(ApprovalReason::ByUser(user.user.id)) - .wrap_internal_err( + .internal_context( "serializing project approval reason", )?; sqlx::query!( diff --git a/apps/labrinth/src/routes/v3/projects/mutation.rs b/apps/labrinth/src/routes/v3/projects/mutation.rs index a933ea5480a..c55fca97f54 100644 --- a/apps/labrinth/src/routes/v3/projects/mutation.rs +++ b/apps/labrinth/src/routes/v3/projects/mutation.rs @@ -105,9 +105,7 @@ impl SyncedProjectState { }; let reason = serde_json::to_value(ApprovalReason::Auto(provenance.clone())) - .wrap_internal_err( - "serializing project auto-approval reason", - )?; + .internal_context("serializing project auto-approval reason")?; sqlx::query!( r#"