diff --git a/.env.example b/.env.example index b583759b..bb034126 100644 --- a/.env.example +++ b/.env.example @@ -100,8 +100,9 @@ S3_REGION=us-east-1 # style S3_FORCE_PATH_STYLE=true -# Access key id. When unset (alongside secret_access_key), the SDK's default credential -# chain is used (environment, profile, IAM role, …) +# Access key id. When unset (alongside secret_access_key), credentials come from the +# environment chain (AWS_* variables, web identity, ECS container credentials, instance +# metadata); ~/.aws profiles are not read # S3_ACCESS_KEY_ID= # Secret access key, paired with access_key_id for static credentials diff --git a/Cargo.lock b/Cargo.lock index 587c7530..117a32fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -736,49 +736,6 @@ dependencies = [ "arrayvec", ] -[[package]] -name = "aws-config" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3a314ce5fe1e5bdfbc6495e5e1f9ad066d34e567b26c41864eef40c22bfe16" -dependencies = [ - "aws-credential-types", - "aws-runtime", - "aws-sdk-sso", - "aws-sdk-ssooidc", - "aws-sdk-sts", - "aws-smithy-async", - "aws-smithy-http", - "aws-smithy-json", - "aws-smithy-runtime", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "aws-types", - "bytes", - "fastrand", - "hex", - "http", - "sha1 0.10.7", - "time", - "tokio", - "tracing", - "url", - "zeroize", -] - -[[package]] -name = "aws-credential-types" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "576e8da35751dc85409ec1cd15999f692c277a1fbe9336780fe6f15e49dd637d" -dependencies = [ - "aws-smithy-async", - "aws-smithy-runtime-api", - "aws-smithy-types", - "zeroize", -] - [[package]] name = "aws-lc-rs" version = "1.19.0" @@ -803,403 +760,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "aws-runtime" -version = "1.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de8930c11353c72ae54aa24dc94d692df74d59814839cbaf8069d63dbcb4c519" -dependencies = [ - "aws-credential-types", - "aws-sigv4", - "aws-smithy-async", - "aws-smithy-eventstream", - "aws-smithy-http", - "aws-smithy-runtime", - "aws-smithy-runtime-api", - "aws-smithy-types", - "aws-types", - "bytes", - "bytes-utils", - "fastrand", - "http", - "http-body", - "percent-encoding", - "pin-project-lite", - "tracing", - "uuid", -] - -[[package]] -name = "aws-sdk-s3" -version = "1.161.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe" -dependencies = [ - "arc-swap", - "aws-credential-types", - "aws-runtime", - "aws-sigv4", - "aws-smithy-async", - "aws-smithy-checksums", - "aws-smithy-eventstream", - "aws-smithy-http", - "aws-smithy-json", - "aws-smithy-observability", - "aws-smithy-runtime", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "aws-smithy-xml", - "aws-types", - "bytes", - "fastrand", - "hex", - "hmac 0.13.0", - "http", - "http-body", - "lru", - "percent-encoding", - "regex-lite", - "sha2 0.11.1", - "tracing", - "url", -] - -[[package]] -name = "aws-sdk-sso" -version = "1.122.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2dd812c2090bec82fd410ac3fb37e72432c8830eb1293c19d49d1ebd4c30c0e" -dependencies = [ - "arc-swap", - "aws-credential-types", - "aws-runtime", - "aws-smithy-async", - "aws-smithy-http", - "aws-smithy-json", - "aws-smithy-observability", - "aws-smithy-runtime", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "aws-types", - "bytes", - "fastrand", - "http", - "regex-lite", - "tracing", -] - -[[package]] -name = "aws-sdk-ssooidc" -version = "1.124.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fba228d6f4566858501a057dd1febc225a0f7a22b6f66f1475e2445d72d40621" -dependencies = [ - "arc-swap", - "aws-credential-types", - "aws-runtime", - "aws-smithy-async", - "aws-smithy-http", - "aws-smithy-json", - "aws-smithy-observability", - "aws-smithy-runtime", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "aws-types", - "fastrand", - "regex-lite", - "tracing", -] - -[[package]] -name = "aws-sdk-sts" -version = "1.128.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c357588cdf8c9ae96c0d9930fff757f9b678d06b8f68d8e37a1278fe034912" -dependencies = [ - "arc-swap", - "aws-credential-types", - "aws-runtime", - "aws-smithy-async", - "aws-smithy-http", - "aws-smithy-json", - "aws-smithy-observability", - "aws-smithy-query", - "aws-smithy-runtime", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "aws-smithy-xml", - "aws-types", - "fastrand", - "http", - "regex-lite", - "tracing", -] - -[[package]] -name = "aws-sigv4" -version = "1.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c5aa04c533733a77879294f1854c27b3715cc50ea71756d1f6a958702b1a9fb" -dependencies = [ - "aws-credential-types", - "aws-smithy-eventstream", - "aws-smithy-http", - "aws-smithy-runtime-api", - "aws-smithy-types", - "bytes", - "crypto-bigint", - "ecdsa", - "form_urlencoded", - "hex", - "hmac 0.13.0", - "http", - "p256", - "percent-encoding", - "sha2 0.11.1", - "subtle", - "time", - "tracing", - "zeroize", -] - -[[package]] -name = "aws-smithy-async" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" -dependencies = [ - "futures-util", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "aws-smithy-checksums" -version = "0.65.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab2f2d12a431aab3703d55277278bad45f02208569b11506220b95fdc1ef0507" -dependencies = [ - "aws-smithy-http", - "aws-smithy-types", - "bytes", - "crc-fast", - "hex", - "http", - "http-body", - "http-body-util", - "md-5 0.11.0", - "pin-project-lite", - "sha1 0.11.0", - "sha2 0.11.1", - "tracing", -] - -[[package]] -name = "aws-smithy-eventstream" -version = "0.61.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c8a643d0e114cae39e45415e3225793a6396698b7779a0c9e3ede731d8fc71" -dependencies = [ - "aws-smithy-types", - "bytes", - "crc32fast", -] - -[[package]] -name = "aws-smithy-http" -version = "0.64.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19af609dd5edf8b056cd0bb001c706c8b3b1458055328b334ec13d7f46f6aaa8" -dependencies = [ - "aws-smithy-eventstream", - "aws-smithy-runtime-api", - "aws-smithy-types", - "bytes", - "bytes-utils", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "percent-encoding", - "pin-project-lite", - "tracing", -] - -[[package]] -name = "aws-smithy-http-client" -version = "1.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "203e36a754ced29dab0d710dab8c4fecf181d78f229e90fa6e75c6406ecb55a3" -dependencies = [ - "aws-smithy-async", - "aws-smithy-runtime-api", - "aws-smithy-types", - "h2", - "http", - "hyper", - "hyper-rustls", - "hyper-util", - "pin-project-lite", - "rustls", - "rustls-native-certs", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tower", - "tracing", -] - -[[package]] -name = "aws-smithy-json" -version = "0.65.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b45f9fc77ffe92c92c341165a01a565bd30c39ecf5aa8c0719b41719009604f9" -dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", -] - -[[package]] -name = "aws-smithy-observability" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a416257d7b1b0f32a517a470a8c1dd354d8c4aa697ccab81a11a1e6cfb7418e3" -dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-types", - "tracing", -] - -[[package]] -name = "aws-smithy-query" -version = "0.64.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "165f6265342a313ad6f7a1ac17a0cdba30c522039d3f41d8d6871ce8a2b34ecd" -dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "aws-smithy-xml", - "urlencoding", -] - -[[package]] -name = "aws-smithy-runtime" -version = "1.16.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ed38b842f93dd8220cc8816750c72ce914b22c6eb3df02beb9632333ccb366d" -dependencies = [ - "aws-smithy-async", - "aws-smithy-http", - "aws-smithy-http-client", - "aws-smithy-observability", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "bytes", - "fastrand", - "http", - "http-body", - "http-body-util", - "pin-project-lite", - "tokio", - "tracing", -] - -[[package]] -name = "aws-smithy-runtime-api" -version = "1.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20b0ce5fd8f8ec576f6737cf9a3a02172fddad2b90b8874577a4647fab11425c" -dependencies = [ - "aws-smithy-async", - "aws-smithy-runtime-api-macros", - "aws-smithy-types", - "bytes", - "http", - "pin-project-lite", - "tokio", - "tracing", - "zeroize", -] - -[[package]] -name = "aws-smithy-runtime-api-macros" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce237f890a2283c9b328955c3b0918d2d5bf66a1cb6ceccd36a0047246fbc6e6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "aws-smithy-schema" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7ef30d39e131651359b60a1c560de9a9502a4c3754172ab2d6e8734fe21bcba" -dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-types", - "http", -] - -[[package]] -name = "aws-smithy-types" -version = "1.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2085f9721fb3755821f8db7611a67ed15f4d6fdba6785b4db8ed7cd18eebee0f" -dependencies = [ - "base64-simd", - "bytes", - "bytes-utils", - "futures-core", - "http", - "http-body", - "http-body-util", - "itoa", - "pin-project-lite", - "ryu", - "serde", - "time", - "tokio", - "tokio-util", -] - -[[package]] -name = "aws-smithy-xml" -version = "0.64.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "590fdc1a70546b2f7f2061c42eaf173fb6f26d935330d069edc04dbd8f01d924" -dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "xmlparser", -] - -[[package]] -name = "aws-types" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ba0d970d3947bb064d2ae1d823efa186c1dbde88f88afa8f6549946e5d8deee" -dependencies = [ - "aws-credential-types", - "aws-smithy-async", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "rustc_version", - "tracing", -] - [[package]] name = "axum" version = "0.8.9" @@ -1379,16 +939,6 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" -[[package]] -name = "base64-simd" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" -dependencies = [ - "outref", - "vsimd", -] - [[package]] name = "base64ct" version = "1.8.3" @@ -1753,16 +1303,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bytes-utils" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" -dependencies = [ - "bytes", - "either", -] - [[package]] name = "bytesize" version = "2.7.0" @@ -4833,9 +4373,6 @@ name = "hashbrown" version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" -dependencies = [ - "foldhash 0.2.0", -] [[package]] name = "hayro-cmap" @@ -4875,7 +4412,7 @@ dependencies = [ "http", "httpdate", "mime", - "sha1 0.10.7", + "sha1", ] [[package]] @@ -4947,9 +4484,9 @@ dependencies = [ [[package]] name = "hipstr" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07a5072958d04f9147e517881d929d3f4706612712f8f4cfcd247f2b716d5262" +checksum = "637f99a632c30b144cb58da2b75a6f7e7f6aa76bf19e5291a154af518fa17aae" dependencies = [ "loom", "serde", @@ -6636,15 +6173,6 @@ dependencies = [ "weezl 0.2.1", ] -[[package]] -name = "lru" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" -dependencies = [ - "hashbrown 0.17.2", -] - [[package]] name = "lru-cache" version = "0.1.2" @@ -7226,8 +6754,6 @@ checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" name = "nvisy-assistant" version = "0.1.0" dependencies = [ - "async-stream", - "futures", "nvisy-core", "rig 0.47.0", "schemars 1.2.3", @@ -7250,7 +6776,6 @@ dependencies = [ "nvisy-core", "nvisy-server", "nvisy-webhook", - "serde", "tokio", "tokio-util", "tracing", @@ -7265,9 +6790,13 @@ dependencies = [ "bytes", "clap", "futures", + "http", "jiff 0.2.46", + "oauth2", "reqwest 0.13.5", "reqwest-middleware", + "reqwest-retry", + "reqwest-tracing", "schemars 1.2.3", "serde", "serde_json", @@ -7285,20 +6814,15 @@ dependencies = [ "bytes", "clap", "futures", - "http", "jiff 0.2.46", "nvisy-core", "oauth2", "percent-encoding", "reqwest 0.13.5", - "reqwest-middleware", - "reqwest-retry", - "reqwest-tracing", "schemars 1.2.3", "serde", "serde_json", "strum 0.28.0", - "thiserror 2.0.21", "tracing", "uuid", ] @@ -7327,7 +6851,6 @@ name = "nvisy-object-store" version = "0.1.0" dependencies = [ "bytes", - "derive_more", "futures", "nvisy-core", "object_store 0.14.2", @@ -7377,18 +6900,20 @@ name = "nvisy-s3" version = "0.1.0" dependencies = [ "async-trait", - "aws-config", - "aws-credential-types", - "aws-sdk-s3", - "aws-smithy-types", "base64 0.23.1", "clap", + "futures", "nvisy-core", + "nvisy-object-store", + "object_store 0.14.2", + "reqwest 0.13.5", "strum 0.28.0", "testcontainers-modules", "thiserror 2.0.21", "tokio", + "tokio-util", "tracing", + "url", "uuid", ] @@ -7438,6 +6963,7 @@ dependencies = [ "openidconnect", "pin-project-lite", "rand 0.10.4", + "reqwest 0.13.5", "schemars 1.2.3", "serde", "serde_json", @@ -7469,8 +6995,6 @@ dependencies = [ "nvisy-core", "reqwest 0.13.5", "reqwest-middleware", - "reqwest-retry", - "reqwest-tracing", "schemars 1.2.3", "serde", "serde_json", @@ -7492,7 +7016,6 @@ dependencies = [ "getrandom 0.2.17", "http", "rand 0.8.8", - "reqwest 0.12.28", "serde", "serde_json", "serde_path_to_error", @@ -7710,12 +7233,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "outref" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" - [[package]] name = "oxilangtag" version = "0.1.6" @@ -10016,17 +9533,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "sha1" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", -] - [[package]] name = "sha1_smol" version = "1.0.1" @@ -11264,7 +10770,7 @@ dependencies = [ "rand 0.9.5", "rustls", "rustls-pki-types", - "sha1 0.10.7", + "sha1", "thiserror 2.0.21", ] @@ -11478,12 +10984,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "urlencoding" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" - [[package]] name = "utf8-ranges" version = "1.0.5" @@ -11559,12 +11059,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "vsimd" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" - [[package]] name = "walkdir" version = "2.5.1" @@ -12181,12 +11675,6 @@ dependencies = [ "rustix", ] -[[package]] -name = "xmlparser" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" - [[package]] name = "xxhash-rust" version = "0.8.21" diff --git a/Cargo.toml b/Cargo.toml index 9c674c66..d9aaa80a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ debug = true # See for more details: https://github.com/rust-lang/cargo/issues/11329 # Elide crates -elide-pipeline = { git = "https://github.com/nvisycom/elide-runtime", rev = "6712316061b4497098ba5a7b61f7c0a7e70ca5b0", default-features = false } +elide-pipeline = { git = "https://github.com/nvisycom/elide-runtime", rev = "6712316061b4497098ba5a7b61f7c0a7e70ca5b0", default-features = false, features = [] } # Internal crates nvisy-core = { path = "./crates/nvisy-core", version = "0.1.0" } @@ -67,9 +67,7 @@ dotenvy = { version = "0.15", features = [] } # Async runtime tokio = { version = "1.54", features = [] } tokio-util = { version = "0.7", features = ["io"] } -tokio-stream = { version = "0.1", features = [] } futures = { version = "0.3", features = [] } -futures-util = { version = "0.3", features = [] } async-stream = { version = "0.3", features = [] } async-trait = { version = "0.1", features = [] } @@ -82,11 +80,9 @@ reqwest-middleware = { version = "0.5", features = ["json", "multipart"] } reqwest-retry = { version = "0.9", features = [] } reqwest-tracing = { version = "0.7", features = [] } -# OAuth2 (auth-code + refresh); no built-in HTTP client, driven via our reqwest -oauth2 = { version = "5.0", default-features = false } -# OIDC sign-in (discovery, JWKS, id_token validation); wraps oauth2 5.x. Uses its -# bundled reqwest+rustls HTTP client for discovery/JWKS/token calls. -openidconnect = { version = "4.1", default-features = false, features = ["reqwest", "rustls-tls"] } +# OAuth & OIDC +oauth2 = { version = "5.0", default-features = false, features = [] } +openidconnect = { version = "4.1", default-features = false, features = [] } http = { version = "1.5", features = [] } # HTTP server & middleware @@ -118,7 +114,6 @@ hmac = { version = "0.13", features = [] } # Encoding base64 = { version = "0.23", features = [] } hex = { version = "0.4", features = [] } -hipstr = { version = "0.8", features = [] } mime_guess = { version = "2.0", features = [] } percent-encoding = { version = "2.3", features = [] } @@ -134,56 +129,34 @@ diesel-derive-enum = { version = "2.1", features = [] } deadpool = { version = "0.13", features = [] } pgtrgm = { version = "0.5", features = [] } -# Messaging and object storage (NATS) +# Messaging (NATS) async-nats = { version = "0.53", features = [] } -# Cloud object storage +# Object storage object_store = { version = "0.14", features = [] } -# S3-compatible blob storage (AWS S3, RustFS, MinIO, R2) -aws-config = { version = "1.13", default-features = false, features = [ - "default-https-client", - "rt-tokio", - "credentials-process", - "sso", - "behavior-version-latest", -] } -aws-sdk-s3 = { version = "1.161", default-features = false, features = [ - "default-https-client", - "rt-tokio", - "sigv4a", - "http-1x", - "behavior-version-latest", -] } -aws-smithy-types = { version = "1.9", features = [] } -aws-credential-types = { version = "1.3", features = [] } - # Observability tracing = { version = "0.1", features = [] } tracing-subscriber = { version = "0.3", features = [] } # Testing utilities tempfile = { version = "3.27", features = [] } -mockall = { version = "0.15", features = [] } -# Each crate enables the module it needs (postgres/nats/minio) via its own -# `features = [...]`; Cargo unions them. testcontainers-modules = { version = "0.15", features = [] } # (De)serialization csv = { version = "1.4", features = [] } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = [] } -toml = { version = "1.2", features = [] } garde = { version = "0.23", features = ["derive", "email", "url"] } # Text processing slug = { version = "0.1", features = [] } +woothee = { version = "0.13", features = [] } # Derive macros & utilities thiserror = { version = "2.0", features = [] } strum = { version = "0.28", features = ["derive"] } derive_more = { version = "2.1", features = [] } -derive_builder = { version = "0.20", features = [] } anyhow = { version = "1.0", features = [] } pin-project-lite = { version = "0.2", features = [] } http-body = { version = "1.1", features = [] } @@ -198,18 +171,10 @@ time = { version = "0.3", features = [] } # Image processing image = { version = "0.25", default-features = false, features = ["jpeg", "png", "gif", "webp"] } -# Archive reading & writing -zip = { version = "9", default-features = false, features = ["deflate-flate2"] } - # Cron parsing -croner = { version = "5" } +croner = { version = "5", features = [] } chrono = { version = "0.4", default-features = false, features = ["std"] } # Domain datatypes & data structures ipnet = { version = "2.12", features = [] } url = { version = "2.5", features = [] } -semver = { version = "1.0", features = ["serde"] } - -# Text processing -regex = { version = "1.13", features = [] } -woothee = { version = "0.13", features = [] } diff --git a/crates/nvisy-assistant/Cargo.toml b/crates/nvisy-assistant/Cargo.toml index ae0b95b8..8a248112 100644 --- a/crates/nvisy-assistant/Cargo.toml +++ b/crates/nvisy-assistant/Cargo.toml @@ -25,28 +25,29 @@ schema = ["dep:schemars", "nvisy-core/schema"] [dependencies] # Internal crates -nvisy-core = { workspace = true } - -# Async runtime -futures = { workspace = true, features = [] } -async-stream = { workspace = true, features = [] } +nvisy-core = { workspace = true, features = [] } # LLM framework rig = { workspace = true, features = ["reqwest"] } +# OpenAPI/Documentation +schemars = { workspace = true, features = [], optional = true } + # Observability tracing = { workspace = true, features = [] } # (De)serialization serde = { workspace = true, features = ["derive"] } -schemars = { workspace = true, features = [], optional = true } # Derive macros & utilities thiserror = { workspace = true, features = [] } [dev-dependencies] -serde_json = { workspace = true, features = [] } +# Async runtime tokio = { workspace = true, features = ["macros", "rt"] } +# (De)serialization +serde_json = { workspace = true, features = [] } + [lints] workspace = true diff --git a/crates/nvisy-assistant/src/client/config.rs b/crates/nvisy-assistant/src/client/config.rs index e60e0264..219f1aff 100644 --- a/crates/nvisy-assistant/src/client/config.rs +++ b/crates/nvisy-assistant/src/client/config.rs @@ -1,15 +1,13 @@ //! The typed LLM connection configuration. use nvisy_core::Secret; +use rig::agent::AgentBuilder; #[cfg(feature = "schema")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use super::AssistantClient; +use super::{AssistantClient, providers}; use crate::error::Result; -use crate::provider::{ - AnthropicProvider, Client, OllamaCredentials, OllamaProvider, OpenAiProvider, -}; /// Configuration for a provider reached with an API key (`OpenAI`, Anthropic). /// @@ -72,9 +70,9 @@ impl LlmConfig { #[must_use] pub fn provider_id(&self) -> &'static str { match self { - Self::OpenAi(_) => OpenAiProvider::ID, - Self::Ollama(_) => OllamaProvider::ID, - Self::Anthropic(_) => AnthropicProvider::ID, + Self::OpenAi(_) => "openai", + Self::Ollama(_) => "ollama", + Self::Anthropic(_) => "anthropic", } } @@ -102,35 +100,17 @@ impl LlmConfig { /// credentials against the provider. /// /// Used by the connection test endpoint. Returns `Ok(())` when the provider - /// accepts the credentials, or an [`Error`] describing the build or - /// verification failure. + /// accepts the credentials, or an [`Error`] describing the verification + /// failure. /// /// [`Error`]: crate::Error /// /// # Errors /// - /// - A `Build` error if the provider client cannot be constructed from the - /// config. - /// - A `Verify` error if the provider rejects the credentials or is - /// unreachable. + /// A `Verify` error if the provider rejects the credentials or is + /// unreachable. pub async fn validate(&self) -> Result<()> { - match self { - Self::OpenAi(p) => { - OpenAiProvider::connect(p.api_key.expose(), p.base_url.as_deref()) - .verify() - .await - } - Self::Ollama(p) => { - OllamaProvider::connect(&OllamaCredentials, Some(&p.base_url)) - .verify() - .await - } - Self::Anthropic(p) => { - AnthropicProvider::connect(p.api_key.expose(), p.base_url.as_deref()) - .verify() - .await - } - } + providers::verify(self).await } /// Builds a ready-to-use [`AssistantClient`] for this config. @@ -139,25 +119,11 @@ impl LlmConfig { /// provider's own default applies. /// /// [`default_model`]: Self::default_model - /// - /// # Errors - /// - /// Returns a `Result` for a stable call-site seam; building a provider client - /// from a validated config does not currently fail. - pub fn connect(&self, model: Option<&str>) -> Result { + #[must_use] + pub fn connect(&self, model: Option<&str>) -> AssistantClient { let model = model.or_else(|| self.default_model()).unwrap_or_default(); - let client = match self { - Self::OpenAi(p) => { - OpenAiProvider::connect(p.api_key.expose(), p.base_url.as_deref()).model(model) - } - Self::Ollama(p) => { - OllamaProvider::connect(&OllamaCredentials, Some(&p.base_url)).model(model) - } - Self::Anthropic(p) => { - AnthropicProvider::connect(p.api_key.expose(), p.base_url.as_deref()).model(model) - } - }; - Ok(client) + let completion = providers::completion_model(self, model); + AssistantClient::new(AgentBuilder::new(completion).build()) } } @@ -200,8 +166,8 @@ impl AssistantConfig { /// /// # Errors /// - /// Returns an [`Error`] describing the build or verification failure when the - /// provider does not accept the credentials. + /// Returns an [`Error`] describing the verification failure when the provider + /// does not accept the credentials. /// /// [`Error`]: crate::Error pub async fn validate(&self) -> Result<()> { diff --git a/crates/nvisy-assistant/src/client/mod.rs b/crates/nvisy-assistant/src/client/mod.rs index 976fe57c..c5f3edcf 100644 --- a/crates/nvisy-assistant/src/client/mod.rs +++ b/crates/nvisy-assistant/src/client/mod.rs @@ -5,13 +5,12 @@ //! is the provider-agnostic runtime handle it builds. mod config; +mod providers; mod service; -mod token_stream; mod turn; pub use self::config::{ AssistantConfig, AuthenticatedProvider, LlmConfig, UnauthenticatedProvider, }; pub use self::service::AssistantClient; -pub use self::token_stream::TokenStream; pub use self::turn::{ChatTurn, Role}; diff --git a/crates/nvisy-assistant/src/client/providers.rs b/crates/nvisy-assistant/src/client/providers.rs new file mode 100644 index 00000000..5b2b863b --- /dev/null +++ b/crates/nvisy-assistant/src/client/providers.rs @@ -0,0 +1,62 @@ +//! The rig client for each provider, built from its stored config. + +use rig::DynModel; +use rig::error::ProviderError; +use rig::operation::Completion; +use rig::providers::anthropic::{self, AnthropicConfig}; +use rig::providers::ollama::{self, OllamaConfig}; +use rig::providers::openai::{self, OpenAIConfig}; + +use super::config::{AuthenticatedProvider, LlmConfig, UnauthenticatedProvider}; +use crate::error::{Error, Result}; + +/// An `OpenAI` client; also serves any OpenAI-compatible endpoint (Azure +/// `OpenAI`, a proxy) through `base_url`. +fn openai(provider: &AuthenticatedProvider) -> openai::OpenAI { + let mut config = OpenAIConfig::new(provider.api_key.expose()); + if let Some(base_url) = &provider.base_url { + config = config.with_base_url(base_url); + } + config.client() +} + +/// An Anthropic (Claude) client. +fn anthropic(provider: &AuthenticatedProvider) -> anthropic::Anthropic { + let mut config = AnthropicConfig::new(provider.api_key.expose()); + if let Some(base_url) = &provider.base_url { + config = config.with_base_url(base_url); + } + config.client() +} + +/// An Ollama client: self-hosted and unauthenticated, so only a base URL. +fn ollama(provider: &UnauthenticatedProvider) -> ollama::Ollama { + OllamaConfig::new() + .with_base_url(&provider.base_url) + .client() +} + +/// Checks `config`'s credentials, or for keyless Ollama that the daemon is +/// reachable (by listing its models). +pub(super) async fn verify(config: &LlmConfig) -> Result<()> { + let result = match config { + LlmConfig::OpenAi(provider) => openai(provider).verify().await, + LlmConfig::Anthropic(provider) => anthropic(provider).verify().await, + LlmConfig::Ollama(provider) => ollama(provider).list_models().await.map(drop), + }; + result.map_err(|err| match err { + ProviderError::InvalidAuthentication(_) => { + Error::Verify("invalid authentication".to_owned()) + } + err => Error::Verify(err.to_string()), + }) +} + +/// The completion model `config`'s provider serves `model` with. +pub(super) fn completion_model(config: &LlmConfig, model: &str) -> DynModel { + match config { + LlmConfig::OpenAi(provider) => openai(provider).completion(model).into(), + LlmConfig::Anthropic(provider) => anthropic(provider).completion(model).into(), + LlmConfig::Ollama(provider) => ollama(provider).completion(model).into(), + } +} diff --git a/crates/nvisy-assistant/src/client/service.rs b/crates/nvisy-assistant/src/client/service.rs index 728c1bd2..ed8684eb 100644 --- a/crates/nvisy-assistant/src/client/service.rs +++ b/crates/nvisy-assistant/src/client/service.rs @@ -1,23 +1,16 @@ //! Provider-agnostic assistant client backed by a rig agent. //! //! [`AssistantClient`] is a thin, cloneable wrapper around any provider's rig -//! [`Agent`] that provides convenience methods for the most common operations — -//! one-shot [`prompt`](AssistantClient::prompt), multi-turn -//! [`chat`](AssistantClient::chat), and streaming -//! [`stream_chat`](AssistantClient::stream_chat). Every public method is -//! instrumented with [`tracing`] for observability. It plays the same role for -//! language-model access that `ObjectStoreClient` plays for object storage: one -//! runtime handle callers use regardless of which provider backs it. +//! [`Agent`] that runs a multi-turn [`chat`](AssistantClient::chat), instrumented +//! with [`tracing`]: one runtime handle callers use regardless of which provider +//! backs it. use std::sync::Arc; -use async_stream::stream; -use futures::StreamExt; -use rig::agent::{Agent, MultiTurnStreamItem}; +use rig::agent::Agent; use rig::completion::Message; -use rig::streaming::{Item, StreamEvent}; -use super::{ChatTurn, TokenStream}; +use super::ChatTurn; use crate::error::{Error, Result}; /// Cloneable handle to any language-model backend (`OpenAI`, Anthropic, Ollama, ...). @@ -34,21 +27,6 @@ impl AssistantClient { Self(Arc::new(agent)) } - /// Send a single prompt with no conversation history and return the model's - /// text response. - /// - /// # Errors - /// - /// A `Prompt` error if the completion request fails at runtime. - #[tracing::instrument(name = "assistant.prompt", skip_all)] - pub async fn prompt(&self, prompt: &str) -> Result { - self.0 - .prompt(prompt.to_owned()) - .await - .map(|response| response.output()) - .map_err(|err| Error::Prompt(err.to_string())) - } - /// Run one chat turn against `history`, returning the model's text response. /// /// `history` is the prior conversation as [`ChatTurn`]s. @@ -65,46 +43,6 @@ impl AssistantClient { .map(|response| response.output()) .map_err(|err| Error::Prompt(err.to_string())) } - - /// Stream one chat turn against `history`, yielding the model's response as - /// text deltas. - /// - /// Returns immediately with a [`TokenStream`]; the request opens lazily when - /// the stream is first polled. Each item is a token chunk as it arrives, and - /// a failure mid-generation ends the stream with an `Err`. `history` is the - /// prior conversation as [`ChatTurn`]s; persist the user prompt and the - /// assembled reply on the caller side. - #[tracing::instrument(name = "assistant.stream_chat", skip_all, fields(history_len = history.len()))] - pub fn stream_chat(&self, prompt: &str, history: Vec) -> TokenStream { - // Own the agent handle in the generator so the result is `'static` and - // can outlive this `AssistantClient` (moved into a response body). The - // provider stream borrows the owned `Arc`, which the coroutine keeps - // alive for the whole stream. - let agent = Arc::clone(&self.0); - let prompt = prompt.to_owned(); - let history = to_messages(history); - let inner = stream! { - let stream = agent.prompt(prompt).history(history).stream(); - for await item in stream { - // Map rig's multi-turn stream down to bare text deltas: non-text - // items (tool calls, reasoning, the final-response marker) carry - // no user-visible text and are dropped. - match item { - Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event( - StreamEvent::Text { text, .. }, - ))) => yield Ok(text), - Ok(_) => {} - // An error is terminal: yield it and stop, per TokenStream's - // contract, rather than polling the rig stream again. - Err(err) => { - yield Err(Error::Prompt(err.to_string())); - break; - } - } - } - }; - TokenStream::new(inner.boxed()) - } } /// Converts a provider-agnostic history into rig messages. diff --git a/crates/nvisy-assistant/src/client/token_stream.rs b/crates/nvisy-assistant/src/client/token_stream.rs deleted file mode 100644 index c7d3eafd..00000000 --- a/crates/nvisy-assistant/src/client/token_stream.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! The [`TokenStream`] type: an assistant response streamed as text deltas. - -use std::pin::Pin; -use std::task::{Context, Poll}; - -use futures::Stream; -use futures::stream::{BoxStream, StreamExt}; - -use crate::error::Result; - -/// A stream of the assistant's response as text deltas. -/// -/// Each item is a token chunk (`Ok`); a failure mid-generation is the final item -/// (`Err`) and ends the stream. Owned and `'static`, so it can be moved into a -/// response body outliving the client that produced it. -/// -/// Yielded by [`AssistantClient::stream_chat`]. Poll it with the [`Stream`] API -/// ([`futures::StreamExt`]). -/// -/// [`AssistantClient::stream_chat`]: crate::AssistantClient::stream_chat -#[must_use = "a token stream does nothing unless polled"] -pub struct TokenStream { - inner: BoxStream<'static, Result>, -} - -impl TokenStream { - /// Wraps an owned delta stream. - pub(crate) fn new(inner: BoxStream<'static, Result>) -> Self { - Self { inner } - } -} - -impl Stream for TokenStream { - type Item = Result; - - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - self.inner.poll_next_unpin(cx) - } -} diff --git a/crates/nvisy-assistant/src/error.rs b/crates/nvisy-assistant/src/error.rs index cd4099bc..4ee2a951 100644 --- a/crates/nvisy-assistant/src/error.rs +++ b/crates/nvisy-assistant/src/error.rs @@ -3,15 +3,10 @@ /// A result whose error is the crate [`Error`]. pub type Result = std::result::Result; -/// An error building or validating an LLM provider client. +/// An error verifying an LLM provider or running a completion against it. #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum Error { - /// The client could not be constructed from the config (e.g. an invalid - /// base URL). - #[error("failed to build the assistant client: {0}")] - Build(String), - /// The provider rejected the credentials or was unreachable. #[error("provider verification failed: {0}")] Verify(String), diff --git a/crates/nvisy-assistant/src/lib.rs b/crates/nvisy-assistant/src/lib.rs index 077cdfdc..cbce23e1 100644 --- a/crates/nvisy-assistant/src/lib.rs +++ b/crates/nvisy-assistant/src/lib.rs @@ -4,10 +4,9 @@ mod client; mod error; -pub mod provider; pub use client::{ AssistantClient, AssistantConfig, AuthenticatedProvider, ChatTurn, LlmConfig, Role, - TokenStream, UnauthenticatedProvider, + UnauthenticatedProvider, }; pub use error::{Error, Result}; diff --git a/crates/nvisy-assistant/src/provider/anthropic.rs b/crates/nvisy-assistant/src/provider/anthropic.rs deleted file mode 100644 index af1951c3..00000000 --- a/crates/nvisy-assistant/src/provider/anthropic.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! Anthropic (Claude) provider, backed by rig's Anthropic client. - -use rig::DynModel; -use rig::operation::Completion; -use rig::providers::anthropic::{self, AnthropicConfig}; - -use super::{Client, map_verify}; -use crate::error::Result; - -/// Anthropic-backed assistant client. -pub struct AnthropicProvider(anthropic::Anthropic); - -impl Client for AnthropicProvider { - /// The Anthropic API key. - type Credentials = str; - - const ID: &str = "anthropic"; - - fn connect(api_key: &Self::Credentials, base_url: Option<&str>) -> Self { - let mut config = AnthropicConfig::new(api_key); - if let Some(base) = base_url { - config = config.with_base_url(base); - } - Self(config.client()) - } - - async fn verify(&self) -> Result<()> { - map_verify(self.0.verify().await) - } - - fn completion_model(&self, model: &str) -> DynModel { - self.0.completion(model).into() - } -} diff --git a/crates/nvisy-assistant/src/provider/mod.rs b/crates/nvisy-assistant/src/provider/mod.rs deleted file mode 100644 index a3d5c691..00000000 --- a/crates/nvisy-assistant/src/provider/mod.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! LLM provider clients and the dispatch trait over them. - -mod anthropic; -mod ollama; -mod openai; - -pub use anthropic::AnthropicProvider; -pub use ollama::OllamaProvider; -pub use openai::OpenAiProvider; -use rig::DynModel; -use rig::agent::AgentBuilder; -use rig::error::ProviderError; -use rig::operation::Completion; - -use crate::client::AssistantClient; -use crate::error::{Error, Result}; - -/// An LLM provider that builds a verifiable, prompt-capable client from -/// typed credentials. -/// -/// Each provider is a newtype wrapping its rig client. [`verify`](Client::verify) -/// checks its credentials, and [`model`](Client::model) turns it into a -/// provider-agnostic `AssistantClient`. -pub(crate) trait Client: Send + Sync + 'static { - /// The credential this provider connects with. A single-secret provider uses - /// `str` (the API key); a keyless one (Ollama) uses a unit type. - type Credentials: Send + Sync + ?Sized; - - /// Unique identifier (e.g. `openai`, `anthropic`). - const ID: &str; - - /// Build a client from credentials and an optional base-URL override. - fn connect(credentials: &Self::Credentials, base_url: Option<&str>) -> Self - where - Self: Sized; - - /// Verify the client's credentials against the provider. - /// - /// Succeeds when the provider accepts the credentials; maps an authentication - /// rejection or any other failure to [`Error::Verify`]. - fn verify(&self) -> impl Future> + Send; - - /// The rig completion model this provider serves `model` with, erased for - /// the agent builder. - fn completion_model(&self, model: &str) -> DynModel; - - /// Turn this provider client into a provider-agnostic [`AssistantClient`] - /// bound to `model`. - fn model(&self, model: &str) -> AssistantClient { - AssistantClient::new(AgentBuilder::new(self.completion_model(model)).build()) - } -} - -/// Maps a provider verification result to [`Error::Verify`], naming an -/// authentication rejection distinctly. -fn map_verify(result: std::result::Result<(), ProviderError>) -> Result<()> { - match result { - Ok(()) => Ok(()), - Err(ProviderError::InvalidAuthentication(_)) => { - Err(Error::Verify("invalid authentication".to_owned())) - } - Err(err) => Err(Error::Verify(err.to_string())), - } -} - -/// Keyless credentials for Ollama, which is typically unauthenticated. -#[derive(Debug, Clone, Copy)] -pub struct OllamaCredentials; diff --git a/crates/nvisy-assistant/src/provider/ollama.rs b/crates/nvisy-assistant/src/provider/ollama.rs deleted file mode 100644 index 8dc5c5af..00000000 --- a/crates/nvisy-assistant/src/provider/ollama.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Ollama provider, backed by rig's Ollama client. -//! -//! Ollama is typically self-hosted and unauthenticated, so it carries no -//! credentials — only a server base URL. - -use rig::DynModel; -use rig::operation::Completion; -use rig::providers::ollama::{self, OllamaConfig}; - -use super::{Client, OllamaCredentials, map_verify}; -use crate::error::Result; - -/// Ollama-backed assistant client. -pub struct OllamaProvider(ollama::Ollama); - -impl Client for OllamaProvider { - type Credentials = OllamaCredentials; - - const ID: &str = "ollama"; - - fn connect(_credentials: &Self::Credentials, base_url: Option<&str>) -> Self { - let mut config = OllamaConfig::new(); - if let Some(base) = base_url { - config = config.with_base_url(base); - } - Self(config.client()) - } - - /// Ollama is unauthenticated, so there is no credential to check, but the - /// daemon still has to be reachable at the configured base URL. Probe it by - /// listing models (`GET /api/tags`); an unreachable server or a wrong URL - /// fails here rather than at the first assistant request. - async fn verify(&self) -> Result<()> { - map_verify(self.0.list_models().await.map(|_| ())) - } - - fn completion_model(&self, model: &str) -> DynModel { - self.0.completion(model).into() - } -} diff --git a/crates/nvisy-assistant/src/provider/openai.rs b/crates/nvisy-assistant/src/provider/openai.rs deleted file mode 100644 index b8bccb2e..00000000 --- a/crates/nvisy-assistant/src/provider/openai.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! `OpenAI` provider, backed by rig's `OpenAI` client. -//! -//! Works with `OpenAI` and any OpenAI-compatible endpoint (Azure `OpenAI`, a proxy). - -use rig::DynModel; -use rig::operation::Completion; -use rig::providers::openai::{self, OpenAIConfig}; - -use super::{Client, map_verify}; -use crate::error::Result; - -/// OpenAI-backed assistant client. -pub struct OpenAiProvider(openai::OpenAI); - -impl Client for OpenAiProvider { - /// The `OpenAI` API key. - type Credentials = str; - - const ID: &str = "openai"; - - fn connect(api_key: &Self::Credentials, base_url: Option<&str>) -> Self { - let mut config = OpenAIConfig::new(api_key); - if let Some(base) = base_url { - config = config.with_base_url(base); - } - Self(config.client()) - } - - async fn verify(&self) -> Result<()> { - map_verify(self.0.verify().await) - } - - fn completion_model(&self, model: &str) -> DynModel { - self.0.completion(model).into() - } -} diff --git a/crates/nvisy-cli/Cargo.toml b/crates/nvisy-cli/Cargo.toml index 88360b86..725a8867 100644 --- a/crates/nvisy-cli/Cargo.toml +++ b/crates/nvisy-cli/Cargo.toml @@ -29,29 +29,24 @@ default = [] # TLS support: enables HTTPS with rustls for secure connections tls = ["axum-server"] -# OpenTelemetry support: enables environment-based log filtering -otel = ["tracing-subscriber/env-filter"] - # Dotenv support: loads environment variables from .env files # This allows configuration via .env files in addition to CLI args dotenv = ["dep:dotenvy"] [dependencies] -# Internal crates. Service configs and their clap wiring come through -# nvisy-server's `cli` feature; the reqwest webhook client is the binary's own -# choice of `WebhookService` implementation, so nvisy-webhook is a direct dep. +# Internal crates nvisy-core = { workspace = true, features = ["cli"] } nvisy-server = { workspace = true, features = ["cli"] } nvisy-webhook = { workspace = true, features = ["reqwest", "cli"] } -# Async runtime -tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal"] } -tokio-util = { workspace = true, features = [] } - # CLI clap = { workspace = true, features = ["derive", "env"] } dotenvy = { workspace = true, features = [], optional = true } +# Async runtime +tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal"] } +tokio-util = { workspace = true, features = [] } + # HTTP server & middleware axum = { workspace = true, features = ["http2", "macros"] } axum-server = { workspace = true, features = ["tls-rustls"], optional = true } @@ -60,9 +55,6 @@ axum-server = { workspace = true, features = ["tls-rustls"], optional = true } tracing = { workspace = true, features = [] } tracing-subscriber = { workspace = true, features = ["fmt", "ansi", "json", "env-filter"] } -# (De)serialization -serde = { workspace = true, features = ["derive"] } - # Derive macros & utilities anyhow = { workspace = true, features = ["backtrace"] } diff --git a/crates/nvisy-cli/src/config/mod.rs b/crates/nvisy-cli/src/config/mod.rs index 03f80d47..d622d7b6 100644 --- a/crates/nvisy-cli/src/config/mod.rs +++ b/crates/nvisy-cli/src/config/mod.rs @@ -143,7 +143,6 @@ impl Cli { fn enabled_features() -> Vec<&'static str> { [ cfg!(feature = "tls").then_some("tls"), - cfg!(feature = "otel").then_some("otel"), cfg!(feature = "dotenv").then_some("dotenv"), ] .into_iter() diff --git a/crates/nvisy-cli/src/config/server.rs b/crates/nvisy-cli/src/config/server.rs index 7348d900..6deba7c8 100644 --- a/crates/nvisy-cli/src/config/server.rs +++ b/crates/nvisy-cli/src/config/server.rs @@ -6,8 +6,8 @@ //! # Environment Variables //! //! - `HOST` - Server host address (default: 127.0.0.1) -//! - `PORT` - Server port (default: 3000) -//! - `SHUTDOWN_TIMEOUT` - Graceful shutdown timeout in seconds (default: 30) +//! - `PORT` - Server port (default: 8080) +//! - `SHUTDOWN_TIMEOUT` - Graceful shutdown timeout (default: 30s) //! - `TLS_CERT_PATH` - Path to TLS certificate (required when `tls` feature enabled) //! - `TLS_KEY_PATH` - Path to TLS private key (required when `tls` feature enabled) //! @@ -21,13 +21,12 @@ //! nvisy-cli --tls-cert-path ./cert.pem --tls-key-path ./key.pem //! ``` -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::net::{IpAddr, SocketAddr}; #[cfg(feature = "tls")] use std::path::PathBuf; use std::time::Duration; use clap::Args; -use serde::{Deserialize, Serialize}; use super::TRACING_TARGET_CONFIG; @@ -35,7 +34,7 @@ use super::TRACING_TARGET_CONFIG; /// /// Controls how the server binds to network interfaces, handles TLS, /// and performs graceful shutdown. -#[derive(Debug, Clone, Args, Serialize, Deserialize)] +#[derive(Debug, Clone, Args)] #[must_use = "config does nothing unless you use it"] pub struct ServerConfig { /// Host address to bind the server to. @@ -44,7 +43,6 @@ pub struct ServerConfig { /// /// In production, consider binding to specific interfaces for security. #[arg(long, env = "HOST", default_value = "127.0.0.1")] - #[serde(default = "default_host")] pub host: IpAddr, /// TCP port number for the server to listen on. @@ -78,11 +76,21 @@ pub struct ServerConfig { pub tls_key_path: PathBuf, } -const fn default_host() -> IpAddr { - IpAddr::V4(Ipv4Addr::UNSPECIFIED) -} - impl ServerConfig { + /// A loopback config on an OS-assigned port, for tests. + #[cfg(test)] + pub(crate) fn test() -> Self { + Self { + host: IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + port: 0, + shutdown_timeout: Duration::from_secs(30), + #[cfg(feature = "tls")] + tls_cert_path: PathBuf::from("cert.pem"), + #[cfg(feature = "tls")] + tls_key_path: PathBuf::from("key.pem"), + } + } + /// Returns the socket address for server binding. #[must_use] pub const fn socket_addr(&self) -> SocketAddr { @@ -122,50 +130,28 @@ impl ServerConfig { } } -impl Default for ServerConfig { - fn default() -> Self { - Self { - host: default_host(), - port: 3000, - shutdown_timeout: Duration::from_secs(30), - #[cfg(feature = "tls")] - tls_cert_path: PathBuf::from("cert.pem"), - #[cfg(feature = "tls")] - tls_key_path: PathBuf::from("key.pem"), - } - } -} - #[cfg(test)] mod tests { - use std::net::Ipv6Addr; + use std::net::{Ipv4Addr, Ipv6Addr}; use super::*; #[test] - fn default_config() { - let config = ServerConfig::default(); - assert!(config.binds_to_all_interfaces()); - assert_eq!(config.port, 3000); - assert_eq!(config.shutdown_timeout, Duration::from_secs(30)); - } - - #[test] - fn socket_addr_returns_correct_address() { - let config = ServerConfig::default(); - let addr = config.socket_addr(); - assert_eq!(addr.ip(), IpAddr::V4(Ipv4Addr::UNSPECIFIED)); - assert_eq!(addr.port(), 3000); + fn socket_addr_joins_host_and_port() { + let mut config = ServerConfig::test(); + config.port = 8080; + assert_eq!( + config.socket_addr(), + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) + ); } #[test] fn binds_to_all_interfaces_detection() { - let mut config = ServerConfig::default(); - assert!(config.binds_to_all_interfaces()); - - config.host = IpAddr::V4(Ipv4Addr::LOCALHOST); + let mut config = ServerConfig::test(); assert!(!config.binds_to_all_interfaces()); - + config.host = IpAddr::V4(Ipv4Addr::UNSPECIFIED); + assert!(config.binds_to_all_interfaces()); config.host = IpAddr::V6(Ipv6Addr::UNSPECIFIED); assert!(config.binds_to_all_interfaces()); } diff --git a/crates/nvisy-cli/src/server/lifecycle.rs b/crates/nvisy-cli/src/server/lifecycle.rs index 231d2adf..a10ec764 100644 --- a/crates/nvisy-cli/src/server/lifecycle.rs +++ b/crates/nvisy-cli/src/server/lifecycle.rs @@ -30,7 +30,6 @@ where let start_time = Instant::now(); log_security_warnings(server_config); - log_config_details(server_config); let result = serve_fn().await; @@ -47,19 +46,7 @@ fn log_security_warnings(config: &ServerConfig) { } } -/// Logs configuration details. -fn log_config_details(config: &ServerConfig) { - tracing::debug!( - target: TRACING_TARGET_STARTUP, - host = %config.host, - port = config.port, - shutdown_timeout = ?config.shutdown_timeout, - tls = config.is_tls_enabled(), - "Server configuration" - ); -} - -/// Handles the server result and logs appropriate messages. +/// Logs a clean shutdown, or a recovery suggestion for a failure. fn handle_result(result: io::Result<()>, start_time: Instant) -> io::Result<()> { let uptime = start_time.elapsed(); @@ -72,15 +59,8 @@ fn handle_result(result: io::Result<()>, start_time: Instant) -> io::Result<()> ); Ok(()) } + // The error itself is reported once, by `main`; this adds only the hint. Err(err) => { - tracing::error!( - target: TRACING_TARGET_SHUTDOWN, - error = %err, - kind = ?err.kind(), - uptime_secs = uptime.as_secs(), - "Fatal error" - ); - if let Some(suggestion) = error_suggestion(&err) { tracing::info!( target: TRACING_TARGET_SHUTDOWN, @@ -120,14 +100,14 @@ mod tests { #[tokio::test] async fn serve_with_shutdown_success() { - let config = ServerConfig::default(); + let config = ServerConfig::test(); let result = serve_with_shutdown(&config, || async { Ok(()) }).await; assert!(result.is_ok()); } #[tokio::test] async fn serve_with_shutdown_handles_error() { - let config = ServerConfig::default(); + let config = ServerConfig::test(); let result = serve_with_shutdown(&config, || async { Err(io::Error::other("test error")) }).await; diff --git a/crates/nvisy-core/Cargo.toml b/crates/nvisy-core/Cargo.toml index 852c680f..c525f37c 100644 --- a/crates/nvisy-core/Cargo.toml +++ b/crates/nvisy-core/Cargo.toml @@ -33,29 +33,43 @@ schema = ["dep:schemars"] # the duration parser config flags use. cli = ["dep:clap", "dep:jiff"] -# HTTP client support: classifies reqwest and reqwest-middleware failures into -# the shared error kinds. -reqwest = ["dep:reqwest", "dep:reqwest-middleware"] +# Test support: the container-boot limiter shared by every test harness. +test_util = ["tokio/sync"] + +# HTTP client support: the shared middleware stack, and the classification of +# reqwest failures into the shared error kinds. +reqwest = ["dep:reqwest", "dep:reqwest-middleware", "dep:reqwest-retry", "dep:reqwest-tracing"] + +# OAuth support: an `oauth2` HTTP transport over the shared middleware stack. +oauth2 = ["reqwest", "dep:oauth2", "dep:http"] [dependencies] +# CLI +clap = { workspace = true, features = ["derive"], optional = true } + # Async runtime -async-trait = { workspace = true } +async-trait = { workspace = true, features = [] } futures = { workspace = true, features = [] } tokio = { workspace = true, features = ["net"] } -# CLI -clap = { workspace = true, features = ["derive"], optional = true } - -# HTTP client +# HTTP client & middleware reqwest = { workspace = true, features = [], optional = true } reqwest-middleware = { workspace = true, features = [], optional = true } +reqwest-retry = { workspace = true, features = [], optional = true } +reqwest-tracing = { workspace = true, features = [], optional = true } + +# OAuth & OIDC +http = { workspace = true, features = [], optional = true } +oauth2 = { workspace = true, features = [], optional = true } + +# OpenAPI/Documentation +schemars = { workspace = true, optional = true, features = [] } # Observability tracing = { workspace = true, features = [] } # (De)serialization serde = { workspace = true, features = ["derive"] } -schemars = { workspace = true, optional = true } # Derive macros & utilities thiserror = { workspace = true, features = [] } @@ -63,11 +77,16 @@ thiserror = { workspace = true, features = [] } # Primitive datatypes bytes = { workspace = true, features = [] } jiff = { workspace = true, features = [], optional = true } + +# Domain datatypes & data structures url = { workspace = true, features = [] } [dev-dependencies] -serde_json = { workspace = true, features = [] } +# Async runtime tokio = { workspace = true, features = ["macros", "rt"] } +# (De)serialization +serde_json = { workspace = true, features = [] } + [lints] workspace = true diff --git a/crates/nvisy-core/src/http/mod.rs b/crates/nvisy-core/src/http/mod.rs new file mode 100644 index 00000000..b98da56f --- /dev/null +++ b/crates/nvisy-core/src/http/mod.rs @@ -0,0 +1,34 @@ +//! The shared outbound HTTP stack. +//! +//! Every client that calls an external service layers the same middleware on a +//! [`reqwest::Client`]: request tracing, then retry of transient failures with +//! exponential backoff. [`middleware_client`] builds that stack; each caller +//! keeps its own base client, since timeouts and redirect policy differ by use +//! (a streamed file transfer, a webhook delivery, a token request). +//! `OAuthHttpClient` runs `oauth2` requests through the same stack. + +#[cfg(feature = "oauth2")] +mod oauth; + +#[cfg(feature = "oauth2")] +pub use oauth::{OAuthHttpClient, OAuthHttpError}; +use reqwest_middleware::{ClientBuilder, ClientWithMiddleware}; +use reqwest_retry::RetryTransientMiddleware; +pub use reqwest_retry::policies::ExponentialBackoff; +use reqwest_tracing::TracingMiddleware; + +/// Wraps `client` with request tracing and retry of transient failures under +/// `retry`. +/// +/// A `reqwest::Client` is an `Arc` handle, so the result shares its connection +/// pool, TLS, and timeout configuration. +#[must_use] +pub fn middleware_client( + client: reqwest::Client, + retry: ExponentialBackoff, +) -> ClientWithMiddleware { + ClientBuilder::new(client) + .with(TracingMiddleware::default()) + .with(RetryTransientMiddleware::new_with_policy(retry)) + .build() +} diff --git a/crates/nvisy-core/src/http/oauth.rs b/crates/nvisy-core/src/http/oauth.rs new file mode 100644 index 00000000..8592baee --- /dev/null +++ b/crates/nvisy-core/src/http/oauth.rs @@ -0,0 +1,76 @@ +//! An `oauth2` transport over the shared HTTP stack. + +use std::pin::Pin; + +use oauth2::{AsyncHttpClient, HttpRequest, HttpResponse}; +use reqwest_middleware::ClientWithMiddleware; + +use super::{ExponentialBackoff, middleware_client}; + +/// Number of times a transient token-request failure is retried. +const MAX_RETRIES: u32 = 3; + +/// An error from the OAuth HTTP transport. +#[derive(Debug, thiserror::Error)] +pub enum OAuthHttpError { + /// The middleware chain or the underlying reqwest call failed. + #[error("oauth http request failed: {0}")] + Request(#[from] reqwest_middleware::Error), + /// The response could not be rebuilt as an `http::Response`. + #[error("oauth http response was invalid: {0}")] + Response(#[from] http::Error), +} + +/// An `oauth2` (and so `openidconnect`) async HTTP client that sends requests +/// through [`middleware_client`], retrying transient failures. +/// +/// `oauth2`'s built-in reqwest integration targets another reqwest major +/// version, so this implements its [`AsyncHttpClient`] over the workspace's +/// client, translating between the `http` crate's request and response types +/// and reqwest's. Build it once and share it: cloning is cheap. +#[derive(Clone)] +pub struct OAuthHttpClient { + http: ClientWithMiddleware, +} + +impl OAuthHttpClient { + /// Wraps `client` for OAuth requests, retrying transient failures with + /// exponential backoff. + #[must_use] + pub fn new(client: reqwest::Client) -> Self { + let retry = ExponentialBackoff::builder().build_with_max_retries(MAX_RETRIES); + Self { + http: middleware_client(client, retry), + } + } + + /// Sends one `oauth2` request and returns the reply rebuilt as the + /// `http::Response` `oauth2` expects: status, HTTP version, headers, body. + async fn send(&self, request: HttpRequest) -> Result { + let request = + reqwest::Request::try_from(request).map_err(reqwest_middleware::Error::from)?; + let response = self.http.execute(request).await?; + + let mut builder = http::Response::builder() + .status(response.status()) + .version(response.version()); + for (name, value) in response.headers() { + builder = builder.header(name, value); + } + let body = response + .bytes() + .await + .map_err(reqwest_middleware::Error::from)? + .to_vec(); + Ok(builder.body(body)?) + } +} + +impl<'c> AsyncHttpClient<'c> for OAuthHttpClient { + type Error = OAuthHttpError; + type Future = Pin> + Send + 'c>>; + + fn call(&'c self, request: HttpRequest) -> Self::Future { + Box::pin(self.send(request)) + } +} diff --git a/crates/nvisy-core/src/lib.rs b/crates/nvisy-core/src/lib.rs index 11905c2d..dbacce5a 100644 --- a/crates/nvisy-core/src/lib.rs +++ b/crates/nvisy-core/src/lib.rs @@ -6,8 +6,13 @@ mod duration; mod error; pub mod health; +#[cfg(feature = "reqwest")] +#[cfg_attr(docsrs, doc(cfg(feature = "reqwest")))] +pub mod http; pub mod net; mod secret; +#[cfg(feature = "test_util")] +pub mod test_util; mod transfer; #[cfg(feature = "cli")] diff --git a/crates/nvisy-core/src/test_util.rs b/crates/nvisy-core/src/test_util.rs new file mode 100644 index 00000000..da4481b1 --- /dev/null +++ b/crates/nvisy-core/src/test_util.rs @@ -0,0 +1,34 @@ +//! Test support shared by every crate's container-backed test harness. + +use std::sync::OnceLock; + +use tokio::sync::{Semaphore, SemaphorePermit}; + +/// Takes a permit to boot a test container (Postgres, NATS, or S3). +/// +/// Booting many containers at once stresses the Docker daemon enough that +/// readiness probes and first connections time out. One semaphore covers every +/// harness in the process, so a test binary that starts all three still boots +/// them one at a time. Hold the permit until the container is usable (started +/// and first connected); the tests themselves run in parallel afterwards. +/// +/// The permit count defaults to 1 and can be raised with the +/// `NVISY_TEST_BOOT_CONCURRENCY` environment variable. +/// +/// # Panics +/// +/// Never in practice: the semaphore is never closed. +pub async fn boot_permit() -> SemaphorePermit<'static> { + static BOOT: OnceLock = OnceLock::new(); + BOOT.get_or_init(|| { + let permits = std::env::var("NVISY_TEST_BOOT_CONCURRENCY") + .ok() + .and_then(|value| value.parse::().ok()) + .filter(|&n| n >= 1) + .unwrap_or(1); + Semaphore::new(permits) + }) + .acquire() + .await + .expect("the boot semaphore is never closed") +} diff --git a/crates/nvisy-file-service/Cargo.toml b/crates/nvisy-file-service/Cargo.toml index d89e0ff3..0d8260bb 100644 --- a/crates/nvisy-file-service/Cargo.toml +++ b/crates/nvisy-file-service/Cargo.toml @@ -27,25 +27,27 @@ cli = ["dep:clap"] [dependencies] # Internal crates -nvisy-core = { workspace = true, features = ["reqwest"] } +nvisy-core = { workspace = true, features = ["oauth2"] } # CLI clap = { workspace = true, features = ["derive", "env"], optional = true } # Async runtime futures = { workspace = true, features = [] } +async-trait = { workspace = true, features = [] } # HTTP client & middleware reqwest = { workspace = true, features = ["json", "query", "stream", "multipart"] } -reqwest-middleware = { workspace = true, features = [] } -reqwest-retry = { workspace = true, features = [] } -reqwest-tracing = { workspace = true, features = [] } + +# OAuth & OIDC oauth2 = { workspace = true, features = [] } -http = { workspace = true, features = [] } # OpenAPI/Documentation schemars = { workspace = true, features = [], optional = true } +# Encoding +percent-encoding = { workspace = true, features = [] } + # Observability tracing = { workspace = true, features = [] } @@ -53,12 +55,7 @@ tracing = { workspace = true, features = [] } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = [] } -# Encoding -percent-encoding = { workspace = true, features = [] } - # Derive macros & utilities -thiserror = { workspace = true, features = [] } -async-trait = { workspace = true, features = [] } strum = { workspace = true, features = ["derive"] } # Primitive datatypes diff --git a/crates/nvisy-file-service/src/client/config.rs b/crates/nvisy-file-service/src/client/config.rs index 62a06cb3..cfdfd34e 100644 --- a/crates/nvisy-file-service/src/client/config.rs +++ b/crates/nvisy-file-service/src/client/config.rs @@ -210,7 +210,7 @@ impl OAuthAppsConfig { /// Returns an error if the HTTP client cannot be built (see /// [`FileService::new`]). pub fn build(self) -> crate::Result { - FileService::new(self.into_apps()) + FileService::new(&self.into_apps()) } } diff --git a/crates/nvisy-file-service/src/client/service.rs b/crates/nvisy-file-service/src/client/service.rs index 77cd7d92..feb3cf4a 100644 --- a/crates/nvisy-file-service/src/client/service.rs +++ b/crates/nvisy-file-service/src/client/service.rs @@ -1,7 +1,7 @@ //! The dependency-injected entry point and the provider-neutral client surface. //! -//! [`FileService`] holds the shared HTTP client and the configured OAuth -//! apps, and turns a stored [`FileServiceConfig`] into a connected provider +//! [`FileService`] holds the shared HTTP client and an OAuth client per +//! configured provider, and turns a stored [`FileServiceConfig`] into a connected provider //! client, refreshing the OAuth token when expired. [`FileServiceClient`] is the //! provider-neutral surface the sync engine drives: verify the connection, //! stream a file's bytes, and upload a stream. Files to import are chosen through @@ -11,9 +11,14 @@ //! Token *persistence* is the caller's responsibility: a refresh returns the //! updated config via [`ConnectedFileService::refreshed`] for the caller to store. +use std::collections::HashMap; +use std::sync::Arc; use std::time::Duration; +use jiff::Timestamp; +use nvisy_core::http::OAuthHttpClient; use nvisy_core::{ByteStream, Error, ErrorKind, FileUpload, Result, Secret}; +use strum::IntoEnumIterator; use super::apps::OAuthApps; use super::connected::ConnectedFileService; @@ -37,34 +42,48 @@ const READ_TIMEOUT: Duration = Duration::from_secs(30); /// Connects cloud file-service configs to their provider backends, refreshing /// OAuth tokens as needed. /// -/// Cloneable and cheap to pass around; it holds the shared HTTP client and the -/// OAuth app credentials, and builds a fresh provider client per request. +/// Cloneable and cheap to pass around: it holds the shared HTTP client and one +/// [`OAuthClient`] per configured provider, built once, and builds a fresh +/// provider client per request. #[derive(Clone)] #[must_use = "service does nothing unless you use it"] pub struct FileService { http: reqwest::Client, - apps: OAuthApps, + oauth: Arc>, } impl FileService { - /// Creates a new [`FileService`] with the given OAuth app credentials. + /// Creates a new [`FileService`] for the given OAuth app credentials. /// /// Builds an HTTP client with finite connect and read timeouts so a stalled /// provider cannot pin a caller for its whole timeout window; no total /// request timeout is set, since transfers are streamed and can run long. + /// Then builds each configured provider's [`OAuthClient`] over it. /// /// # Errors /// - /// Returns an error if the HTTP client cannot be built. Falling back to a - /// default client would silently drop the connect and read timeouts and let - /// a stalled provider pin a caller indefinitely. - pub fn new(apps: OAuthApps) -> Result { + /// - A `Connection` error if the HTTP client cannot be built. Falling back + /// to a default client would silently drop the connect and read timeouts. + /// - An `Invalid` error if a configured app's redirect URI is not a valid + /// URL. + pub fn new(apps: &OAuthApps) -> Result { let http = reqwest::Client::builder() .connect_timeout(CONNECT_TIMEOUT) .read_timeout(READ_TIMEOUT) .build() .map_err(|err| Error::connection("failed to build HTTP client").with_source(err))?; - Ok(Self { http, apps }) + let oauth_http = OAuthHttpClient::new(http.clone()); + let oauth = FileServiceProvider::iter() + .filter_map(|provider| { + let app = apps.for_provider(provider)?; + let client = OAuthClient::new(provider.oauth_provider(), app, oauth_http.clone()); + Some(client.map(|client| (provider, client))) + }) + .collect::>>()?; + Ok(Self { + http, + oauth: Arc::new(oauth), + }) } /// Whether the host has configured an OAuth app for `provider`, and so @@ -72,29 +91,20 @@ impl FileService { /// attempting a flow that would fail. #[must_use] pub fn is_configured(&self, provider: FileServiceProvider) -> bool { - self.apps.for_provider(provider).is_some() + self.oauth.contains_key(&provider) } - /// An [`OAuthClient`] for `provider`, resolving its configured app, or an - /// error if the host has not configured one. This is the handle for the - /// authorize URL and the code/token exchanges. + /// The [`OAuthClient`] for `provider`: the handle for the authorize URL and + /// the code and token exchanges. /// /// # Errors /// /// Returns an `Invalid` error if the host has not configured an OAuth app /// for `provider`. - pub fn oauth_client(&self, provider: FileServiceProvider) -> Result { - let app = self.apps.for_provider(provider).ok_or_else(|| { - Error::new( - ErrorKind::Invalid, - "this cloud file provider is not configured", - ) - })?; - Ok(OAuthClient::new( - provider.oauth_provider(), - app.clone(), - self.http.clone(), - )) + pub fn oauth_client(&self, provider: FileServiceProvider) -> Result<&OAuthClient> { + self.oauth + .get(&provider) + .ok_or_else(|| Error::invalid("this cloud file provider is not configured")) } /// Ensures `config` has a usable access token, refreshing it if expired. @@ -107,7 +117,7 @@ impl FileService { /// Returns [`ErrorKind::Unauthenticated`] if the token is expired and there is /// no refresh token, or the refresh is rejected. pub async fn ensure_fresh(&self, config: &FileServiceConfig) -> Result { - let now = jiff::Timestamp::now().as_second(); + let now = Timestamp::now().as_second(); let tokens = config.tokens(); if !tokens.is_expired(now, REFRESH_SKEW_SECS) { return Ok(FreshToken { diff --git a/crates/nvisy-file-service/src/oauth/client.rs b/crates/nvisy-file-service/src/oauth/client.rs index 022ba271..1b8a639f 100644 --- a/crates/nvisy-file-service/src/oauth/client.rs +++ b/crates/nvisy-file-service/src/oauth/client.rs @@ -1,5 +1,7 @@ //! The [`OAuthClient`]: the authorization-code flow bound to a provider and app. +use jiff::Timestamp; +use nvisy_core::http::OAuthHttpClient; use nvisy_core::{Error, ErrorKind, Result, Secret}; use oauth2::basic::BasicClient; use oauth2::{ @@ -7,7 +9,6 @@ use oauth2::{ PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, RefreshToken, Scope, TokenResponse, TokenUrl, }; -use super::http_client::OAuthHttpClient; use super::types::{Authorization, OAuthApp, OAuthProvider, OAuthTokens}; /// A configured `oauth2` client for the authorization-code grant, with the auth, @@ -15,57 +16,55 @@ use super::types::{Authorization, OAuthApp, OAuthProvider, OAuthTokens}; type ConfiguredClient = BasicClient; -/// An `OAuth2` client bound to a provider, an app, and an HTTP client. +/// An `OAuth2` client bound to a provider, an app, and the shared OAuth HTTP +/// transport, built once and reused for every flow step. /// -/// Groups the parameters every flow step shares, so building the authorize URL, -/// exchanging a code, and refreshing a token are methods rather than functions -/// each threading provider/app/http. +/// Building validates the provider's endpoints and the app's redirect URI, so a +/// misconfigured app fails when the service is built rather than mid-flow. #[derive(Clone)] pub struct OAuthClient { + client: ConfiguredClient, provider: OAuthProvider, - app: OAuthApp, - http: reqwest::Client, + http: OAuthHttpClient, } impl OAuthClient { - /// Binds a provider and app to an HTTP client. - #[must_use] - pub fn new(provider: OAuthProvider, app: OAuthApp, http: reqwest::Client) -> Self { - Self { - provider, - app, - http, - } - } - - /// Builds the underlying `oauth2` client with the endpoints set. - fn build(&self) -> Result { - let auth_url = AuthUrl::new(self.provider.auth_url.clone()) - .map_err(|err| Error::connection("invalid OAuth auth URL").with_source(err))?; - let token_url = TokenUrl::new(self.provider.token_url.clone()) - .map_err(|err| Error::connection("invalid OAuth token URL").with_source(err))?; - let redirect_uri = RedirectUrl::new(self.app.redirect_uri.clone()) - .map_err(|err| Error::connection("invalid OAuth redirect URI").with_source(err))?; - - Ok(BasicClient::new(ClientId::new(self.app.client_id.clone())) - .set_client_secret(ClientSecret::new(self.app.client_secret.expose().clone())) + /// Builds the client for `provider` and `app`, sending token requests through + /// `http`. + /// + /// # Errors + /// + /// Returns an `Invalid` error if the auth URL, token URL, or redirect URI is + /// not a valid URL. + pub fn new(provider: OAuthProvider, app: &OAuthApp, http: OAuthHttpClient) -> Result { + let auth_url = AuthUrl::new(provider.auth_url.clone()) + .map_err(|err| Error::invalid("invalid OAuth auth URL").with_source(err))?; + let token_url = TokenUrl::new(provider.token_url.clone()) + .map_err(|err| Error::invalid("invalid OAuth token URL").with_source(err))?; + let redirect_uri = RedirectUrl::new(app.redirect_uri.clone()) + .map_err(|err| Error::invalid("invalid OAuth redirect URI").with_source(err))?; + + let client = BasicClient::new(ClientId::new(app.client_id.clone())) + .set_client_secret(ClientSecret::new(app.client_secret.expose().clone())) .set_auth_uri(auth_url) .set_token_uri(token_url) - .set_redirect_uri(redirect_uri)) + .set_redirect_uri(redirect_uri); + Ok(Self { + client, + provider, + http, + }) } /// Starts the authorization-code flow: returns the URL to send the user to /// plus the CSRF state and PKCE verifier the callback must present. /// - /// # Errors - /// - /// Returns a connection error if a configured OAuth endpoint (auth, token, or - /// redirect URI) is not a valid URL. - pub fn begin_authorization(&self) -> Result { - let client = self.build()?; + #[must_use] + pub fn begin_authorization(&self) -> Authorization { let (challenge, verifier) = PkceCodeChallenge::new_random_sha256(); - let mut request = client + let mut request = self + .client .authorize_url(CsrfToken::new_random) .set_pkce_challenge(challenge); for scope in &self.provider.scopes { @@ -76,26 +75,25 @@ impl OAuthClient { } let (authorize_url, csrf) = request.url(); - Ok(Authorization { + Authorization { authorize_url: authorize_url.to_string(), csrf_state: csrf.secret().clone(), pkce_verifier: verifier.secret().clone(), - }) + } } /// Exchanges an authorization `code` (with its PKCE `verifier`) for tokens. /// /// # Errors /// - /// Returns a connection error if a configured OAuth endpoint is not a valid - /// URL, or an `Unauthenticated` error if the code exchange request fails or is - /// rejected by the provider. + /// Returns an `Unauthenticated` error if the code exchange request fails or + /// is rejected by the provider. pub async fn exchange_code(&self, code: String, pkce_verifier: String) -> Result { let response = self - .build()? + .client .exchange_code(AuthorizationCode::new(code)) .set_pkce_verifier(PkceCodeVerifier::new(pkce_verifier)) - .request_async(&OAuthHttpClient::new(self.http.clone())) + .request_async(&self.http) .await .map_err(|err| { Error::new(ErrorKind::Unauthenticated, "OAuth code exchange failed") @@ -124,27 +122,21 @@ impl OAuthClient { /// /// # Errors /// - /// Returns a connection error if a configured OAuth endpoint is not a valid - /// URL, or an `Unauthenticated` error if the refresh request fails or is + /// Returns an `Unauthenticated` error if the refresh request fails or is /// rejected by the provider. pub async fn refresh_with_scopes( &self, refresh_token: &str, scopes: &[String], ) -> Result { - let client = self.build()?; let refresh = RefreshToken::new(refresh_token.to_owned()); - let mut request = client.exchange_refresh_token(&refresh); + let mut request = self.client.exchange_refresh_token(&refresh); for scope in scopes { request = request.add_scope(Scope::new(scope.clone())); } - let response = request - .request_async(&OAuthHttpClient::new(self.http.clone())) - .await - .map_err(|err| { - Error::new(ErrorKind::Unauthenticated, "OAuth token refresh failed") - .with_source(err) - })?; + let response = request.request_async(&self.http).await.map_err(|err| { + Error::new(ErrorKind::Unauthenticated, "OAuth token refresh failed").with_source(err) + })?; // A refresh response often omits the refresh token; keep the existing one. Ok(tokens_from_response( @@ -160,16 +152,10 @@ fn tokens_from_response( response: &oauth2::basic::BasicTokenResponse, existing_refresh: Option>, ) -> OAuthTokens { - let expires_at = response.expires_in().map(|d| { - let now = i64::try_from( - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs(), - ) - .unwrap_or(i64::MAX); - now + i64::try_from(d.as_secs()).unwrap_or(i64::MAX) - }); + let now = Timestamp::now().as_second(); + let expires_at = response + .expires_in() + .map(|lifetime| now.saturating_add(i64::try_from(lifetime.as_secs()).unwrap_or(i64::MAX))); OAuthTokens { access_token: Secret::new(response.access_token().secret().clone()), refresh_token: response diff --git a/crates/nvisy-file-service/src/oauth/http_client.rs b/crates/nvisy-file-service/src/oauth/http_client.rs deleted file mode 100644 index f5c98fc1..00000000 --- a/crates/nvisy-file-service/src/oauth/http_client.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! Adapter that lets the `oauth2` crate make its token requests through a shared -//! [`reqwest::Client`], with retry and tracing middleware layered on. -//! -//! `oauth2`'s built-in `reqwest` integration targets a different major version of -//! `reqwest` than the workspace uses, so its `Client` type does not match ours. -//! [`OAuthHttpClient`] implements `oauth2`'s [`AsyncHttpClient`] over our shared -//! client, translating between the `http` crate's request/response types (which -//! `oauth2` speaks) and `reqwest`. Token requests are short RPC calls, so -//! transient failures are retried with exponential backoff. - -use std::pin::Pin; - -use oauth2::{AsyncHttpClient, HttpRequest, HttpResponse}; -use reqwest_middleware::{ClientBuilder, ClientWithMiddleware}; -use reqwest_retry::RetryTransientMiddleware; -use reqwest_retry::policies::ExponentialBackoff; -use reqwest_tracing::TracingMiddleware; - -/// Number of times a transient token-request failure is retried before giving up. -const MAX_RETRIES: u32 = 3; - -/// An error from the OAuth HTTP transport. -#[derive(Debug, thiserror::Error)] -pub enum HttpClientError { - /// The middleware chain or the underlying reqwest call failed. - #[error("oauth http request failed: {0}")] - Request(#[from] reqwest_middleware::Error), - /// The response could not be rebuilt as an `http::Response`. - #[error("oauth http response was invalid: {0}")] - Response(#[from] http::Error), -} - -/// An `oauth2` async HTTP client backed by a shared [`reqwest::Client`] with -/// retry and tracing middleware. -/// -/// A `reqwest::Client` is an `Arc` handle, so building the middleware client over -/// one is cheap and shares its connection pool and TLS/proxy configuration. -pub struct OAuthHttpClient { - http: ClientWithMiddleware, -} - -impl OAuthHttpClient { - /// Wraps a shared reqwest client with retry (exponential backoff) and - /// tracing middleware for OAuth token requests. - pub fn new(client: reqwest::Client) -> Self { - let retry_policy = ExponentialBackoff::builder().build_with_max_retries(MAX_RETRIES); - let http = ClientBuilder::new(client) - .with(TracingMiddleware::default()) - .with(RetryTransientMiddleware::new_with_policy(retry_policy)) - .build(); - Self { http } - } - - /// Sends one `oauth2` request through the middleware client and returns the - /// reply, rebuilt as the `http::Response` `oauth2` expects. - /// - /// Mirrors `oauth2`'s own `reqwest::Client` integration (which targets an - /// incompatible `reqwest` version): convert the request with `try_into`, then - /// copy status, HTTP version, and headers onto the rebuilt response. - async fn send(&self, request: HttpRequest) -> Result { - let request = - reqwest::Request::try_from(request).map_err(reqwest_middleware::Error::from)?; - let response = self.http.execute(request).await?; - - let mut builder = http::Response::builder() - .status(response.status()) - .version(response.version()); - for (name, value) in response.headers() { - builder = builder.header(name, value); - } - let body = response - .bytes() - .await - .map_err(reqwest_middleware::Error::from)? - .to_vec(); - Ok(builder.body(body)?) - } -} - -impl<'c> AsyncHttpClient<'c> for OAuthHttpClient { - type Error = HttpClientError; - type Future = Pin> + Send + 'c>>; - - fn call(&'c self, request: HttpRequest) -> Self::Future { - Box::pin(self.send(request)) - } -} diff --git a/crates/nvisy-file-service/src/oauth/mod.rs b/crates/nvisy-file-service/src/oauth/mod.rs index 738a66fb..f26e7bde 100644 --- a/crates/nvisy-file-service/src/oauth/mod.rs +++ b/crates/nvisy-file-service/src/oauth/mod.rs @@ -2,16 +2,15 @@ //! //! Provides the reusable pieces every OAuth file-service provider needs: the //! per-provider endpoint/scope description ([`OAuthProvider`]), the persisted -//! token set ([`OAuthTokens`]), and an [`OAuthClient`] bound to a provider, app, -//! and HTTP client that builds an authorize URL with PKCE and CSRF state, and -//! exchanges codes and refresh tokens. +//! token set ([`OAuthTokens`]), and an [`OAuthClient`], built once per provider +//! and app, that builds an authorize URL with PKCE and CSRF state, and exchanges +//! codes and refresh tokens. //! //! The `oauth2` crate is used with no built-in HTTP client; every token request -//! runs through an adapter over a caller-supplied [`reqwest::Client`], so OAuth -//! traffic shares the same TLS/proxy/tracing setup as the rest of the platform. +//! runs through `nvisy-core`'s OAuth transport over the shared `reqwest` client, +//! so OAuth traffic shares the platform's TLS, retry, and tracing setup. mod client; -mod http_client; mod types; pub use self::client::OAuthClient; diff --git a/crates/nvisy-file-service/src/provider/box_provider.rs b/crates/nvisy-file-service/src/provider/box_provider.rs index 27b29fc2..172fa663 100644 --- a/crates/nvisy-file-service/src/provider/box_provider.rs +++ b/crates/nvisy-file-service/src/provider/box_provider.rs @@ -12,13 +12,11 @@ use nvisy_core::{ByteStream, FileUpload, Result, Secret}; -use super::{ProviderRequest, encode_path_segment, response_stream}; +use super::session::Session; +use super::{FileServiceProvider, encode_path_segment, response_stream}; use crate::client::FileServiceClient; use crate::oauth::OAuthProvider; -/// Provider identifier stored in the connection's `provider` column. -pub const PROVIDER_ID: &str = "box"; - /// Box OAuth authorize endpoint. const AUTH_URL: &str = "https://account.box.com/api/oauth2/authorize"; /// Box OAuth token endpoint. @@ -44,8 +42,7 @@ pub fn oauth_provider() -> OAuthProvider { /// A connected Box client holding a valid access token. pub struct BoxClient { - http: reqwest::Client, - access_token: Secret, + session: Session, /// The folder id that new exports are created in; `None` is the account root /// (`"0"`). root_folder_id: Option, @@ -59,8 +56,7 @@ impl BoxClient { root_folder_id: Option, ) -> Self { Self { - http, - access_token, + session: Session::new(http, access_token, FileServiceProvider::Box), root_folder_id, } } @@ -69,10 +65,8 @@ impl BoxClient { #[async_trait::async_trait] impl FileServiceClient for BoxClient { async fn verify(&self) -> Result<()> { - self.http - .get(format!("{API_BASE}/users/me")) - .bearer_auth(self.access_token.expose()) - .send_checked(PROVIDER_ID) + self.session + .send(self.session.get(format!("{API_BASE}/users/me"))) .await?; Ok(()) } @@ -83,10 +77,8 @@ impl FileServiceClient for BoxClient { // cannot alter the request URL. let id = encode_path_segment(id); let response = self - .http - .get(format!("{API_BASE}/files/{id}/content")) - .bearer_auth(self.access_token.expose()) - .send_checked(PROVIDER_ID) + .session + .send(self.session.get(format!("{API_BASE}/files/{id}/content"))) .await?; Ok(response_stream(response)) } @@ -109,11 +101,12 @@ impl FileServiceClient for BoxClient { .text("attributes", attributes) .part("file", content_part); - self.http - .post(format!("{UPLOAD_BASE}/files/content")) - .bearer_auth(self.access_token.expose()) - .multipart(form) - .send_checked(PROVIDER_ID) + self.session + .send( + self.session + .post(format!("{UPLOAD_BASE}/files/content")) + .multipart(form), + ) .await?; Ok(()) } diff --git a/crates/nvisy-file-service/src/provider/drive.rs b/crates/nvisy-file-service/src/provider/drive.rs index 02135ba4..ffc658b5 100644 --- a/crates/nvisy-file-service/src/provider/drive.rs +++ b/crates/nvisy-file-service/src/provider/drive.rs @@ -12,13 +12,11 @@ use bytes::Bytes; use futures::stream::{self, StreamExt}; use nvisy_core::{ByteStream, Error, FileUpload, Result, Secret}; -use super::{ProviderRequest, encode_path_segment, response_stream}; +use super::session::Session; +use super::{FileServiceProvider, encode_path_segment, response_stream}; use crate::client::FileServiceClient; use crate::oauth::OAuthProvider; -/// Provider identifier stored in the connection's `provider` column. -pub const PROVIDER_ID: &str = "google_drive"; - /// Drive OAuth authorize endpoint. const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth"; /// Google OAuth token endpoint. @@ -50,8 +48,7 @@ pub fn oauth_provider() -> OAuthProvider { /// A connected Google Drive client, holding a valid access token. pub struct DriveClient { - http: reqwest::Client, - access_token: Secret, + session: Session, /// The Drive folder id that new exports are created in; `None` uses the /// user's root. root_folder_id: Option, @@ -66,8 +63,7 @@ impl DriveClient { root_folder_id: Option, ) -> Self { Self { - http, - access_token, + session: Session::new(http, access_token, FileServiceProvider::GoogleDrive), root_folder_id, } } @@ -78,10 +74,11 @@ impl FileServiceClient for DriveClient { async fn verify(&self) -> Result<()> { // Fetch the lightweight `about` resource: reachable and authorized iff // it returns, without listing or transferring any file. - self.http - .get(format!("{API_BASE}/about?fields=user(emailAddress)")) - .bearer_auth(self.access_token.expose()) - .send_checked(PROVIDER_ID) + self.session + .send( + self.session + .get(format!("{API_BASE}/about?fields=user(emailAddress)")), + ) .await?; Ok(()) } @@ -91,10 +88,8 @@ impl FileServiceClient for DriveClient { // normally URL-safe, but a stored key must never alter the request URL. let id = encode_path_segment(id); let response = self - .http - .get(format!("{API_BASE}/files/{id}?alt=media")) - .bearer_auth(self.access_token.expose()) - .send_checked(PROVIDER_ID) + .session + .send(self.session.get(format!("{API_BASE}/files/{id}?alt=media"))) .await?; Ok(response_stream(response)) } @@ -134,15 +129,16 @@ impl FileServiceClient for DriveClient { .chain(body) .chain(stream::once(async { Ok(Bytes::from(epilogue)) })); - self.http - .post(format!("{UPLOAD_BASE}/files?uploadType=multipart")) - .bearer_auth(self.access_token.expose()) - .header( - "Content-Type", - format!("multipart/related; boundary={boundary}"), + self.session + .send( + self.session + .post(format!("{UPLOAD_BASE}/files?uploadType=multipart")) + .header( + "Content-Type", + format!("multipart/related; boundary={boundary}"), + ) + .body(reqwest::Body::wrap_stream(related)), ) - .body(reqwest::Body::wrap_stream(related)) - .send_checked(PROVIDER_ID) .await?; Ok(()) } diff --git a/crates/nvisy-file-service/src/provider/dropbox.rs b/crates/nvisy-file-service/src/provider/dropbox.rs index a1440dd3..4fbf276f 100644 --- a/crates/nvisy-file-service/src/provider/dropbox.rs +++ b/crates/nvisy-file-service/src/provider/dropbox.rs @@ -11,13 +11,11 @@ use std::fmt::Write; use nvisy_core::{ByteStream, FileUpload, Result, Secret}; use reqwest::header::CONTENT_LENGTH; -use super::{ProviderRequest, response_stream}; +use super::session::Session; +use super::{FileServiceProvider, response_stream}; use crate::client::FileServiceClient; use crate::oauth::OAuthProvider; -/// Provider identifier stored in the connection's `provider` column. -pub const PROVIDER_ID: &str = "dropbox"; - /// Dropbox OAuth authorize endpoint. const AUTH_URL: &str = "https://www.dropbox.com/oauth2/authorize"; /// Dropbox OAuth token endpoint. @@ -46,8 +44,7 @@ pub fn oauth_provider() -> OAuthProvider { /// A connected Dropbox client holding a valid access token. pub struct DropboxClient { - http: reqwest::Client, - access_token: Secret, + session: Session, /// The folder path new exports are written into; `None` (or empty) is the /// account root. root_path: Option, @@ -66,8 +63,7 @@ impl DropboxClient { root_path: Option, ) -> Self { Self { - http, - access_token, + session: Session::new(http, access_token, FileServiceProvider::Dropbox), root_path: normalize_root(root_path), } } @@ -106,10 +102,11 @@ fn api_arg(value: &serde_json::Value) -> String { impl FileServiceClient for DropboxClient { async fn verify(&self) -> Result<()> { // get_current_account is the idiomatic whoami; it takes an empty body. - self.http - .post(format!("{API_BASE}/users/get_current_account")) - .bearer_auth(self.access_token.expose()) - .send_checked(PROVIDER_ID) + self.session + .send( + self.session + .post(format!("{API_BASE}/users/get_current_account")), + ) .await?; Ok(()) } @@ -117,11 +114,12 @@ impl FileServiceClient for DropboxClient { async fn get_stream(&self, id: &str) -> Result { let arg = api_arg(&serde_json::json!({ "path": id })); let response = self - .http - .post(format!("{CONTENT_BASE}/files/download")) - .bearer_auth(self.access_token.expose()) - .header("Dropbox-API-Arg", arg) - .send_checked(PROVIDER_ID) + .session + .send( + self.session + .post(format!("{CONTENT_BASE}/files/download")) + .header("Dropbox-API-Arg", arg), + ) .await?; Ok(response_stream(response)) } @@ -147,14 +145,15 @@ impl FileServiceClient for DropboxClient { // known Content-Length. The body is streamed (not buffered), so set the // length explicitly from the caller's known size. Simple upload is capped // at 150 MiB by Dropbox; larger files would need an upload session. - self.http - .post(format!("{CONTENT_BASE}/files/upload")) - .bearer_auth(self.access_token.expose()) - .header("Dropbox-API-Arg", arg) - .header("Content-Type", "application/octet-stream") - .header(CONTENT_LENGTH, content_length) - .body(reqwest::Body::wrap_stream(body)) - .send_checked(PROVIDER_ID) + self.session + .send( + self.session + .post(format!("{CONTENT_BASE}/files/upload")) + .header("Dropbox-API-Arg", arg) + .header("Content-Type", "application/octet-stream") + .header(CONTENT_LENGTH, content_length) + .body(reqwest::Body::wrap_stream(body)), + ) .await?; Ok(()) } diff --git a/crates/nvisy-file-service/src/provider/mod.rs b/crates/nvisy-file-service/src/provider/mod.rs index dca6df3c..7751a6be 100644 --- a/crates/nvisy-file-service/src/provider/mod.rs +++ b/crates/nvisy-file-service/src/provider/mod.rs @@ -10,15 +10,16 @@ mod box_provider; mod drive; mod dropbox; mod onedrive; +mod session; use futures::TryStreamExt; -use nvisy_core::{ByteStream, Error, ErrorKind, Result, Secret, kind_for_status}; +use nvisy_core::{ByteStream, Error, ErrorKind, Result, Secret}; use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode}; use reqwest::Response; #[cfg(feature = "schema")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use strum::EnumIter; +use strum::{EnumIter, IntoStaticStr}; use crate::client::{FileService, FileServiceClient, PickerAccessToken}; use crate::oauth::{OAuthProvider, OAuthTokens}; @@ -32,78 +33,6 @@ fn response_stream(response: Response) -> ByteStream { Box::pin(response.bytes_stream().map_err(Error::from)) } -/// Sends a provider request and checks its status in one step, surfacing the -/// provider's own error body — the single place every provider request goes -/// through so a failure is legible rather than an opaque status. -#[async_trait::async_trait] -trait ProviderRequest { - /// Sends the request; on a non-2xx, reads a bounded prefix of the provider's - /// response body, logs it, and returns an error carrying it, classified by - /// status. On success, returns the [`Response`] for the caller to consume - /// (JSON, byte stream, or discard). - /// - /// `reqwest`'s own `error_for_status` drops the body, but providers (Dropbox - /// especially) put the actual reason there, so a bare status is useless for - /// diagnosis. `provider` labels the log and error for the failing provider. - async fn send_checked(self, provider: &str) -> Result; -} - -/// Cap on how many bytes of a failed provider response body are read, so a large -/// or unbounded error body cannot cause memory pressure or flood the logs on this -/// shared request path. Comfortably covers the JSON error objects providers -/// return while bounding the pathological case. -const MAX_ERROR_BODY_BYTES: usize = 8 * 1024; - -#[async_trait::async_trait] -impl ProviderRequest for reqwest::RequestBuilder { - async fn send_checked(self, provider: &str) -> Result { - let response = self.send().await?; - let status = response.status(); - if status.is_success() { - return Ok(response); - } - // Read only a bounded prefix of the body: it may be large or unbounded, - // and this runs on every provider request. - let body = read_bounded_body(response, MAX_ERROR_BODY_BYTES).await; - tracing::warn!( - target: TRACING_TARGET, - %provider, status = status.as_u16(), body = %body, - "FileServiceProvider request failed", - ); - let detail: String = body.trim().chars().take(300).collect(); - let message = if detail.is_empty() { - format!( - "[{provider}] request failed with status {}", - status.as_u16() - ) - } else { - format!("[{provider}] {detail}") - }; - Err(Error::new(kind_for_status(status.as_u16()), message)) - } -} - -/// Reads at most `cap` bytes of a response body, then stops (dropping the rest of -/// the stream). Best-effort and lossy by design: it is used only to surface a -/// diagnostic prefix of a provider error, so a stream error mid-read yields -/// whatever was read so far, and the bytes are decoded lossily. -async fn read_bounded_body(response: Response, cap: usize) -> String { - use futures::StreamExt; - - let mut stream = response.bytes_stream(); - let mut buf: Vec = Vec::new(); - while buf.len() < cap { - match stream.next().await { - Some(Ok(chunk)) => { - let take = (cap - buf.len()).min(chunk.len()); - buf.extend_from_slice(&chunk[..take]); - } - Some(Err(_)) | None => break, - } - } - String::from_utf8_lossy(&buf).into_owned() -} - /// Percent-encodes a provider file id or name for safe interpolation into a /// request URL path segment. /// @@ -120,9 +49,11 @@ fn encode_path_segment(segment: &str) -> String { /// /// The serialized form (`snake_case`) is the `provider` tag stored on a connection /// and used in the API, so every provider name lives in exactly one place. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, EnumIter)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Deserialize, Serialize, EnumIter, IntoStaticStr)] #[cfg_attr(feature = "schema", derive(JsonSchema))] #[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] pub enum FileServiceProvider { /// Google Drive. GoogleDrive, @@ -139,12 +70,7 @@ impl FileServiceProvider { /// matching the serialized tag. #[must_use] pub fn id(self) -> &'static str { - match self { - Self::GoogleDrive => drive::PROVIDER_ID, - Self::Dropbox => dropbox::PROVIDER_ID, - Self::OneDrive => onedrive::PROVIDER_ID, - Self::Box => box_provider::PROVIDER_ID, - } + self.into() } /// The OAuth endpoints and scopes for this provider. diff --git a/crates/nvisy-file-service/src/provider/onedrive.rs b/crates/nvisy-file-service/src/provider/onedrive.rs index d8fb39ba..0d9ce214 100644 --- a/crates/nvisy-file-service/src/provider/onedrive.rs +++ b/crates/nvisy-file-service/src/provider/onedrive.rs @@ -9,16 +9,11 @@ use nvisy_core::{ByteStream, Error, ErrorKind, FileUpload, Result, Secret}; use reqwest::header::CONTENT_LENGTH; use serde::Deserialize; -use super::{FileServiceConfig, ProviderRequest, encode_path_segment, response_stream}; +use super::session::Session; +use super::{FileServiceConfig, FileServiceProvider, encode_path_segment, response_stream}; use crate::client::{FileService, FileServiceClient, PickerAccessToken}; use crate::oauth::OAuthProvider; -/// Provider identifier stored in the connection's `provider` column. -/// -/// Must match `FileServiceProvider::OneDrive`'s serde tag (`one_drive`) so the -/// stored provider column and the serialized config agree. -pub const PROVIDER_ID: &str = "one_drive"; - /// Microsoft identity platform authorize endpoint (multi-tenant + personal). const AUTH_URL: &str = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"; /// Microsoft identity platform token endpoint. @@ -76,15 +71,18 @@ pub(super) async fn mint_picker_token( let fresh = service.ensure_fresh(config).await?; let effective = fresh.refreshed.as_ref().unwrap_or(config); - let host = resolve_sharepoint_host(service.http(), fresh.access_token.expose()) - .await? - .ok_or_else(|| { - Error::new( - ErrorKind::Invalid, - "the OneDrive file picker is available only for work or school \ + let graph = Session::new( + service.http().clone(), + fresh.access_token.clone(), + FileServiceProvider::OneDrive, + ); + let host = resolve_sharepoint_host(&graph).await?.ok_or_else(|| { + Error::new( + ErrorKind::Invalid, + "the OneDrive file picker is available only for work or school \ (OneDrive for Business) accounts, not personal accounts", - ) - })?; + ) + })?; // The picker names the resource it wants per `authenticate` command; fall back // to the account's SharePoint host. A client-supplied resource is untrusted — @@ -115,7 +113,7 @@ pub(super) async fn mint_picker_token( } /// Resolves the `SharePoint` host that backs a `OneDrive` account's drive, using a -/// Microsoft Graph access token. Returns `None` for a consumer/personal account, +/// Microsoft Graph session. Returns `None` for a consumer/personal account, /// whose drive is on the legacy consumer `OneDrive` service and has no `SharePoint` /// host. /// @@ -128,30 +126,19 @@ pub(super) async fn mint_picker_token( /// # Errors /// /// Returns an error if the Graph request fails or its body cannot be parsed. -pub(super) async fn resolve_sharepoint_host( - http: &reqwest::Client, - graph_access_token: &str, -) -> Result> { +pub(super) async fn resolve_sharepoint_host(graph: &Session) -> Result> { #[derive(Deserialize)] struct DriveResponse { #[serde(rename = "webUrl")] web_url: Option, } - let response = http - .get(format!("{API_BASE}/me/drive?$select=webUrl")) - .bearer_auth(graph_access_token) - .send() - .await - .map_err(|err| Error::connection("failed to query OneDrive drive").with_source(err))? - // Classify by status via the crate's `From`, so 401 maps - // to an auth error while a 429 throttle or 5xx outage maps to a transient - // kind rather than an auth failure. - .error_for_status() - .map_err(Error::from)? + let response = graph + .send(graph.get(format!("{API_BASE}/me/drive?$select=webUrl"))) + .await? .json::() .await - .map_err(|err| Error::connection("invalid OneDrive drive response").with_source(err))?; + .map_err(|err| Error::runtime("invalid OneDrive drive response").with_source(err))?; let host = response.web_url.and_then(|url| { let parsed = reqwest::Url::parse(&url).ok()?; @@ -195,8 +182,7 @@ fn same_sharepoint_tenant(host: &str, resource: &str) -> bool { /// A connected `OneDrive` client holding a valid access token. pub struct OneDriveClient { - http: reqwest::Client, - access_token: Secret, + session: Session, /// The drive item id of the folder new exports are created in; `None` is the /// drive root. root_folder_id: Option, @@ -210,8 +196,7 @@ impl OneDriveClient { root_folder_id: Option, ) -> Self { Self { - http, - access_token, + session: Session::new(http, access_token, FileServiceProvider::OneDrive), root_folder_id, } } @@ -220,10 +205,8 @@ impl OneDriveClient { #[async_trait::async_trait] impl FileServiceClient for OneDriveClient { async fn verify(&self) -> Result<()> { - self.http - .get(format!("{API_BASE}/me/drive")) - .bearer_auth(self.access_token.expose()) - .send_checked(PROVIDER_ID) + self.session + .send(self.session.get(format!("{API_BASE}/me/drive"))) .await?; Ok(()) } @@ -235,10 +218,11 @@ impl FileServiceClient for OneDriveClient { // request URL. let id = encode_path_segment(id); let response = self - .http - .get(format!("{API_BASE}/me/drive/items/{id}/content")) - .bearer_auth(self.access_token.expose()) - .send_checked(PROVIDER_ID) + .session + .send( + self.session + .get(format!("{API_BASE}/me/drive/items/{id}/content")), + ) .await?; Ok(response_stream(response)) } @@ -262,13 +246,14 @@ impl FileServiceClient for OneDriveClient { } None => format!("{API_BASE}/me/drive/root:/{name}:/content"), }; - self.http - .put(url) - .bearer_auth(self.access_token.expose()) - .header("Content-Type", content_type) - .header(CONTENT_LENGTH, content_length) - .body(reqwest::Body::wrap_stream(body)) - .send_checked(PROVIDER_ID) + self.session + .send( + self.session + .put(url) + .header("Content-Type", content_type) + .header(CONTENT_LENGTH, content_length) + .body(reqwest::Body::wrap_stream(body)), + ) .await?; Ok(()) } diff --git a/crates/nvisy-file-service/src/provider/session.rs b/crates/nvisy-file-service/src/provider/session.rs new file mode 100644 index 00000000..206572ab --- /dev/null +++ b/crates/nvisy-file-service/src/provider/session.rs @@ -0,0 +1,110 @@ +//! An authorized session against one provider: the shared HTTP client, the +//! access token, and the provider every request is labelled with. + +use futures::StreamExt; +use nvisy_core::{Error, Result, Secret, kind_for_status}; +use reqwest::{IntoUrl, RequestBuilder, Response}; + +use super::{FileServiceProvider, TRACING_TARGET}; + +/// Cap on how many bytes of a failed provider response body are read, so a large +/// or unbounded error body cannot cause memory pressure or flood the logs. +/// Comfortably covers the JSON error objects providers return. +const MAX_ERROR_BODY_BYTES: usize = 8 * 1024; + +/// Most characters of a provider's error body carried into the error message. +const MAX_ERROR_DETAIL_CHARS: usize = 300; + +/// An authorized session against one provider. +/// +/// Every request it builds carries the bearer token, and every request goes +/// through [`send`](Self::send), so a failure is classified by status and +/// carries the provider's own error body rather than an opaque status. +pub(crate) struct Session { + http: reqwest::Client, + access_token: Secret, + provider: FileServiceProvider, +} + +impl Session { + /// Opens a session for `provider` with an already-valid access token. + pub(crate) fn new( + http: reqwest::Client, + access_token: Secret, + provider: FileServiceProvider, + ) -> Self { + Self { + http, + access_token, + provider, + } + } + + /// An authorized `GET` request to `url`. + pub(crate) fn get(&self, url: impl IntoUrl) -> RequestBuilder { + self.http.get(url).bearer_auth(self.access_token.expose()) + } + + /// An authorized `POST` request to `url`. + pub(crate) fn post(&self, url: impl IntoUrl) -> RequestBuilder { + self.http.post(url).bearer_auth(self.access_token.expose()) + } + + /// An authorized `PUT` request to `url`. + pub(crate) fn put(&self, url: impl IntoUrl) -> RequestBuilder { + self.http.put(url).bearer_auth(self.access_token.expose()) + } + + /// Sends `request` and checks its status. On a non-2xx, reads a bounded + /// prefix of the provider's response body, logs it, and returns an error + /// carrying it, classified by status; on success, returns the response for + /// the caller to consume. + /// + /// `reqwest`'s own `error_for_status` drops the body, but providers (Dropbox + /// especially) put the actual reason there. + /// + /// # Errors + /// + /// An error classified by the response status, or by the transport failure + /// if no response arrived. + pub(crate) async fn send(&self, request: RequestBuilder) -> Result { + let response = request.send().await?; + let status = response.status(); + if status.is_success() { + return Ok(response); + } + + let provider: &'static str = self.provider.into(); + let body = read_bounded_body(response).await; + tracing::warn!( + target: TRACING_TARGET, + provider, status = status.as_u16(), body = %body, + "Provider request failed", + ); + let detail: String = body.trim().chars().take(MAX_ERROR_DETAIL_CHARS).collect(); + let message = if detail.is_empty() { + format!("{provider} request failed with status {}", status.as_u16()) + } else { + format!("{provider}: {detail}") + }; + Err(Error::new(kind_for_status(status.as_u16()), message)) + } +} + +/// Reads at most [`MAX_ERROR_BODY_BYTES`] of a response body, then stops. +/// Best-effort and lossy by design: it only surfaces a diagnostic prefix, so a +/// stream error mid-read yields whatever was read, decoded lossily. +async fn read_bounded_body(response: Response) -> String { + let mut stream = response.bytes_stream(); + let mut buf: Vec = Vec::new(); + while buf.len() < MAX_ERROR_BODY_BYTES { + match stream.next().await { + Some(Ok(chunk)) => { + let take = (MAX_ERROR_BODY_BYTES - buf.len()).min(chunk.len()); + buf.extend_from_slice(&chunk[..take]); + } + Some(Err(_)) | None => break, + } + } + String::from_utf8_lossy(&buf).into_owned() +} diff --git a/crates/nvisy-nats/Cargo.toml b/crates/nvisy-nats/Cargo.toml index adc9afb8..307b83d3 100644 --- a/crates/nvisy-nats/Cargo.toml +++ b/crates/nvisy-nats/Cargo.toml @@ -32,31 +32,33 @@ cli = ["dep:clap", "nvisy-core/cli"] # Test support: an ephemeral NATS (JetStream) container + connected client, for # this crate's tests and for downstream crates that compose a real server. -test_util = ["dep:testcontainers-modules", "tokio/sync"] +test_util = ["dep:testcontainers-modules", "nvisy-core/test_util"] [dependencies] # Internal crates -nvisy-core = { workspace = true } +nvisy-core = { workspace = true, features = [] } + +# CLI +clap = { workspace = true, features = ["derive", "env"], optional = true } # Async runtime tokio = { workspace = true, features = ["rt-multi-thread", "macros", "time", "sync"] } tokio-util = { workspace = true, features = ["rt"] } futures = { workspace = true, features = [] } -async-trait = { workspace = true } +async-trait = { workspace = true, features = [] } # Messaging (NATS) -async-nats = { workspace = true } +async-nats = { workspace = true, features = [] } # Observability tracing = { workspace = true, features = [] } +# Testing utilities +testcontainers-modules = { workspace = true, features = ["nats"], optional = true } + # (De)serialization serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = [] } -clap = { workspace = true, features = ["derive", "env"], optional = true } - -# Test-only: ephemeral NATS container (gated on the `test_util` feature). -testcontainers-modules = { workspace = true, features = ["nats"], optional = true } # Derive macros & utilities thiserror = { workspace = true, features = [] } diff --git a/crates/nvisy-nats/src/client/config.rs b/crates/nvisy-nats/src/client/config.rs index c29da409..9bca76a5 100644 --- a/crates/nvisy-nats/src/client/config.rs +++ b/crates/nvisy-nats/src/client/config.rs @@ -133,13 +133,6 @@ impl NatsConfig { let max = self.nats_max_reconnects.unwrap_or(DEFAULT_MAX_RECONNECTS); if max == 0 { None } else { Some(max) } } - - /// Set the request-reply timeout. - #[must_use] - pub fn with_request_timeout(mut self, timeout: Duration) -> Self { - self.nats_request_timeout = Some(timeout); - self - } } #[cfg(test)] @@ -170,13 +163,6 @@ mod tests { assert_eq!(config.max_reconnects_option(), Some(10)); } - #[test] - fn test_with_request_timeout() { - let config = NatsConfig::new("nats://localhost:4222", "token") - .with_request_timeout(Duration::from_secs(15)); - assert_eq!(config.nats_request_timeout, Some(Duration::from_secs(15))); - } - #[test] fn test_unlimited_reconnects() { let mut config = NatsConfig::new("nats://localhost:4222", "token"); diff --git a/crates/nvisy-nats/src/client/service.rs b/crates/nvisy-nats/src/client/service.rs index 8226ce84..ba02c530 100644 --- a/crates/nvisy-nats/src/client/service.rs +++ b/crates/nvisy-nats/src/client/service.rs @@ -116,6 +116,7 @@ impl NatsClient { ) .await .map_err(|_| Error::Timeout { + operation: "connect", timeout: connect_timeout, })? .map_err(|e| Error::Connection(Box::new(e)))?; @@ -162,6 +163,7 @@ impl NatsClient { timeout(Duration::from_secs(10), self.inner.client.flush()) .await .map_err(|_| Error::Timeout { + operation: "ping", timeout: Duration::from_secs(10), })? .map_err(|e| Error::Connection(Box::new(e)))?; @@ -184,27 +186,28 @@ impl NatsClient { // Key-value store getters impl NatsClient { - /// Get or create the KV store for a bucket. The bucket fixes the key and - /// value types, so it is the only type argument. + /// Creates a bucket from its configuration if it does not exist yet. Call + /// once per bucket at startup, so [`kv_store`](Self::kv_store) only opens. /// /// # Errors /// - /// - `Operation` if the bucket cannot be retrieved or created (a `JetStream` + /// - `Operation` if the bucket cannot be looked up or created (a `JetStream` /// request fails, or the server rejects the bucket config). #[tracing::instrument(skip(self), target = TRACING_TARGET_CLIENT)] - pub async fn kv_store(&self) -> Result> { - KvStore::new(&self.inner.jetstream).await + pub async fn ensure_kv_bucket(&self) -> Result<()> { + KvStore::::ensure(&self.inner.jetstream).await } - /// Get or create the KV store for a bucket with a custom TTL. + /// Opens the KV store for a bucket created by + /// [`ensure_kv_bucket`](Self::ensure_kv_bucket). The bucket fixes the value + /// type, so it is the only type argument. /// /// # Errors /// - /// - `Operation` if the bucket cannot be retrieved or created (a `JetStream` - /// request fails, or the server rejects the bucket config). + /// - `Operation` if the bucket does not exist or the lookup fails. #[tracing::instrument(skip(self), target = TRACING_TARGET_CLIENT)] - pub async fn kv_store_with_ttl(&self, ttl: Duration) -> Result> { - KvStore::with_ttl(&self.inner.jetstream, ttl).await + pub async fn kv_store(&self) -> Result> { + KvStore::open(&self.inner.jetstream).await } } diff --git a/crates/nvisy-nats/src/error.rs b/crates/nvisy-nats/src/error.rs index 364ffcb5..318f605e 100644 --- a/crates/nvisy-nats/src/error.rs +++ b/crates/nvisy-nats/src/error.rs @@ -1,181 +1,43 @@ -//! Error types and utilities for NATS operations. +//! Error types for NATS operations. use std::time::Duration; /// Result type for all NATS operations in this crate. -/// -/// This is a convenience type alias that defaults to using [`Error`] as the error type. -/// Most functions in this crate return this type for consistent error handling. pub type Result = std::result::Result; -/// Unified error type for NATS operations +/// An error from a NATS operation. #[derive(Debug, thiserror::Error)] pub enum Error { - /// NATS client/connection errors - #[error("NATS connection error: {0}")] + /// The server could not be reached, or the connection failed. + #[error("NATS connection failed: {0}")] Connection(#[from] async_nats::Error), - - /// Serialization errors when sending or receiving messages - #[error("Serialization error: {0}")] + /// A connect or ping did not finish in time. + #[error("NATS {operation} timed out after {timeout:?}")] + Timeout { + /// The operation that timed out. + operation: &'static str, + /// How long it was given. + timeout: Duration, + }, + /// A payload could not be serialized or deserialized. + #[error("NATS payload serialization failed: {0}")] Serialization(#[from] serde_json::Error), - - /// `JetStream` publish error - #[error("JetStream publish error: {0}")] - JetstreamPublish(async_nats::error::Error), - - /// `JetStream` message error - #[error("JetStream message error: {0}")] - JetstreamMessage(Box), - - /// Consumer error - #[error("Consumer error: {0}")] - Consumer(String), - - /// Stream error - #[error("Stream error: {0}")] - Stream(String), - - /// Acknowledgement error - #[error("Acknowledgement error: {0}")] - Ack(String), - - /// Operation timeout - #[error("Operation timed out after {timeout:?}")] - Timeout { timeout: Duration }, - - /// Message delivery failed - #[error("Message delivery failed to subject '{subject}': {reason}")] - DeliveryFailed { subject: String, reason: String }, - - /// Stream operation failed - #[error("Stream operation failed on '{stream}': {error}")] - StreamError { stream: String, error: String }, - - /// Job queue operation failed - #[error("Job queue error on '{queue}': {reason}")] - JobQueueError { queue: String, reason: String }, - - /// Consumer operation failed - #[error("Consumer '{consumer}' error: {reason}")] - ConsumerError { consumer: String, reason: String }, - - /// KV bucket not found - #[error("KV bucket '{bucket}' not found")] - KvBucketNotFound { bucket: String }, - - /// KV key not found - #[error("Key '{key}' not found in bucket '{bucket}'")] - KvKeyNotFound { bucket: String, key: String }, - - /// KV revision mismatch (optimistic concurrency failure) - #[error("Revision mismatch for key '{key}': expected {expected}, got {actual}")] - KvRevisionMismatch { - key: String, - expected: u64, - actual: u64, + /// A publish, KV, stream, consumer, or acknowledgement operation failed. + #[error("NATS {operation} failed: {details}")] + Operation { + /// The operation that failed. + operation: &'static str, + /// What went wrong. + details: String, }, - - /// Invalid configuration - #[error("Invalid configuration: {reason}")] - InvalidConfig { reason: String }, - - /// Generic operation error with context - #[error("NATS operation failed: {operation} - {details}")] - Operation { operation: String, details: String }, } impl Error { - /// Create a delivery failed error - pub fn delivery_failed(subject: impl Into, reason: impl Into) -> Self { - Self::DeliveryFailed { - subject: subject.into(), - reason: reason.into(), - } - } - - /// Create a stream error - pub fn stream_error(stream: impl Into, error: impl Into) -> Self { - Self::StreamError { - stream: stream.into(), - error: error.into(), - } - } - - /// Create a job queue error - pub fn job_queue_error(queue: impl Into, reason: impl Into) -> Self { - Self::JobQueueError { - queue: queue.into(), - reason: reason.into(), - } - } - - /// Create a consumer error - pub fn consumer_error(consumer: impl Into, reason: impl Into) -> Self { - Self::ConsumerError { - consumer: consumer.into(), - reason: reason.into(), - } - } - - /// Create an operation error with context - pub fn operation(op: impl Into, details: impl Into) -> Self { + /// Builds an [`Error::Operation`] for `operation`. + pub(crate) fn operation(operation: &'static str, details: impl Into) -> Self { Self::Operation { - operation: op.into(), + operation, details: details.into(), } } - - /// Create a KV bucket not found error - pub fn kv_bucket_not_found(bucket: impl Into) -> Self { - Self::KvBucketNotFound { - bucket: bucket.into(), - } - } - - /// Create a KV key not found error - pub fn kv_key_not_found(bucket: impl Into, key: impl Into) -> Self { - Self::KvKeyNotFound { - bucket: bucket.into(), - key: key.into(), - } - } - - /// Create a KV revision mismatch error - pub fn kv_revision_mismatch(key: impl Into, expected: u64, actual: u64) -> Self { - Self::KvRevisionMismatch { - key: key.into(), - expected, - actual, - } - } - - /// Create an invalid configuration error - pub fn invalid_config(reason: impl Into) -> Self { - Self::InvalidConfig { - reason: reason.into(), - } - } - - /// Create a timeout error with the given duration - #[must_use] - pub fn timeout(duration: Duration) -> Self { - Self::Timeout { timeout: duration } - } - - /// Get a user-friendly error message suitable for display - #[must_use] - pub fn user_message(&self) -> String { - match self { - Error::Connection(_) => { - "Connection to NATS server failed. Please check your connection.".to_string() - } - Error::Timeout { timeout } => { - format!("Operation timed out after {timeout:?}. Please try again.") - } - Error::KvKeyNotFound { key, .. } => format!("Key '{key}' not found."), - Error::Serialization(_) => "Data format error. Please check your input.".to_string(), - Error::InvalidConfig { reason } => format!("Configuration error: {reason}"), - _ => "An unexpected error occurred. Please try again.".to_string(), - } - } } diff --git a/crates/nvisy-nats/src/kv/core.rs b/crates/nvisy-nats/src/kv/core.rs index e2124dd8..c96f6c24 100644 --- a/crates/nvisy-nats/src/kv/core.rs +++ b/crates/nvisy-nats/src/kv/core.rs @@ -1,75 +1,55 @@ -//! The core KV contracts: the key and bucket traits every store is built on. +//! The core KV contracts: the entry key and the bucket trait every store is +//! built on. -use std::fmt; use std::str::FromStr; use std::time::Duration; +use derive_more::Display; use serde::Serialize; use serde::de::DeserializeOwned; -/// Marker trait for KV key types. -/// -/// Defines how keys are formatted for storage in NATS KV: a key must render to -/// and parse from the string form used as the entry's KV key. -pub trait KvKey: - fmt::Debug + fmt::Display + FromStr + Clone + Send + Sync + 'static -{ -} - /// Returned when a string is not a valid NATS KV key (empty, or containing -/// characters KV keys disallow). Shared by the opaque-token key types whose -/// value arrives untrusted (OAuth/OIDC state, step-up proofs). +/// characters KV keys disallow). #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[error("invalid KV key")] pub struct InvalidKvKey; -/// Validates that `value` is a usable NATS KV key: non-empty and composed only of -/// the alphanumeric and `-/_=.` characters KV keys allow. A URL-safe base64 token -/// (the common opaque-key case) always passes. -/// -/// The `.` is a NATS subject-token separator, so a key must have no empty -/// token: a leading, trailing, or consecutive dot (e.g. `.a`, `a.`, `a..b`, or a -/// bare `.`) is rejected, matching async-nats KV subject rules. -/// -/// Returns the value on success so a caller's [`FromStr`] is a one-liner: -/// `validate_kv_key(s).map(Self)`. +/// A KV entry key: an opaque token (an OAuth or OIDC state, a reauth proof id) +/// or a lock name. /// -/// # Errors -/// -/// - `InvalidKvKey` if `value` is empty, contains a character outside the -/// allowed alphanumeric and `-/_=.` set, or has an empty dot-separated token -/// (a leading, trailing, or consecutive dot). -pub fn validate_kv_key(value: &str) -> Result { - if value.is_empty() { - return Err(InvalidKvKey); - } - let chars_valid = value - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'/' | b'_' | b'=' | b'.')); - // Every dot-separated token must be non-empty (no leading, trailing, or - // consecutive dots), since `.` separates NATS subject tokens. - let tokens_nonempty = value.split('.').all(|token| !token.is_empty()); - if chars_valid && tokens_nonempty { - Ok(value.to_owned()) - } else { - Err(InvalidKvKey) +/// Keys often arrive untrusted (a state echoed into a callback URL, a proof in a +/// request body), so [`FromStr`] is the only constructor and enforces NATS KV key +/// syntax: non-empty, only alphanumeric and `-/_=.` characters, and no empty +/// dot-separated token. A URL-safe base64 token always passes. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[derive(Display)] +pub struct TokenKey(String); + +impl FromStr for TokenKey { + type Err = InvalidKvKey; + + fn from_str(value: &str) -> Result { + let chars_valid = value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'/' | b'_' | b'=' | b'.')); + // `.` separates NATS subject tokens, so no token may be empty (no + // leading, trailing, or consecutive dot); this also rejects "". + let tokens_nonempty = value.split('.').all(|token| !token.is_empty()); + if chars_valid && tokens_nonempty { + Ok(Self(value.to_owned())) + } else { + Err(InvalidKvKey) + } } } -/// Configuration for a NATS KV bucket, similar to `ObjectBucket` for object -/// stores. +/// A NATS KV bucket: the value it stores and its name, description, and entry +/// TTL. A store is selected by its bucket alone; every bucket is keyed by +/// [`TokenKey`]. /// -/// A bucket fixes both the key and the value it stores, so they are associated -/// types rather than free parameters on [`kv_store`]: a store is selected by its -/// bucket alone. A bucket is a pure type-level tag — all of its configuration -/// lives in associated types and consts — so it is never instantiated and carries -/// no value bounds. -/// -/// [`kv_store`]: crate::NatsClient::kv_store +/// A bucket is a pure type-level tag, never instantiated. Define one with +/// [`kv_bucket!`](crate::kv_bucket). pub trait KvBucket: 'static { - /// The key type addressing entries in this bucket. - type Key: KvKey; - /// The value type stored in this bucket. type Value: Serialize + DeserializeOwned + Send + Sync + 'static; @@ -79,39 +59,72 @@ pub trait KvBucket: 'static { /// Human-readable description for the bucket. const DESCRIPTION: &'static str; - /// Default TTL for entries in this bucket. - /// Returns `None` for buckets where entries should not expire. - const TTL: Option; + /// How long an entry lives before it expires. + const TTL: Duration; +} + +/// Defines a [`KvBucket`]: an uninhabited tag type with its value, name, +/// description, and entry TTL. +/// +/// ```ignore +/// nvisy_nats::kv_bucket! { +/// /// In-flight OAuth authorization state. +/// pub(crate) OAuthStateBucket: OAuthFlowState { +/// name: "oauth_state", +/// description: "In-flight OAuth authorization state", +/// ttl: Duration::from_mins(10), +/// } +/// } +/// ``` +#[macro_export] +macro_rules! kv_bucket { + ( + $(#[$meta:meta])* + $vis:vis $bucket:ident: $value:ty { + name: $name:literal, + description: $description:literal, + ttl: $ttl:expr $(,)? + } + ) => { + $(#[$meta])* + $vis enum $bucket {} + + impl $crate::kv::KvBucket for $bucket { + type Value = $value; + + const DESCRIPTION: &'static str = $description; + const NAME: &'static str = $name; + const TTL: ::std::time::Duration = $ttl; + } + }; } #[cfg(test)] mod tests { use super::*; + fn parse(value: &str) -> Result { + value.parse::().map(|key| key.to_string()) + } + #[test] - fn validate_kv_key_accepts_url_safe_tokens() { - // A URL-safe base64 value (with `-_=` and `/.`) is a valid KV key and - // round-trips unchanged. - assert_eq!(validate_kv_key("abc-123_XYZ=").unwrap(), "abc-123_XYZ="); - assert_eq!(validate_kv_key("a/b.c").unwrap(), "a/b.c"); + fn accepts_url_safe_tokens_unchanged() { + assert_eq!(parse("abc-123_XYZ=").unwrap(), "abc-123_XYZ="); + assert_eq!(parse("a/b.c").unwrap(), "a/b.c"); } #[test] - fn validate_kv_key_rejects_empty_and_disallowed_chars() { - assert_eq!(validate_kv_key(""), Err(InvalidKvKey)); - assert_eq!(validate_kv_key("has space"), Err(InvalidKvKey)); - assert_eq!(validate_kv_key("bad*char"), Err(InvalidKvKey)); - assert_eq!(validate_kv_key("newline\n"), Err(InvalidKvKey)); + fn rejects_empty_and_disallowed_chars() { + for value in ["", "has space", "bad*char", "newline\n"] { + assert_eq!(parse(value), Err(InvalidKvKey), "{value:?}"); + } } #[test] - fn validate_kv_key_rejects_empty_dot_tokens() { - // `.` separates NATS subject tokens, so no token may be empty. - assert_eq!(validate_kv_key("."), Err(InvalidKvKey)); - assert_eq!(validate_kv_key(".a"), Err(InvalidKvKey)); - assert_eq!(validate_kv_key("a."), Err(InvalidKvKey)); - assert_eq!(validate_kv_key("a..b"), Err(InvalidKvKey)); - // A single interior dot with non-empty tokens is still fine. - assert_eq!(validate_kv_key("a.b").unwrap(), "a.b"); + fn rejects_empty_dot_tokens() { + for value in [".", ".a", "a.", "a..b"] { + assert_eq!(parse(value), Err(InvalidKvKey), "{value:?}"); + } + assert_eq!(parse("a.b").unwrap(), "a.b"); } } diff --git a/crates/nvisy-nats/src/kv/mod.rs b/crates/nvisy-nats/src/kv/mod.rs index 10ec8d88..d6336fac 100644 --- a/crates/nvisy-nats/src/kv/mod.rs +++ b/crates/nvisy-nats/src/kv/mod.rs @@ -1,30 +1,22 @@ //! NATS Key-Value store operations. //! -//! The [`KvKey`] and [`KvBucket`] contracts back the generic [`KvStore`], which -//! is selected by a bucket alone. Concrete buckets and their keys are grouped by -//! domain (scheduler locks, OAuth state). +//! A [`KvBucket`] fixes a store's value type, name, and entry TTL, and every +//! entry is keyed by a [`TokenKey`], so a [`KvStore`] is selected by its bucket +//! alone. Buckets are defined where their value lives, with +//! [`kv_bucket!`](crate::kv_bucket), and created at startup with +//! [`NatsClient::ensure_kv_bucket`](crate::NatsClient::ensure_kv_bucket). //! //! # Example //! //! ```ignore -//! // A bucket fixes its key and value types, so the store is selected by the -//! // bucket alone. //! let store = nats_client.kv_store::().await?; //! store.put(&key, &value).await?; -//! let value = store.get_value(&key).await?; +//! let value = store.take(&key).await?; //! ``` mod core; -mod oauth_bucket; -mod oidc_bucket; -mod reauth_bucket; -mod scheduler_bucket; mod typed_store; -pub use core::{InvalidKvKey, KvBucket, KvKey, validate_kv_key}; +pub use core::{InvalidKvKey, KvBucket, TokenKey}; -pub use oauth_bucket::{OAuthStateBucket, OAuthStateKey}; -pub use oidc_bucket::{OidcStateBucket, OidcStateKey}; -pub use reauth_bucket::{ReauthProofBucket, ReauthProofKey}; -pub use scheduler_bucket::{SchedulerLockKey, SchedulerLocksBucket}; -pub use typed_store::{KvEntry, KvStore, KvValue}; +pub use typed_store::KvStore; diff --git a/crates/nvisy-nats/src/kv/oauth_bucket.rs b/crates/nvisy-nats/src/kv/oauth_bucket.rs deleted file mode 100644 index faa7eb79..00000000 --- a/crates/nvisy-nats/src/kv/oauth_bucket.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! The in-flight OAuth authorization-state bucket and its key. - -use std::marker::PhantomData; -use std::str::FromStr; -use std::time::Duration; - -use derive_more::Display; -use serde::Serialize; -use serde::de::DeserializeOwned; - -use super::core::{InvalidKvKey, KvBucket, KvKey, validate_kv_key}; - -/// The CSRF-state key for an in-flight OAuth authorization. The value is the -/// opaque state token the provider echoes back to the callback. -/// -/// The provider echoes this back into a callback URL, so it is untrusted on the -/// way in. [`FromStr`] enforces NATS KV key syntax — non-empty and only the -/// `-/_=.` and alphanumeric characters KV allows — so a malformed value is -/// rejected before it reaches the store (a URL-safe OAuth state always passes). -#[derive(Debug, Clone, PartialEq, Eq, Hash, Display)] -pub struct OAuthStateKey(String); - -impl FromStr for OAuthStateKey { - type Err = InvalidKvKey; - - fn from_str(s: &str) -> Result { - validate_kv_key(s).map(Self) - } -} - -impl KvKey for OAuthStateKey {} - -/// Bucket for in-flight OAuth authorization state (CSRF token + PKCE verifier), -/// held between starting an authorization and its callback. -/// -/// Its value is application-owned (the flow state a consuming crate defines), so -/// the bucket is generic over `V`; a consumer pins it with a type alias, e.g. -/// `type OAuthStateBucket = nvisy_nats::kv::OAuthStateBucket`. -/// Entries are short-lived: a user completes the consent screen within minutes, -/// and an abandoned flow's state should not linger. -/// -/// The bucket is a pure type-level tag, so it is uninhabited: the `V` it pins -/// lives only in the `PhantomData`, never in a value. -pub enum OAuthStateBucket { - #[doc(hidden)] - Never(PhantomData V>), -} - -impl KvBucket for OAuthStateBucket -where - V: Serialize + DeserializeOwned + Send + Sync + 'static, -{ - type Key = OAuthStateKey; - type Value = V; - - const DESCRIPTION: &'static str = "In-flight OAuth authorization state"; - const NAME: &'static str = "oauth_state"; - const TTL: Option = Some(Duration::from_mins(10)); // 10 minutes -} diff --git a/crates/nvisy-nats/src/kv/oidc_bucket.rs b/crates/nvisy-nats/src/kv/oidc_bucket.rs deleted file mode 100644 index f204372f..00000000 --- a/crates/nvisy-nats/src/kv/oidc_bucket.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! The in-flight OIDC sign-in state bucket and its key. -//! -//! Kept separate from the connection-OAuth bucket ([`OAuthStateBucket`]): the two -//! serve different purposes — signing a user in versus linking a cloud file -//! connector — and carry different state (an OIDC sign-in also holds a `nonce`), -//! so they get independent buckets rather than sharing one. -//! -//! [`OAuthStateBucket`]: super::OAuthStateBucket - -use std::marker::PhantomData; -use std::str::FromStr; -use std::time::Duration; - -use derive_more::Display; -use serde::Serialize; -use serde::de::DeserializeOwned; - -use super::core::{InvalidKvKey, KvBucket, KvKey, validate_kv_key}; - -/// The CSRF-state key for an in-flight OIDC sign-in. The value is the opaque -/// state token the provider echoes back to the callback. -/// -/// The provider echoes this into a callback URL, so it is untrusted on the way -/// in. [`FromStr`] enforces NATS KV key syntax — non-empty and only the `-/_=.` -/// and alphanumeric characters KV allows — so a malformed value is rejected -/// before it reaches the store (a URL-safe OAuth state always passes). -#[derive(Debug, Clone, PartialEq, Eq, Hash, Display)] -pub struct OidcStateKey(String); - -impl FromStr for OidcStateKey { - type Err = InvalidKvKey; - - fn from_str(s: &str) -> Result { - validate_kv_key(s).map(Self) - } -} - -impl KvKey for OidcStateKey {} - -/// Bucket for in-flight OIDC sign-in state (CSRF token, PKCE verifier, and -/// nonce), held between starting a sign-in and its callback. -/// -/// Its value is application-owned (the flow state the server defines), so the -/// bucket is generic over `V`; a consumer pins it with a type alias, e.g. -/// `type OidcStateBucket = nvisy_nats::kv::OidcStateBucket`. Entries -/// are short-lived: a user completes the provider's consent screen within -/// minutes, and an abandoned sign-in's state should not linger. -/// -/// The bucket is a pure type-level tag, so it is uninhabited: the `V` it pins -/// lives only in the `PhantomData`, never in a value. -pub enum OidcStateBucket { - #[doc(hidden)] - Never(PhantomData V>), -} - -impl KvBucket for OidcStateBucket -where - V: Serialize + DeserializeOwned + Send + Sync + 'static, -{ - type Key = OidcStateKey; - type Value = V; - - const DESCRIPTION: &'static str = "In-flight OIDC sign-in state"; - const NAME: &'static str = "oidc_state"; - const TTL: Option = Some(Duration::from_mins(10)); // 10 minutes -} diff --git a/crates/nvisy-nats/src/kv/reauth_bucket.rs b/crates/nvisy-nats/src/kv/reauth_bucket.rs deleted file mode 100644 index 9084ba66..00000000 --- a/crates/nvisy-nats/src/kv/reauth_bucket.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! The step-up re-authentication proof bucket and its key. -//! -//! A *reauth proof* is minted when an authenticated user completes a fresh OIDC -//! sign-in with a provider already linked to their account, and is then required -//! to authorize a credential-adding action (setting a first password, linking a -//! new provider). It exists so those actions need current control of a linked -//! identity, not merely a live session — a stolen session alone cannot mint a -//! durable new credential. -//! -//! The proof is short-lived and single-use: the consuming handler reads it and -//! deletes it, so it authorizes exactly one action within a small window. - -use std::marker::PhantomData; -use std::str::FromStr; -use std::time::Duration; - -use derive_more::Display; -use serde::Serialize; -use serde::de::DeserializeOwned; - -use super::core::{InvalidKvKey, KvBucket, KvKey, validate_kv_key}; - -/// The key of a step-up re-authentication proof: an opaque, unguessable id minted -/// by the reauth callback and presented by the credential-adding action. -/// -/// It reaches the server in a request body, so it is untrusted on the way in. -/// [`FromStr`] enforces NATS KV key syntax — non-empty and only the `-/_=.` and -/// alphanumeric characters KV allows — so a malformed value is rejected before it -/// reaches the store. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Display)] -pub struct ReauthProofKey(String); - -impl FromStr for ReauthProofKey { - type Err = InvalidKvKey; - - fn from_str(s: &str) -> Result { - validate_kv_key(s).map(Self) - } -} - -impl KvKey for ReauthProofKey {} - -/// Bucket for step-up re-authentication proofs. -/// -/// Its value is application-owned (what the proof attests, e.g. the account it is -/// good for), so the bucket is generic over `V`; a consumer pins it with a type -/// alias. Proofs are short-lived: a step-up action follows its re-auth within a -/// few minutes, and an unused proof should not linger as a standing capability. -/// -/// The bucket is a pure type-level tag, so it is uninhabited: the `V` it pins -/// lives only in the `PhantomData`, never in a value. -pub enum ReauthProofBucket { - #[doc(hidden)] - Never(PhantomData V>), -} - -impl KvBucket for ReauthProofBucket -where - V: Serialize + DeserializeOwned + Send + Sync + 'static, -{ - type Key = ReauthProofKey; - type Value = V; - - const DESCRIPTION: &'static str = "Step-up re-authentication proofs"; - const NAME: &'static str = "reauth_proof"; - const TTL: Option = Some(Duration::from_mins(5)); // 5 minutes -} diff --git a/crates/nvisy-nats/src/kv/scheduler_bucket.rs b/crates/nvisy-nats/src/kv/scheduler_bucket.rs deleted file mode 100644 index d675df84..00000000 --- a/crates/nvisy-nats/src/kv/scheduler_bucket.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! The scheduler leader-election lock bucket and its key. - -use std::str::FromStr; -use std::time::Duration; - -use derive_more::Display; - -use super::core::{InvalidKvKey, KvBucket, KvKey, validate_kv_key}; - -/// A string key for named locks and similar coordination entries. -/// -/// [`FromStr`] is the only constructor and enforces NATS KV key syntax (via -/// [`validate_kv_key`]), like the other key types, so a malformed lock name is -/// rejected on parse rather than at the store. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Display)] -pub struct SchedulerLockKey(String); - -impl FromStr for SchedulerLockKey { - type Err = InvalidKvKey; - - fn from_str(s: &str) -> Result { - validate_kv_key(s).map(Self) - } -} - -impl KvKey for SchedulerLockKey {} - -/// Bucket for short-lived distributed leader-election locks. -/// -/// Entries expire quickly so a crashed holder never blocks future ticks. The -/// value is a nonce; only the key's presence matters. -pub enum SchedulerLocksBucket {} - -impl KvBucket for SchedulerLocksBucket { - type Key = SchedulerLockKey; - type Value = u64; - - const DESCRIPTION: &'static str = "Short-lived scheduler leader-election locks"; - const NAME: &'static str = "scheduler_locks"; - // Comfortably above the scheduler tick interval so a period's lock outlives - // its period despite clock skew; per-period keys expire on their own. - const TTL: Option = Some(Duration::from_mins(5)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn lock_key_roundtrip() { - let key = SchedulerLockKey("scheduler.42".to_owned()); - let parsed: SchedulerLockKey = key.to_string().parse().unwrap(); - assert_eq!(key, parsed); - } -} diff --git a/crates/nvisy-nats/src/kv/typed_store.rs b/crates/nvisy-nats/src/kv/typed_store.rs index 0b89045c..ed662718 100644 --- a/crates/nvisy-nats/src/kv/typed_store.rs +++ b/crates/nvisy-nats/src/kv/typed_store.rs @@ -1,20 +1,18 @@ //! Type-safe NATS KV store wrapper. -use std::future::Future; use std::marker::PhantomData; -use std::time::{Duration, SystemTime}; +use async_nats::jetstream::kv::{CreateErrorKind, PurgeErrorKind}; use async_nats::jetstream::{self, kv}; -use futures::StreamExt; -use serde::{Deserialize, Serialize}; -use super::core::KvBucket; +use super::core::{KvBucket, TokenKey}; use crate::{Error, Result, TRACING_TARGET_KV}; /// Type-safe NATS KV store wrapper. /// -/// Generic only over the bucket `B`, which fixes the key type ([`KvBucket::Key`]) -/// and value type ([`KvBucket::Value`]) as well as the name, description, and TTL. +/// Generic only over the bucket `B`, which fixes the value type +/// ([`KvBucket::Value`]) as well as the name, description, and TTL; every entry +/// is keyed by a [`TokenKey`]. #[derive(Clone)] pub struct KvStore { store: kv::Store, @@ -22,56 +20,39 @@ pub struct KvStore { } impl KvStore { - /// Create or get a KV bucket using the bucket configuration. + /// Opens the bucket, which [`ensure`](Self::ensure) created at startup. #[tracing::instrument(skip(jetstream), target = TRACING_TARGET_KV)] - pub(crate) async fn new(jetstream: &jetstream::Context) -> Result { - Self::with_ttl(jetstream, B::TTL.unwrap_or_default()).await - } - - /// Create or get a KV bucket with custom TTL. - #[tracing::instrument(skip(jetstream), target = TRACING_TARGET_KV)] - pub(crate) async fn with_ttl(jetstream: &jetstream::Context, ttl: Duration) -> Result { - let config = kv::Config { - bucket: B::NAME.to_string(), - description: B::DESCRIPTION.to_string(), - max_age: ttl, - ..Default::default() - }; - - let store = if let Ok(store) = jetstream.get_key_value(B::NAME).await { - tracing::trace!( - target: TRACING_TARGET_KV, - bucket = %B::NAME, - "Using existing KV bucket" - ); - store - } else { - tracing::debug!( - target: TRACING_TARGET_KV, - bucket = %B::NAME, - ttl_secs = ttl.as_secs(), - "Creating new KV bucket" - ); - jetstream - .create_key_value(config) - .await - .map_err(|e| Error::operation("kv_create", e.to_string()))? - }; - + pub(crate) async fn open(jetstream: &jetstream::Context) -> Result { + let store = jetstream + .get_key_value(B::NAME) + .await + .map_err(|e| Error::operation("kv_open_bucket", format!("{}: {e}", B::NAME)))?; Ok(Self { store, _bucket: PhantomData, }) } - /// Returns the bucket name. - #[inline] - #[must_use] - pub fn bucket_name(&self) -> &'static str { - B::NAME + /// Creates the bucket from its configuration if it does not exist yet. + #[tracing::instrument(skip(jetstream), target = TRACING_TARGET_KV)] + pub(crate) async fn ensure(jetstream: &jetstream::Context) -> Result<()> { + if jetstream.get_key_value(B::NAME).await.is_ok() { + return Ok(()); + } + tracing::debug!(target: TRACING_TARGET_KV, bucket = %B::NAME, "Creating KV bucket"); + jetstream + .create_key_value(kv::Config { + bucket: B::NAME.to_owned(), + description: B::DESCRIPTION.to_owned(), + max_age: B::TTL, + ..Default::default() + }) + .await + .map_err(|e| Error::operation("kv_create_bucket", format!("{}: {e}", B::NAME)))?; + Ok(()) } - /// Put a value into the store. + /// Puts a value into the store, replacing any existing one. /// /// # Errors /// @@ -79,40 +60,21 @@ impl KvStore { /// - `Operation` if the KV put fails (e.g. the connection is down or the /// server rejects the write). #[tracing::instrument(skip(self, value), target = TRACING_TARGET_KV)] - pub async fn put(&self, key: &B::Key, value: &B::Value) -> Result { - let key_str = key.to_string(); + pub async fn put(&self, key: &TokenKey, value: &B::Value) -> Result<()> { let json = serde_json::to_vec(value)?; - let size = json.len(); - let revision = self - .store - .put(&key_str, json.into()) + self.store + .put(key.to_string(), json.into()) .await .map_err(|e| Error::operation("kv_put", e.to_string()))?; - - tracing::debug!( - target: TRACING_TARGET_KV, - key = %key_str, - revision = revision, - size_bytes = size, - "Put value to KV store" - ); - - Ok(KvEntry { - key: key_str, - revision, - size: u64::try_from(size).unwrap_or(u64::MAX), - }) + Ok(()) } - /// Atomically create a value only if the key does not already exist. + /// Atomically creates a value only if the key does not already exist. /// /// Returns `Ok(true)` if this call created the entry, `Ok(false)` if the key /// was already present. This is the put-if-absent primitive for distributed - /// locks / leader election: combined with a bucket TTL, exactly one caller - /// wins the create and the entry auto-expires if the winner dies. - /// - /// A create against an already-present key is not an error: it returns - /// `Ok(false)`. + /// locks: combined with a bucket TTL, exactly one caller wins the create and + /// the entry expires if the winner dies. /// /// # Errors /// @@ -120,341 +82,102 @@ impl KvStore { /// - `Operation` if the create fails for any reason other than the key /// already existing (e.g. network, ack, or publish failure). #[tracing::instrument(skip(self, value), target = TRACING_TARGET_KV)] - pub async fn create(&self, key: &B::Key, value: &B::Value) -> Result { - use async_nats::jetstream::kv::CreateErrorKind; - - let key_str = key.to_string(); + pub async fn create(&self, key: &TokenKey, value: &B::Value) -> Result { let json = serde_json::to_vec(value)?; - match self.store.create(&key_str, json.into()).await { + match self.store.create(key.to_string(), json.into()).await { Ok(_revision) => Ok(true), // A create against an existing key is the "lock already held" case, - // not an error. Any other failure (network, ack, publish) is a real - // infrastructure error and must be propagated rather than masqueraded - // as a lost lock. + // not an error. Any other failure is a real infrastructure error and + // must not be masqueraded as a lost lock. Err(err) if err.kind() == CreateErrorKind::AlreadyExists => Ok(false), Err(err) => Err(Error::operation("kv_create", err.to_string())), } } - /// Get a value from the store. - /// - /// # Errors - /// - /// - `Serialization` if a stored entry's bytes cannot be deserialized into - /// `B::Value`. - /// - `Operation` if the KV read fails (e.g. the connection is down). A - /// missing key is not an error; it returns `Ok(None)`. - #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn get(&self, key: &B::Key) -> Result>> { - let key_str = key.to_string(); - match self.store.entry(&key_str).await { - Ok(Some(entry)) => { - let size = entry.value.len(); - let deserialized = serde_json::from_slice(&entry.value)?; - tracing::debug!( - target: TRACING_TARGET_KV, - key = %key_str, - size_bytes = size, - revision = entry.revision, - "Retrieved value from KV store" - ); - Ok(Some(KvValue { - key: key_str, - value: deserialized, - revision: entry.revision, - size: u64::try_from(size).unwrap_or(u64::MAX), - created: entry.created.into(), - })) - } - Ok(None) => { - tracing::debug!( - target: TRACING_TARGET_KV, - key = %key_str, - "Key not found in KV store" - ); - Ok(None) - } - Err(e) => Err(Error::operation("kv_get", e.to_string())), - } - } - - /// Get a value, returning just the data. - /// - /// # Errors - /// - /// Propagates any error from [`get`](Self::get). - #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn get_value(&self, key: &B::Key) -> Result> { - Ok(self.get(key).await?.map(|kv| kv.value)) - } - - /// Atomically consume a single-use entry: read its value and delete it in a - /// way that only one caller can win. + /// Reads and removes a value in one step, for single-use entries (an OAuth + /// state, a reauth proof): of concurrent callers, exactly one gets the value. /// - /// Returns `Some(value)` to exactly one caller and `None` to everyone else, - /// even under concurrent calls for the same key. The delete is conditioned on - /// the revision the value was read at (`purge_expect_revision`), so a second - /// racer whose read saw the same revision fails the conditional purge and gets - /// `None` rather than re-consuming the entry. Use this for one-time tokens - /// (OAuth/OIDC state, step-up proofs) where a plain get-then-delete would leave - /// a replay window. + /// The entry is purged only if its revision is still the one read, so a + /// caller that loses the race sees `Ok(None)` rather than a value another + /// caller already consumed. /// /// # Errors /// - /// - `Serialization` or `Operation` propagated from the initial - /// [`get`](Self::get). - /// - `Operation` if the conditional purge fails for any reason other than a - /// revision mismatch (e.g. network, ack, or publish failure). Losing the - /// race is not an error; it returns `Ok(None)`. + /// - `Serialization` if the stored entry cannot be deserialized. + /// - `Operation` if the read or the conditional purge fails for any reason + /// other than a lost race (e.g. network, ack, or publish failure). #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn take(&self, key: &B::Key) -> Result> { - use async_nats::jetstream::kv::PurgeErrorKind; - - let Some(entry) = self.get(key).await? else { + pub async fn take(&self, key: &TokenKey) -> Result> { + let key = key.to_string(); + let entry = self + .store + .entry(&key) + .await + .map_err(|e| Error::operation("kv_get", e.to_string()))?; + // A purged or deleted key leaves a tombstone entry, which is absent. + let Some(entry) = entry.filter(|entry| entry.operation == kv::Operation::Put) else { return Ok(None); }; - let key_str = key.to_string(); + let value = serde_json::from_slice(&entry.value)?; + match self .store - .purge_expect_revision(&key_str, Some(entry.revision)) + .purge_expect_revision(&key, Some(entry.revision)) .await { - Ok(()) => Ok(Some(entry.value)), - // A concurrent caller consumed it first (the revision moved), so this - // caller loses the race and sees nothing to consume. Only a revision - // mismatch means "lost the race"; any other failure (network, ack, - // publish) is a real error and must propagate — masking it as `None` - // would silently leave a single-use token unconsumed and replayable. + Ok(()) => Ok(Some(value)), + // Only a revision mismatch means another caller consumed it first; + // any other failure must propagate, since masking it as `None` would + // leave a single-use token unconsumed and replayable. Err(err) if err.kind() == PurgeErrorKind::WrongLastRevision => { - tracing::debug!( - target: TRACING_TARGET_KV, - key = %key_str, - error = %err, - "Single-use take lost the race; entry already consumed", - ); + tracing::debug!(target: TRACING_TARGET_KV, key = %key, "Single-use take lost the race"); Ok(None) } Err(err) => Err(Error::operation("kv_take", err.to_string())), } } +} - /// Delete a key from the store. - /// - /// # Errors - /// - /// - `Operation` if the purge fails (e.g. the connection is down or the - /// server rejects the request). Purging an absent key is not an error. - #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn delete(&self, key: &B::Key) -> Result<()> { - let key_str = key.to_string(); - self.store - .purge(&key_str) - .await - .map_err(|e| Error::operation("kv_delete", e.to_string()))?; +#[cfg(all(test, feature = "test_util"))] +mod tests { + use std::time::Duration; - tracing::debug!( - target: TRACING_TARGET_KV, - key = %key_str, - "Deleted key from KV store" - ); - Ok(()) - } + use crate::kv::TokenKey; + use crate::test_util::TestNats; - /// Check if a key exists in the store. - /// - /// # Errors - /// - /// - `Operation` if the KV read fails (e.g. the connection is down). A - /// missing key is not an error; it returns `Ok(false)`. - #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn exists(&self, key: &B::Key) -> Result { - let key_str = key.to_string(); - match self.store.get(&key_str).await { - Ok(Some(_)) => Ok(true), - Ok(None) => Ok(false), - Err(e) => Err(Error::operation("kv_exists", e.to_string())), + crate::kv_bucket! { + /// A bucket for exercising the store. + TestBucket: u64 { + name: "test_bucket", + description: "Test bucket", + ttl: Duration::from_mins(1), } } - /// Touches a key to reset its TTL by re-putting the same value. - /// - /// # Errors - /// - /// - `Operation` if the key does not exist (nothing to re-put), or if the - /// underlying [`get`](Self::get) or [`put`](Self::put) fails. - /// - `Serialization` propagated from [`get`](Self::get)/[`put`](Self::put). - #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn touch(&self, key: &B::Key) -> Result { - let kv_value = self - .get(key) - .await? - .ok_or_else(|| Error::operation("kv_touch", format!("key not found: {key}")))?; - - self.put(key, &kv_value.value).await - } - - /// Get all keys in the bucket with the expected prefix. - /// - /// # Errors - /// - /// - `Operation` if opening the key stream fails (e.g. the connection is - /// down). A key that fails to read from the stream is logged and skipped; a - /// key that reads but does not parse into `B::Key` is skipped silently. - /// Neither is surfaced as an error. - #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn keys(&self) -> Result> { - let mut keys = Vec::new(); - let mut key_stream = self - .store - .keys() - .await - .map_err(|e| Error::operation("kv_keys", e.to_string()))?; - - while let Some(key_result) = key_stream.next().await { - match key_result { - Ok(key_str) => { - if let Ok(key) = key_str.parse::() { - keys.push(key); - } - } - Err(e) => { - tracing::warn!( - target: TRACING_TARGET_KV, - error = %e, - "Error reading key from bucket" - ); - } - } - } + #[tokio::test] + async fn create_is_put_if_absent_and_take_is_single_use() { + let nats = TestNats::start().await; + nats.client.ensure_kv_bucket::().await.unwrap(); + let store = nats.client.kv_store::().await.unwrap(); + let key: TokenKey = "lock.1".parse().unwrap(); - tracing::debug!( - target: TRACING_TARGET_KV, - count = keys.len(), - bucket = %B::NAME, - "Retrieved keys from bucket" + assert!( + store.create(&key, &7).await.unwrap(), + "the first create wins" ); - Ok(keys) - } - - /// Purge all keys in the bucket. - /// - /// # Errors - /// - /// - `Operation` if listing the keys via [`keys`](Self::keys) fails, or if - /// any per-key [`delete`](Self::delete) fails (deletion stops at the first - /// failure). - #[tracing::instrument(skip(self), target = TRACING_TARGET_KV)] - pub async fn purge_all(&self) -> Result<()> { - let keys = self.keys().await?; - let count = keys.len(); - for key in keys { - self.delete(&key).await?; - } - tracing::debug!( - target: TRACING_TARGET_KV, - count = count, - bucket = %B::NAME, - "Purged all keys from bucket" + assert!( + !store.create(&key, &8).await.unwrap(), + "the key is already held" ); - Ok(()) - } - /// Update a value only if the revision matches (optimistic concurrency). - /// - /// # Errors - /// - /// - `Serialization` if `value` cannot be serialized to JSON. - /// - `Operation` if the conditional update fails, including when `revision` - /// no longer matches the stored revision (the concurrency check lost). - #[tracing::instrument(skip(self, value), target = TRACING_TARGET_KV)] - pub async fn update(&self, key: &B::Key, value: &B::Value, revision: u64) -> Result { - let key_str = key.to_string(); - let json = serde_json::to_vec(value)?; - let size = json.len(); - let new_revision = self - .store - .update(&key_str, json.into(), revision) - .await - .map_err(|e| Error::operation("kv_update", e.to_string()))?; - - tracing::debug!( - target: TRACING_TARGET_KV, - key = %key_str, - old_revision = revision, - new_revision = new_revision, - size_bytes = size, - "Updated value in KV store" + assert_eq!(store.take(&key).await.unwrap(), Some(7)); + assert_eq!( + store.take(&key).await.unwrap(), + None, + "a taken value is gone" ); - Ok(KvEntry { - key: key_str, - revision: new_revision, - size: u64::try_from(size).unwrap_or(u64::MAX), - }) - } - - /// Get or compute a value using the cache-aside pattern. - /// - /// # Errors - /// - /// - `Serialization` or `Operation` propagated from the [`get_value`](Self::get_value) - /// read or, on a miss, the [`put`](Self::put) that stores the computed value. - /// - Any error returned by `compute_fn` when the key is absent. - #[tracing::instrument(skip(self, compute_fn), target = TRACING_TARGET_KV)] - pub async fn get_or_compute(&self, key: &B::Key, compute_fn: F) -> Result - where - F: FnOnce() -> Fut + Send, - Fut: Future> + Send, - B::Value: Clone, - { - if let Some(existing) = self.get_value(key).await? { - return Ok(existing); - } - - let value = compute_fn().await?; - self.put(key, &value).await?; - Ok(value) - } - - /// Get the underlying store reference. - #[must_use] - pub fn inner(&self) -> &kv::Store { - &self.store - } -} - -/// KV entry metadata. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct KvEntry { - pub key: String, - pub revision: u64, - pub size: u64, -} - -/// KV value with metadata. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct KvValue { - pub key: String, - pub value: V, - pub revision: u64, - pub size: u64, - pub created: SystemTime, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_kv_entry_creation() { - let entry = KvEntry { - key: "test_key".to_string(), - revision: 1, - size: 100, - }; - - assert_eq!(entry.key, "test_key"); - assert_eq!(entry.revision, 1); - assert_eq!(entry.size, 100); + store.put(&key, &9).await.unwrap(); + assert_eq!(store.take(&key).await.unwrap(), Some(9)); } } diff --git a/crates/nvisy-nats/src/stream/consume.rs b/crates/nvisy-nats/src/stream/consume.rs index 93bbfcb4..c974aeab 100644 --- a/crates/nvisy-nats/src/stream/consume.rs +++ b/crates/nvisy-nats/src/stream/consume.rs @@ -114,8 +114,8 @@ impl EventSubscriber { // The pull is not raced against cancellation: dropping it mid-flight // could strand a message the server already sent to its inbox until // the ack lease ran out. It ends within `PULL_TIMEOUT`. - let message = match stream.next(PULL_TIMEOUT).await { - Ok(Some(message)) => message, + let (payload, message) = match stream.next(PULL_TIMEOUT).await { + Ok(Some(pulled)) => pulled, Ok(None) => continue, Err(err) => { tracing::error!(target: TRACING_TARGET_STREAM, stream = S::NAME, error = %err, "Failed to pull a message"); @@ -123,7 +123,6 @@ impl EventSubscriber { continue; } }; - let (payload, message) = message.into_parts(); let delivered = message.info().map_or(1, |info| info.delivered.max(1)); let delivery = Delivery { attempt: delivered.cast_unsigned(), diff --git a/crates/nvisy-nats/src/stream/mod.rs b/crates/nvisy-nats/src/stream/mod.rs index 833c1c09..52ed1222 100644 --- a/crates/nvisy-nats/src/stream/mod.rs +++ b/crates/nvisy-nats/src/stream/mod.rs @@ -17,5 +17,5 @@ pub use broadcast_stream::{BroadcastStream, BroadcastTopic}; pub use consume::{Delivery, Settle}; pub use event_stream::{AssistantStream, ConnectionSyncStream, DetectionStream, WebhookStream}; pub use typed_pub::EventPublisher; -pub use typed_stream::{TypedMessage, TypedMessageStream}; +pub use typed_stream::TypedMessageStream; pub use typed_sub::EventSubscriber; diff --git a/crates/nvisy-nats/src/stream/typed_pub.rs b/crates/nvisy-nats/src/stream/typed_pub.rs index e8cef082..858de57e 100644 --- a/crates/nvisy-nats/src/stream/typed_pub.rs +++ b/crates/nvisy-nats/src/stream/typed_pub.rs @@ -69,9 +69,9 @@ impl EventPublisher { self.jetstream .publish(subject.to_owned(), payload.into()) .await - .map_err(|e| Error::delivery_failed(subject, e.to_string()))? + .map_err(|e| Error::operation("stream_publish", format!("{subject}: {e}")))? .await - .map_err(|e| Error::operation("stream_publish", e.to_string()))?; + .map_err(|e| Error::operation("stream_publish_ack", format!("{subject}: {e}")))?; tracing::debug!( target: TRACING_TARGET_STREAM, @@ -81,18 +81,4 @@ impl EventPublisher { ); Ok(()) } - - /// Returns the stream name. - #[inline] - #[must_use] - pub fn stream_name(&self) -> &'static str { - S::NAME - } - - /// Returns the subject. - #[inline] - #[must_use] - pub fn subject(&self) -> &'static str { - S::SUBJECT - } } diff --git a/crates/nvisy-nats/src/stream/typed_stream.rs b/crates/nvisy-nats/src/stream/typed_stream.rs index 275d337b..2f31cf29 100644 --- a/crates/nvisy-nats/src/stream/typed_stream.rs +++ b/crates/nvisy-nats/src/stream/typed_stream.rs @@ -1,8 +1,7 @@ //! Type-safe wrappers over a `JetStream` pull consumer's messages. //! -//! [`TypedMessageStream`] pulls a consumer's messages one at a time, decoded into -//! `T`; -//! [`TypedMessage`] pairs a decoded value with its ack handle. +//! [`TypedMessageStream`] pulls a consumer's messages one at a time, each decoded +//! into `T` and paired with the raw message that settles it. use std::marker::PhantomData; use std::time::Duration; @@ -47,7 +46,8 @@ impl TypedMessageStream where T: DeserializeOwned + Send + 'static, { - /// Pulls the next message, waiting up to `wait` for one to arrive. + /// Pulls the next message, waiting up to `wait` for one to arrive, and + /// returns its decoded payload with the raw message that settles it. /// /// The wait is the pull request's server-side expiry, so a request the /// server still holds never outlives the caller's interest in it. Every step @@ -61,7 +61,7 @@ where /// /// - `Operation` if the pull request cannot be sent or receiving the message /// fails. No message within `wait` is not an error; it returns `Ok(None)`. - pub async fn next(&self, wait: Duration) -> Result>> { + pub async fn next(&self, wait: Duration) -> Result> { let deadline = Instant::now() + wait; loop { let remaining = deadline.saturating_duration_since(Instant::now()); @@ -106,7 +106,7 @@ where subject = %message.subject, "Received typed message" ); - return Ok(Some(TypedMessage { payload, message })); + return Ok(Some((payload, message))); } Err(err) => { // A payload that cannot be deserialized will never succeed, so @@ -136,138 +136,3 @@ where } } } - -/// A typed message from the stream. -pub struct TypedMessage { - /// The deserialized payload. - pub payload: T, - /// The underlying NATS message for metadata and acknowledgment. - message: Message, -} - -impl TypedMessage { - /// Splits the message into its payload and the raw message that settles it. - pub(crate) fn into_parts(self) -> (T, Message) { - (self.payload, self.message) - } - - /// Get the message subject. - pub fn subject(&self) -> &str { - &self.message.subject - } - - /// Get the message metadata. - /// - /// # Errors - /// - /// - `Operation` if the message's reply subject cannot be parsed into - /// `JetStream` metadata (e.g. it is not a `JetStream` message). - pub fn info(&self) -> Result> { - self.message - .info() - .map_err(|e| Error::operation("message_info", e.to_string())) - } - - /// Acknowledge the message. - /// - /// # Errors - /// - /// - `Operation` if sending the ack to the server fails (e.g. the connection - /// is down). - pub async fn ack(&mut self) -> Result<()> { - self.message - .ack() - .await - .map_err(|e| Error::operation("message_ack", e.to_string())) - } - - /// Negative acknowledge the message (trigger redelivery). - /// - /// # Errors - /// - /// - `Operation` if sending the nack to the server fails (e.g. the connection - /// is down). - pub async fn nack(&mut self) -> Result<()> { - self.message - .ack_with(jetstream::AckKind::Nak(None)) - .await - .map_err(|e| Error::operation("message_nack", e.to_string())) - } - - /// Get a reference to the typed payload. - pub fn payload(&self) -> &T { - &self.payload - } - - /// Consume the message and return the payload. - pub fn into_payload(self) -> T { - self.payload - } - - /// Get message headers if available. - pub fn headers(&self) -> Option<&async_nats::HeaderMap> { - self.message.headers.as_ref() - } - - /// Get message sequence number. - /// - /// # Errors - /// - /// - `Operation` if the message metadata cannot be read (see - /// [`info`](Self::info)). - pub fn sequence(&self) -> Result { - self.info() - .map(|info| info.stream_sequence) - .map_err(|e| Error::operation("get_sequence", e.to_string())) - } - - /// Check if this message is a redelivery. - /// - /// # Errors - /// - /// - `Operation` if the message metadata cannot be read (see - /// [`info`](Self::info)). - pub fn is_redelivery(&self) -> Result { - self.info() - .map(|info| info.delivered > 1) - .map_err(|e| Error::operation("check_redelivery", e.to_string())) - } - - /// Get the number of delivery attempts. - /// - /// # Errors - /// - /// - `Operation` if the message metadata cannot be read (see - /// [`info`](Self::info)). - pub fn delivery_count(&self) -> Result { - self.info() - .map(|info| usize::try_from(info.delivered).unwrap_or(0)) - .map_err(|e| Error::operation("get_delivery_count", e.to_string())) - } - - /// Acknowledge with explicit acknowledgment kind. - /// - /// # Errors - /// - /// - `Operation` if sending the acknowledgment to the server fails (e.g. the - /// connection is down). - pub async fn ack_with(&mut self, ack_kind: jetstream::AckKind) -> Result<()> { - self.message - .ack_with(ack_kind) - .await - .map_err(|e| Error::operation("message_ack_with", e.to_string())) - } - - /// Double acknowledge (useful for at-least-once processing). - /// - /// # Errors - /// - /// - `Operation` if the ack is sent but the server's confirmation is not - /// received (e.g. the connection is down). - pub async fn double_ack(&mut self) -> Result<()> { - self.message - .double_ack() - .await - .map_err(|e| Error::operation("message_double_ack", e.to_string())) - } -} diff --git a/crates/nvisy-nats/src/stream/typed_sub.rs b/crates/nvisy-nats/src/stream/typed_sub.rs index 049b2569..50908005 100644 --- a/crates/nvisy-nats/src/stream/typed_sub.rs +++ b/crates/nvisy-nats/src/stream/typed_sub.rs @@ -83,10 +83,10 @@ impl EventSubscriber { .jetstream .get_stream(S::NAME) .await - .map_err(|e| Error::stream_error(S::NAME, format!("Failed to get stream: {e}")))?; + .map_err(|e| Error::operation("stream_get", format!("{}: {e}", S::NAME)))?; let consumer = stream.create_consumer(config).await.map_err(|e| { - Error::consumer_error(S::CONSUMER_NAME, format!("Failed to create consumer: {e}")) + Error::operation("consumer_create", format!("{}: {e}", S::CONSUMER_NAME)) })?; tracing::debug!( @@ -97,25 +97,4 @@ impl EventSubscriber { ); Ok(TypedMessageStream::new(consumer)) } - - /// Returns the stream name. - #[inline] - #[must_use] - pub fn stream_name(&self) -> &'static str { - S::NAME - } - - /// Returns the subject. - #[inline] - #[must_use] - pub fn subject(&self) -> &'static str { - S::SUBJECT - } - - /// Returns the consumer name. - #[inline] - #[must_use] - pub fn consumer_name(&self) -> &'static str { - S::CONSUMER_NAME - } } diff --git a/crates/nvisy-nats/src/test_util.rs b/crates/nvisy-nats/src/test_util.rs index 449bb50e..f9b616c0 100644 --- a/crates/nvisy-nats/src/test_util.rs +++ b/crates/nvisy-nats/src/test_util.rs @@ -5,36 +5,13 @@ //! real server without any external setup. Gated on the `test_util` feature, so //! it never ships in a default build. -use std::sync::OnceLock; - +use nvisy_core::test_util::boot_permit; use testcontainers_modules::nats::{Nats, NatsServerCmd}; use testcontainers_modules::testcontainers::runners::AsyncRunner; use testcontainers_modules::testcontainers::{ContainerAsync, ImageExt}; -use tokio::sync::Semaphore; use crate::{NatsClient, NatsConfig}; -/// Caps how many NATS containers may boot at once, across the whole test binary. -/// -/// Each test spins up its own container for isolation, but booting all of them -/// at once stresses the Docker daemon enough that some readiness probes time out -/// and the test flakes. This semaphore serializes the boot (only the boot — the -/// container runs and the test executes fully in parallel once it is up). -/// -/// The permit count defaults to 1 and can be raised with the -/// `NVISY_TEST_BOOT_CONCURRENCY` environment variable. -fn boot_semaphore() -> &'static Semaphore { - static BOOT: OnceLock = OnceLock::new(); - BOOT.get_or_init(|| { - let permits = std::env::var("NVISY_TEST_BOOT_CONCURRENCY") - .ok() - .and_then(|value| value.parse::().ok()) - .filter(|&n| n >= 1) - .unwrap_or(1); - Semaphore::new(permits) - }) -} - /// A running NATS (`JetStream`) container paired with a connected [`NatsClient`]. /// /// Keep the whole `TestNats` alive for the duration of a test: dropping it stops @@ -59,13 +36,10 @@ impl TestNats { /// Panics if the container cannot start or the client cannot connect — a test /// cannot proceed without a working NATS server. pub async fn start() -> Self { - // Serialize the boot so many tests do not overwhelm the Docker daemon at - // once; the permit is released as soon as the container is up. - let (container, port) = { - let _permit = boot_semaphore() - .acquire() - .await - .expect("boot semaphore is never closed"); + // Serialize the boot and first connect so many tests do not overwhelm the + // Docker daemon at once; the permit is released once the server is usable. + let (container, client, url) = { + let _permit = boot_permit().await; let container = Nats::default() .with_cmd(&NatsServerCmd::default().with_jetstream()) .start() @@ -75,13 +49,12 @@ impl TestNats { .get_host_port_ipv4(4222) .await .expect("failed to resolve container port"); - (container, port) + let url = format!("nats://127.0.0.1:{port}"); + let client = NatsClient::connect(NatsConfig::new(url.clone(), String::new())) + .await + .expect("failed to connect to the test NATS server"); + (container, client, url) }; - let url = format!("nats://127.0.0.1:{port}"); - - let client = NatsClient::connect(NatsConfig::new(url.clone(), String::new())) - .await - .expect("failed to connect to the test NATS server"); Self { _container: container, diff --git a/crates/nvisy-object-store/Cargo.toml b/crates/nvisy-object-store/Cargo.toml index 04d66c34..f5ae979a 100644 --- a/crates/nvisy-object-store/Cargo.toml +++ b/crates/nvisy-object-store/Cargo.toml @@ -25,13 +25,16 @@ schema = ["dep:schemars", "nvisy-core/schema"] [dependencies] # Internal crates -nvisy-core = { workspace = true } +nvisy-core = { workspace = true, features = [] } # Async runtime -tokio = { workspace = true, features = ["sync"] } +tokio = { workspace = true, features = ["sync", "io-util"] } futures = { workspace = true, features = [] } -# Cloud object storage +# OpenAPI/Documentation +schemars = { workspace = true, features = [], optional = true } + +# Object storage object_store = { workspace = true, features = ["aws", "azure", "gcp"] } # Observability @@ -40,15 +43,12 @@ tracing = { workspace = true, features = [] } # (De)serialization serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = [] } -schemars = { workspace = true, features = [], optional = true } - -# Derive macros & utilities -derive_more = { workspace = true, features = ["deref"] } # Primitive datatypes bytes = { workspace = true, features = [] } [dev-dependencies] +# Async runtime tokio = { workspace = true, features = ["macros", "rt"] } [lints] diff --git a/crates/nvisy-object-store/src/client/get_stream.rs b/crates/nvisy-object-store/src/client/get_stream.rs new file mode 100644 index 00000000..6268870d --- /dev/null +++ b/crates/nvisy-object-store/src/client/get_stream.rs @@ -0,0 +1,14 @@ +//! Result type for [`ObjectStoreClient::get_stream`]. +//! +//! [`ObjectStoreClient::get_stream`]: super::ObjectStoreClient::get_stream + +use nvisy_core::ByteStream; + +/// An object opened for streaming: its size and its body. +#[must_use] +pub struct GetStream { + /// The object's size in bytes, as reported by the store. + pub size: u64, + /// The object's bytes, streamed in chunks. + pub body: ByteStream, +} diff --git a/crates/nvisy-object-store/src/client/mod.rs b/crates/nvisy-object-store/src/client/mod.rs index 54508138..342b65bc 100644 --- a/crates/nvisy-object-store/src/client/mod.rs +++ b/crates/nvisy-object-store/src/client/mod.rs @@ -11,30 +11,34 @@ use std::sync::Arc; use bytes::Bytes; use futures::stream::BoxStream; use futures::{Stream, StreamExt, TryStreamExt}; -use nvisy_core::{ByteStream, Error, ErrorKind}; +use nvisy_core::{Error, ErrorKind}; +use object_store::buffered::BufWriter; use object_store::path::Path; use object_store::{ - Attribute, Attributes, ObjectMeta, ObjectStore, ObjectStoreExt, PutMode, PutMultipartOptions, - PutOptions, PutPayload, WriteMultipart, + Attribute, Attributes, ObjectMeta, ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload, }; +use tokio::io::AsyncWriteExt; mod get_output; +mod get_stream; mod put_output; mod service; pub use get_output::GetOutput; +pub use get_stream::GetStream; pub use put_output::PutOutput; pub use service::ExternalObjectStore; /// Maximum number of in-flight multipart part uploads, bounding memory and -/// concurrent requests during a streaming [`put_multipart`](ObjectStoreClient::put_multipart). +/// concurrent requests during a [`put_stream`](ObjectStoreClient::put_stream). const MULTIPART_MAX_CONCURRENCY: usize = 8; -/// Size each streamed chunk is split into before upload, so backpressure is -/// applied per part. Matches `WriteMultipart`'s internal 5 MiB part size (also -/// the S3 minimum part size), so no part is further subdivided past the capacity -/// check. -const MULTIPART_PART_SIZE: usize = 5 * 1024 * 1024; +/// Size of each multipart part, and the most a [`put_stream`] buffers before +/// switching from a single put to a multipart upload. At 8 MiB, S3's limit of +/// 10,000 parts allows uploads of up to about 78 GiB. +/// +/// [`put_stream`]: ObjectStoreClient::put_stream +const PART_SIZE: usize = 8 * 1024 * 1024; /// Parses a caller-supplied key into an object-store [`Path`], surfacing a /// malformed key as an error rather than silently normalizing it. @@ -58,6 +62,29 @@ fn store_error(err: object_store::Error) -> Error { Error::new(kind, err.to_string()).with_source(err) } +/// Classifies an I/O error from a [`BufWriter`], recovering the +/// [`object_store::Error`] it wraps when there is one. +fn io_store_error(err: std::io::Error) -> Error { + let message = err.to_string(); + let Some(inner) = err.into_inner() else { + return Error::runtime(message); + }; + match inner.downcast::() { + Ok(store) => store_error(*store), + Err(other) => Error::runtime(message).with_source(other), + } +} + +/// Writes `bytes` in part-sized slices, so one large chunk waits for upload +/// capacity per part rather than queueing every part at once. +async fn write_in_parts(writer: &mut BufWriter, mut bytes: Bytes) -> Result<(), Error> { + while !bytes.is_empty() { + let part = bytes.split_to(bytes.len().min(PART_SIZE)); + writer.put(part).await.map_err(store_error)?; + } + Ok(()) +} + /// Cloneable handle to any [`ObjectStore`] backend (S3, Azure, GCS, ...). /// /// All methods accept human-readable string keys and convert them to @@ -73,7 +100,7 @@ impl ObjectStoreClient { /// Verify that the backing store is reachable and the credentials work. /// - /// Performs a bounded top-level listing: it succeeds for any reachable + /// Requests a single listing page: it succeeds for any reachable /// bucket/container (including an empty one) and surfaces authorization /// failures (`PermissionDenied`/`Unauthenticated`) as errors, so callers /// can distinguish a bad connection from bad credentials. Unlike a HEAD on @@ -85,11 +112,12 @@ impl ObjectStoreClient { /// rejected (`PermissionDenied`/`Unauthenticated`). #[tracing::instrument(name = "object.verify", skip(self))] pub async fn verify_reachable(&self) -> Result<(), Error> { - self.0 - .list_with_delimiter(None) - .await - .map(|_| ()) - .map_err(store_error) + // The listing stream fetches pages lazily, so reading one entry sends one + // request; an empty bucket ends the stream without an error. + match self.0.list(None).next().await { + Some(Err(err)) => Err(store_error(err)), + Some(Ok(_)) | None => Ok(()), + } } /// List object keys under `prefix`. @@ -151,22 +179,22 @@ impl ObjectStoreClient { }) } - /// Stream the body of the object at `key` as chunks, without buffering the - /// whole object in memory. - /// - /// The read half of an object-to-elsewhere pipe (e.g. streaming an object - /// into NATS); pair with a chunk-consuming sink. + /// Opens the object at `key` as a stream of chunks, with its size, without + /// buffering the whole object in memory. /// /// # Errors /// - /// - A `Runtime` error if `key` is not a valid object-store path. + /// - An `Invalid` error if `key` is not a valid object-store path. /// - A storage error (including `NotFound`) if the object cannot be opened. /// Errors reading individual chunks are yielded by the returned stream. #[tracing::instrument(name = "object.get_stream", skip(self), fields(key = %key))] - pub async fn get_stream(&self, key: &str) -> Result { + pub async fn get_stream(&self, key: &str) -> Result { let path = parse_key(key)?; let result = self.0.get(&path).await.map_err(store_error)?; - Ok(Box::pin(result.into_stream().map_err(store_error))) + Ok(GetStream { + size: result.meta.size, + body: Box::pin(result.into_stream().map_err(store_error)), + }) } /// Upload `data` to `key`, optionally setting the content-type. @@ -285,83 +313,61 @@ impl ObjectStoreClient { self.0.get_range(&path, range).await.map_err(store_error) } - /// Upload the contents of a byte stream to `key` using a multipart upload. + /// Streams `stream` into `key`, optionally setting the content type, and + /// returns the number of bytes written. /// - /// Chunks are uploaded as they arrive, so the whole object never needs to - /// be buffered in memory. If the stream yields an error, or any part fails, - /// the multipart upload is aborted so no orphaned parts are left behind. + /// Content up to one part (8 MiB) is buffered and written with a single put; + /// anything larger streams as a multipart upload with at most 8 parts in + /// flight, so the whole object is never held in memory. If the stream yields + /// an error, or an upload fails, the upload is aborted so no partial object + /// or orphaned parts are left behind. /// /// # Errors /// - /// - A `Runtime` error if `key` is not a valid object-store path. + /// - An `Invalid` error if `key` is not a valid object-store path. /// - The stream's own error if it yields one (the upload is aborted first). - /// - A storage error if starting, uploading a part, or completing the - /// multipart upload fails. - #[tracing::instrument(name = "object.put_multipart", skip(self, stream), fields(key = %key))] - pub async fn put_multipart( + /// - A storage error if a put, a part, or completing the upload fails. + #[tracing::instrument(name = "object.put_stream", skip(self, stream), fields(key = %key))] + pub async fn put_stream( &self, key: &str, content_type: Option<&str>, mut stream: S, - ) -> Result + ) -> Result where S: Stream> + Unpin + Send, { let path = parse_key(key)?; - let opts = match content_type { - Some(ct) => { - let mut attributes = Attributes::new(); - attributes.insert(Attribute::ContentType, ct.to_string().into()); - PutMultipartOptions { - attributes, - ..Default::default() - } - } - None => PutMultipartOptions::default(), - }; - - let upload = self - .0 - .put_multipart_opts(&path, opts) - .await - .map_err(store_error)?; - let mut writer = WriteMultipart::new(upload); + let mut attributes = Attributes::new(); + if let Some(content_type) = content_type { + attributes.insert(Attribute::ContentType, content_type.to_owned().into()); + } + let mut writer = BufWriter::with_capacity(Arc::clone(&self.0), path, PART_SIZE) + .with_max_concurrency(MULTIPART_MAX_CONCURRENCY) + .with_attributes(attributes); + let mut size: u64 = 0; while let Some(chunk) = stream.next().await { - let mut bytes = match chunk { - Ok(bytes) => bytes, - Err(e) => { - // Abort so the backend does not retain orphaned parts. - let _ = writer.abort().await; - return Err(e); + let written = match chunk { + Ok(bytes) => { + size += u64::try_from(bytes.len()).unwrap_or(u64::MAX); + write_in_parts(&mut writer, bytes).await } + Err(err) => Err(err), }; - - // A single stream item can be arbitrarily large, and `put` splits it - // into part-sized uploads internally. Split it here and wait for - // capacity before *each* part, so one big item cannot exceed the - // in-flight bound (a single check per item could not). - while !bytes.is_empty() { - let part = bytes.split_to(bytes.len().min(MULTIPART_PART_SIZE)); - if let Err(e) = writer.wait_for_capacity(MULTIPART_MAX_CONCURRENCY).await { - let _ = writer.abort().await; - return Err(store_error(e)); + if let Err(err) = written { + // Abort so the backend keeps no partial upload. + if let Err(abort) = writer.abort().await { + tracing::warn!(key = %key, error = %abort, "Failed to abort an upload"); } - writer.put(part); + return Err(err); } } - // Drain all in-flight parts first, so a part error here aborts the upload - // rather than leaking parts. `finish` also waits internally, but consumes - // the writer, leaving nothing to abort if that wait fails; doing it here - // on `&mut writer` keeps the writer available to abort. `finish`'s own - // `complete` step already aborts on failure. - if let Err(e) = writer.wait_for_capacity(0).await { - let _ = writer.abort().await; - return Err(store_error(e)); - } - - writer.finish().await.map(Into::into).map_err(store_error) + // Completes the single put or the multipart upload; a failed complete + // aborts the multipart upload itself. + writer.shutdown().await.map_err(io_store_error)?; + Ok(size) } } @@ -396,26 +402,27 @@ mod tests { } #[tokio::test] - async fn put_multipart_single_item_larger_than_concurrency() { - // One stream item bigger than MAX_CONCURRENCY parts: the per-part - // capacity wait must split and bound it rather than spawn every part at - // once. Correctness check: the reassembled object matches the input. + async fn put_stream_splits_one_large_chunk_into_parts() { + // One stream item spanning more parts than may be in flight: it is + // written a part at a time, so the upload stays bounded. The written + // size and the reassembled object must both match the input. let client = test_client(); - let size = MULTIPART_PART_SIZE * (MULTIPART_MAX_CONCURRENCY + 3) + 123; + let size = PART_SIZE * (MULTIPART_MAX_CONCURRENCY + 3) + 123; let data = Bytes::from(vec![7u8; size]); let stream = futures::stream::once({ let data = data.clone(); async move { Ok(data) } }); - client - .put_multipart( + let written = client + .put_stream( "big.bin", Some("application/octet-stream"), Box::pin(stream), ) .await .unwrap(); + assert_eq!(written, u64::try_from(size).unwrap()); let result = client.get("big.bin").await.unwrap(); assert_eq!(result.data.len(), size); @@ -431,7 +438,7 @@ mod tests { } #[tokio::test] - async fn put_multipart_streams_chunks() { + async fn put_stream_writes_every_chunk() { let client = test_client(); let chunks = vec![ Ok(Bytes::from("hello ")), @@ -439,7 +446,7 @@ mod tests { Ok(Bytes::from("world")), ]; client - .put_multipart("mp.txt", Some("text/plain"), futures::stream::iter(chunks)) + .put_stream("mp.txt", Some("text/plain"), futures::stream::iter(chunks)) .await .unwrap(); @@ -449,14 +456,14 @@ mod tests { } #[tokio::test] - async fn put_multipart_aborts_on_stream_error() { + async fn put_stream_aborts_on_stream_error() { let client = test_client(); let chunks = vec![ Ok(Bytes::from("partial")), Err(Error::runtime("stream broke")), ]; let err = client - .put_multipart("aborted.txt", None, futures::stream::iter(chunks)) + .put_stream("aborted.txt", None, futures::stream::iter(chunks)) .await .unwrap_err(); assert_eq!(err.to_string(), "stream broke"); diff --git a/crates/nvisy-object-store/src/provider/azure.rs b/crates/nvisy-object-store/src/provider/azure.rs index c3769572..c1ee90f6 100644 --- a/crates/nvisy-object-store/src/provider/azure.rs +++ b/crates/nvisy-object-store/src/provider/azure.rs @@ -1,6 +1,5 @@ //! Azure Blob Storage provider using [`object_store::azure::MicrosoftAzureBuilder`]. -use derive_more::Deref; use nvisy_core::net::EndpointPolicy; use nvisy_core::{Error, Secret}; use object_store::azure::{MicrosoftAzureBuilder, split_sas}; @@ -8,7 +7,6 @@ use object_store::azure::{MicrosoftAzureBuilder, split_sas}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use super::Client; use crate::client::ObjectStoreClient; /// Typed credentials for Azure Blob Storage. @@ -54,33 +52,26 @@ pub enum AzureAuth { }, } -/// Azure Blob Storage-backed object storage client. -#[derive(Deref)] -pub struct AzureProvider(ObjectStoreClient); - -impl Client for AzureProvider { - type Credentials = AzureCredentials; - - const ID: &str = "azure"; - - async fn connect(creds: &Self::Credentials, policy: EndpointPolicy) -> Result { +impl AzureCredentials { + /// Connects to the store, validating any custom endpoint under `policy`. + pub(super) async fn connect(&self, policy: EndpointPolicy) -> Result { let mut builder = MicrosoftAzureBuilder::new() - .with_container_name(&creds.container) - .with_account(&creds.account_name); + .with_container_name(&self.container) + .with_account(&self.account_name); - builder = match &creds.auth { + builder = match &self.auth { AzureAuth::AccessKey { access_key } => builder.with_access_key(access_key.expose()), AzureAuth::SasToken { sas_token } => { // `split_sas` percent-decodes and validates the token, handling // the edge cases (e.g. `=` inside a value) a naive split would // corrupt. let pairs = split_sas(sas_token.expose()) - .map_err(|e| Error::invalid(format!("{}: {e}", Self::ID)))?; + .map_err(|e| Error::invalid(format!("{}: {e}", "azure")))?; builder.with_sas_authorization(pairs) } }; - if let Some(endpoint) = &creds.endpoint { + if let Some(endpoint) = &self.endpoint { // Validate the custom endpoint under the deployment policy; enable // plaintext HTTP only for a local emulator (Azurite). let allow_http = super::endpoint_allow_http(policy, endpoint).await?; @@ -92,8 +83,8 @@ impl Client for AzureProvider { let store = builder .build() - .map_err(|e| Error::invalid(format!("{}: {e}", Self::ID)))?; + .map_err(|e| Error::invalid(format!("{}: {e}", "azure")))?; - Ok(Self(ObjectStoreClient::new(store))) + Ok(ObjectStoreClient::new(store)) } } diff --git a/crates/nvisy-object-store/src/provider/gcs.rs b/crates/nvisy-object-store/src/provider/gcs.rs index 02e13224..2f41ac34 100644 --- a/crates/nvisy-object-store/src/provider/gcs.rs +++ b/crates/nvisy-object-store/src/provider/gcs.rs @@ -1,6 +1,5 @@ //! Google Cloud Storage provider using [`object_store::gcp::GoogleCloudStorageBuilder`]. -use derive_more::Deref; use nvisy_core::net::EndpointPolicy; use nvisy_core::{Error, Secret}; use object_store::ClientOptions; @@ -9,7 +8,6 @@ use object_store::gcp::GoogleCloudStorageBuilder; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use super::Client; use crate::client::ObjectStoreClient; /// Typed credentials for Google Cloud Storage. @@ -32,21 +30,14 @@ pub struct GcsCredentials { pub endpoint: Option, } -/// Google Cloud Storage-backed object storage client. -#[derive(Deref)] -pub struct GcsProvider(ObjectStoreClient); - -impl Client for GcsProvider { - type Credentials = GcsCredentials; - - const ID: &str = "gcs"; - - async fn connect(creds: &Self::Credentials, policy: EndpointPolicy) -> Result { +impl GcsCredentials { + /// Connects to the store, validating any custom endpoint under `policy`. + pub(super) async fn connect(&self, policy: EndpointPolicy) -> Result { let mut builder = GoogleCloudStorageBuilder::new() - .with_bucket_name(&creds.bucket) - .with_service_account_key(creds.service_account_key.expose()); + .with_bucket_name(&self.bucket) + .with_service_account_key(self.service_account_key.expose()); - if let Some(endpoint) = &creds.endpoint { + if let Some(endpoint) = &self.endpoint { // Validate the custom endpoint: only http(s), and plaintext http only // for a local emulator (e.g. a fake-gcs server). let allow_http = super::endpoint_allow_http(policy, endpoint).await?; @@ -63,8 +54,8 @@ impl Client for GcsProvider { let store = builder .build() - .map_err(|e| Error::invalid(format!("{}: {e}", Self::ID)))?; + .map_err(|e| Error::invalid(format!("{}: {e}", "gcs")))?; - Ok(Self(ObjectStoreClient::new(store))) + Ok(ObjectStoreClient::new(store)) } } diff --git a/crates/nvisy-object-store/src/provider/mod.rs b/crates/nvisy-object-store/src/provider/mod.rs index 6a184947..1f35001f 100644 --- a/crates/nvisy-object-store/src/provider/mod.rs +++ b/crates/nvisy-object-store/src/provider/mod.rs @@ -1,17 +1,15 @@ -//! Client trait and object storage providers. +//! Object storage providers: the typed connection config and its credentials. mod azure; mod gcs; mod s3; -use std::ops::Deref; - -pub use azure::{AzureAuth, AzureCredentials, AzureProvider}; -pub use gcs::{GcsCredentials, GcsProvider}; +pub use azure::{AzureAuth, AzureCredentials}; +pub use gcs::GcsCredentials; use nvisy_core::Error; use nvisy_core::net::EndpointPolicy; use object_store::prefix::PrefixStore; -pub use s3::{S3Credentials, S3Provider}; +pub use s3::S3Credentials; #[cfg(feature = "schema")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -68,9 +66,9 @@ impl StorageConfig { #[must_use] pub fn provider_id(&self) -> &'static str { match self { - Self::S3 { .. } => S3Provider::ID, - Self::Azure { .. } => AzureProvider::ID, - Self::Gcs { .. } => GcsProvider::ID, + Self::S3 { .. } => "s3", + Self::Azure { .. } => "azure", + Self::Gcs { .. } => "gcs", } } @@ -114,28 +112,6 @@ fn with_root_path(client: ObjectStoreClient, root_path: Option<&str>) -> ObjectS } } -/// Authenticated connection to an object storage backend. -/// -/// Implementations are newtype wrappers around [`ObjectStoreClient`] that -/// handle credential validation and client construction for a specific -/// provider (e.g. S3, Azure, GCS). -pub trait Client: Deref + Send + Sync + 'static { - /// Strongly-typed credentials for this provider. - type Credentials: Send; - - /// Unique identifier (e.g. `s3`, `azure`). - const ID: &str; - - /// Create a connected client from credentials, validating any custom - /// endpoint under `policy`. - fn connect( - creds: &Self::Credentials, - policy: EndpointPolicy, - ) -> impl Future> + Send - where - Self: Sized; -} - /// Connects to an object store from a typed [`StorageConfig`], returning the /// shared [`ObjectStoreClient`] regardless of which provider backs it. /// @@ -152,27 +128,13 @@ pub async fn connect( policy: EndpointPolicy, ) -> Result { let client = match config { - StorageConfig::S3 { credentials, .. } => { - connect_client::(credentials, policy).await - } - StorageConfig::Azure { credentials, .. } => { - connect_client::(credentials, policy).await - } - StorageConfig::Gcs { credentials, .. } => { - connect_client::(credentials, policy).await - } + StorageConfig::S3 { credentials, .. } => credentials.connect(policy).await, + StorageConfig::Azure { credentials, .. } => credentials.connect(policy).await, + StorageConfig::Gcs { credentials, .. } => credentials.connect(policy).await, }?; Ok(with_root_path(client, config.root_path())) } -/// Connects a specific provider and unwraps it to the shared client type. -async fn connect_client( - credentials: &C::Credentials, - policy: EndpointPolicy, -) -> Result { - Ok((*C::connect(credentials, policy).await?).clone()) -} - #[cfg(test)] mod tests { use serde_json::json; diff --git a/crates/nvisy-object-store/src/provider/s3.rs b/crates/nvisy-object-store/src/provider/s3.rs index a9d274e1..c6a46655 100644 --- a/crates/nvisy-object-store/src/provider/s3.rs +++ b/crates/nvisy-object-store/src/provider/s3.rs @@ -2,7 +2,6 @@ //! //! Works with AWS S3, `MinIO`, and any S3-compatible service. -use derive_more::Deref; use nvisy_core::net::EndpointPolicy; use nvisy_core::{Error, Secret}; use object_store::aws::AmazonS3Builder; @@ -10,7 +9,6 @@ use object_store::aws::AmazonS3Builder; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use super::Client; use crate::client::ObjectStoreClient; /// Typed credentials for S3-compatible provider. @@ -45,23 +43,16 @@ fn default_region() -> String { "us-east-1".to_string() } -/// S3-backed object storage client. -#[derive(Deref)] -pub struct S3Provider(ObjectStoreClient); - -impl Client for S3Provider { - type Credentials = S3Credentials; - - const ID: &str = "s3"; - - async fn connect(creds: &Self::Credentials, policy: EndpointPolicy) -> Result { +impl S3Credentials { + /// Connects to the store, validating any custom endpoint under `policy`. + pub(super) async fn connect(&self, policy: EndpointPolicy) -> Result { let mut builder = AmazonS3Builder::new() - .with_bucket_name(&creds.bucket) - .with_region(&creds.region) - .with_access_key_id(creds.access_key_id.expose()) - .with_secret_access_key(creds.secret_access_key.expose()); + .with_bucket_name(&self.bucket) + .with_region(&self.region) + .with_access_key_id(self.access_key_id.expose()) + .with_secret_access_key(self.secret_access_key.expose()); - if let Some(endpoint) = &creds.endpoint { + if let Some(endpoint) = &self.endpoint { // Validate the custom endpoint and enable plaintext HTTP only for a // local emulator (e.g. MinIO), never for a remote host. let allow_http = super::endpoint_allow_http(policy, endpoint).await?; @@ -71,14 +62,14 @@ impl Client for S3Provider { } } - if let Some(token) = &creds.session_token { + if let Some(token) = &self.session_token { builder = builder.with_token(token.expose()); } let store = builder .build() - .map_err(|e| Error::invalid(format!("{}: {e}", Self::ID)))?; + .map_err(|e| Error::invalid(format!("{}: {e}", "s3")))?; - Ok(Self(ObjectStoreClient::new(store))) + Ok(ObjectStoreClient::new(store)) } } diff --git a/crates/nvisy-postgres/Cargo.toml b/crates/nvisy-postgres/Cargo.toml index 69ff7d3f..ce25f10e 100644 --- a/crates/nvisy-postgres/Cargo.toml +++ b/crates/nvisy-postgres/Cargo.toml @@ -39,16 +39,22 @@ cli = ["dep:clap", "nvisy-core/cli"] # constructors (e.g. `Handle::test`), so downstream crates can reuse the same # harness in their own integration tests. Off by default; pulls in the container # runtime and the Tokio features the fixture needs. -test_util = ["dep:testcontainers-modules", "tokio/macros", "tokio/rt-multi-thread"] +test_util = ["dep:testcontainers-modules", "nvisy-core/test_util", "tokio/macros", "tokio/rt-multi-thread"] [dependencies] # Internal crates -nvisy-core = { workspace = true } +nvisy-core = { workspace = true, features = [] } + +# CLI +clap = { workspace = true, features = ["derive", "env"], optional = true } # Async runtime tokio = { workspace = true, features = [] } futures = { workspace = true, features = [] } -async-trait = { workspace = true } +async-trait = { workspace = true, features = [] } + +# OpenAPI/Documentation +schemars = { workspace = true, features = [], optional = true } # Encoding base64 = { workspace = true, features = [] } @@ -60,15 +66,17 @@ diesel-async = { workspace = true, features = ["postgres", "pool", "deadpool", " diesel-derive-enum = { workspace = true, features = ["postgres"] } deadpool = { workspace = true, features = ["rt_tokio_1"] } pgtrgm = { workspace = true, features = ["diesel"] } +jiff-diesel = { workspace = true, features = ["postgres"] } # Observability tracing = { workspace = true, features = [] } +# Testing utilities +testcontainers-modules = { workspace = true, features = ["postgres"], optional = true } + # (De)serialization serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = [] } -schemars = { workspace = true, features = [], optional = true } -clap = { workspace = true, features = ["derive", "env"], optional = true } # Text processing slug = { workspace = true, features = [] } @@ -80,13 +88,11 @@ derive_more = { workspace = true, features = ["deref", "deref_mut", "display", " # Primitive datatypes jiff = { workspace = true, features = ["serde"] } -jiff-diesel = { workspace = true, features = ["postgres"] } uuid = { workspace = true, features = ["serde", "v4", "v7"] } -ipnet = { workspace = true, features = ["serde"] } bigdecimal = { workspace = true, features = ["serde"] } -# Testing utilities -testcontainers-modules = { workspace = true, features = ["postgres"], optional = true } +# Domain datatypes & data structures +ipnet = { workspace = true, features = ["serde"] } [dev-dependencies] # Internal crates diff --git a/crates/nvisy-postgres/src/test_util.rs b/crates/nvisy-postgres/src/test_util.rs index c1ede0bc..9b8065fb 100644 --- a/crates/nvisy-postgres/src/test_util.rs +++ b/crates/nvisy-postgres/src/test_util.rs @@ -5,12 +5,10 @@ //! can be exercised against a real database without any external setup. Gated on //! the `test_util` feature, so it never ships in a default build. -use std::sync::OnceLock; - +use nvisy_core::test_util::boot_permit; use testcontainers_modules::postgres::Postgres; use testcontainers_modules::testcontainers::runners::AsyncRunner; use testcontainers_modules::testcontainers::{ContainerAsync, ImageExt}; -use tokio::sync::Semaphore; use uuid::Uuid; use crate::client::PgClientMigrationExt; @@ -25,30 +23,6 @@ use crate::query::{ use crate::types::WorkspaceRole; use crate::{PgClient, PgConfig}; -/// Caps how many Postgres containers may boot at once, across the whole test -/// binary. -/// -/// Each test spins up its own container for isolation, but the readiness probe -/// inside `start()` is startup-sensitive: booting all of them at once stresses -/// the Docker daemon enough that some probes time out and the test flakes. This -/// semaphore serializes the boot (only the boot — the container runs and the test -/// executes fully in parallel once it is up), so there is never a boot storm. -/// -/// The permit count defaults to 1 (fully serialized boots, deterministic on any -/// runner) and can be raised with the `NVISY_TEST_BOOT_CONCURRENCY` environment -/// variable to trade determinism for faster startup on a capable machine. -fn boot_semaphore() -> &'static Semaphore { - static BOOT: OnceLock = OnceLock::new(); - BOOT.get_or_init(|| { - let permits = std::env::var("NVISY_TEST_BOOT_CONCURRENCY") - .ok() - .and_then(|value| value.parse::().ok()) - .filter(|&n| n >= 1) - .unwrap_or(1); - Semaphore::new(permits) - }) -} - /// A running Postgres container paired with a migrated [`PgClient`]. /// /// Keep the whole `TestDatabase` alive for the duration of a test: dropping it @@ -73,14 +47,11 @@ impl TestDatabase { /// Panics if the container cannot start, the client cannot connect, or the /// migrations fail — a test cannot proceed without a working database. pub async fn start() -> Self { - // Serialize the boot (and the readiness probe inside `start()`) so many - // tests do not overwhelm the Docker daemon at once; the permit is released - // as soon as the container is up, so tests still run in parallel from there. - let (container, port) = { - let _permit = boot_semaphore() - .acquire() - .await - .expect("boot semaphore is never closed"); + // Serialize the boot, readiness probe, and first connect so many tests do + // not overwhelm the Docker daemon at once; the permit is released once the + // database is usable, so tests still run in parallel from there. + let (container, client) = { + let _permit = boot_permit().await; let container = Postgres::default() .with_tag("18-alpine") .start() @@ -90,13 +61,12 @@ impl TestDatabase { .get_host_port_ipv4(5432) .await .expect("failed to resolve container port"); - (container, port) + let url = format!("postgresql://postgres:postgres@127.0.0.1:{port}/postgres"); + let client = PgClient::new_with_test(PgConfig::new(url)) + .await + .expect("failed to connect to the test database"); + (container, client) }; - let url = format!("postgresql://postgres:postgres@127.0.0.1:{port}/postgres"); - - let client = PgClient::new_with_test(PgConfig::new(url)) - .await - .expect("failed to connect to the test database"); client .run_pending_migrations() .await diff --git a/crates/nvisy-postgres/src/types/enums/mod.rs b/crates/nvisy-postgres/src/types/enums/mod.rs index ae4e4b93..c9510048 100644 --- a/crates/nvisy-postgres/src/types/enums/mod.rs +++ b/crates/nvisy-postgres/src/types/enums/mod.rs @@ -84,15 +84,8 @@ macro_rules! db_enum { $(#[doc = $enum_doc])* #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] #[cfg_attr(feature = "schema", derive(::schemars::JsonSchema))] - #[derive( - ::serde::Serialize, - ::serde::Deserialize, - ::diesel_derive_enum::DbEnum, - ::strum::Display, - ::strum::EnumIter, - ::strum::EnumString, - ::strum::IntoStaticStr, - )] + #[derive(::serde::Serialize, ::serde::Deserialize, ::diesel_derive_enum::DbEnum)] + #[derive(::strum::Display, ::strum::EnumIter, ::strum::EnumString, ::strum::IntoStaticStr)] #[ExistingTypePath = $sql_ty] $vis enum $name { $( diff --git a/crates/nvisy-s3/Cargo.toml b/crates/nvisy-s3/Cargo.toml index e945a2e5..7929ef82 100644 --- a/crates/nvisy-s3/Cargo.toml +++ b/crates/nvisy-s3/Cargo.toml @@ -20,55 +20,55 @@ documentation = { workspace = true } all-features = true rustdoc-args = ["--cfg", "docsrs"] -[package.metadata.cargo-machete] -# `aws-smithy-types` has no direct import: it is declared only to turn on its -# `byte-stream-poll-next` feature, which is what makes `ByteStream::into_async_read` -# available on the get path. cargo-machete cannot see feature-only deps. -ignored = ["aws-smithy-types"] - [features] # Exposes the config type's `clap::Args` derive for the CLI binary. cli = ["dep:clap"] -# Test support: an ephemeral MinIO container + a connected store with its bucket -# created, for this crate's tests and downstream crates that need a real S3. -test_util = ["dep:testcontainers-modules", "tokio/sync"] +# Test support: an ephemeral RustFS container + a store with its bucket created, +# for this crate's tests and downstream crates that need a real S3. +test_util = ["dep:testcontainers-modules", "dep:reqwest", "nvisy-core/test_util"] [dependencies] # Internal crates -nvisy-core = { workspace = true } +nvisy-core = { workspace = true, features = [] } +nvisy-object-store = { workspace = true, features = [] } + +# CLI +clap = { workspace = true, features = ["derive", "env"], optional = true } -# Async runtime & IO +# Async runtime tokio = { workspace = true, features = ["io-util"] } -async-trait = { workspace = true } +tokio-util = { workspace = true, features = ["io"] } +futures = { workspace = true, features = [] } +async-trait = { workspace = true, features = [] } -# S3-compatible blob storage (AWS S3, RustFS, MinIO, R2) -aws-config = { workspace = true } -aws-sdk-s3 = { workspace = true } -aws-smithy-types = { workspace = true, features = ["byte-stream-poll-next"] } -aws-credential-types = { workspace = true, features = ["hardcoded-credentials"] } +# HTTP client & middleware +reqwest = { workspace = true, features = [], optional = true } -# CLI configuration (optional; enabled by the server binary) -clap = { workspace = true, features = ["derive", "env"], optional = true } +# Encoding +base64 = { workspace = true, features = [] } -# Test-only: an ephemeral S3-compatible container via testcontainers' generic -# image, with HTTP readiness probing (gated on the `test_util` feature). -testcontainers-modules = { workspace = true, features = ["http_wait"], optional = true } +# Object storage +object_store = { workspace = true, features = ["aws"] } # Observability tracing = { workspace = true, features = [] } -# Errors -thiserror = { workspace = true, features = [] } +# Testing utilities +testcontainers-modules = { workspace = true, features = ["http_wait"], optional = true } # Derive macros & utilities +thiserror = { workspace = true, features = [] } strum = { workspace = true, features = ["derive"] } # Primitive datatypes uuid = { workspace = true, features = ["v7"] } -base64 = { workspace = true, features = [] } + +# Domain datatypes & data structures +url = { workspace = true, features = [] } [dev-dependencies] +# Async runtime tokio = { workspace = true, features = ["macros", "rt"] } [lints] diff --git a/crates/nvisy-s3/src/client/config.rs b/crates/nvisy-s3/src/client/config.rs index 709a2ff6..36ca660a 100644 --- a/crates/nvisy-s3/src/client/config.rs +++ b/crates/nvisy-s3/src/client/config.rs @@ -6,8 +6,9 @@ use nvisy_core::Secret; /// /// A single S3 bucket holds every logical store (files, audits, avatars); /// [`Bucket`] prefixes keep them apart within it, so a deployment provisions one -/// bucket rather than one per kind. `endpoint` selects the backend: unset targets -/// AWS S3, set targets an S3-compatible server (`RustFS`, `MinIO`, R2, …). +/// bucket rather than one per kind. `endpoint` selects the backend: set targets +/// an S3-compatible server (`RustFS`, `MinIO`, R2, …); unset targets AWS S3 +/// unless the environment credential chain supplies an endpoint. /// /// [`Bucket`]: crate::Bucket #[derive(Debug, Clone)] @@ -27,7 +28,8 @@ pub struct S3Config { pub region: String, /// Endpoint URL of an S3-compatible server (e.g. `http://localhost:9000`). - /// Unset targets AWS S3 itself. + /// Unset, the environment credential chain's `AWS_ENDPOINT_URL_S3` or + /// `AWS_ENDPOINT` applies, and without either the client targets AWS S3. #[cfg_attr(feature = "cli", arg(long, env = "S3_ENDPOINT"))] pub endpoint: Option, @@ -45,8 +47,9 @@ pub struct S3Config { )] pub force_path_style: bool, - /// Access key id. When unset (alongside `secret_access_key`), the SDK's - /// default credential chain is used (environment, profile, IAM role, …). + /// Access key id. When unset (alongside `secret_access_key`), credentials + /// come from the environment chain (`AWS_*` variables, web identity, ECS + /// container credentials, instance metadata); `~/.aws` profiles are not read. #[cfg_attr(feature = "cli", arg(long, env = "S3_ACCESS_KEY_ID"))] pub access_key_id: Option>, diff --git a/crates/nvisy-s3/src/client/connect.rs b/crates/nvisy-s3/src/client/connect.rs index 0973e1dc..22dfe1f7 100644 --- a/crates/nvisy-s3/src/client/connect.rs +++ b/crates/nvisy-s3/src/client/connect.rs @@ -1,8 +1,11 @@ -//! Building a connected [`BlobStore`] from configuration. +//! Building a [`BlobStore`] from configuration. -use aws_config::BehaviorVersion; -use aws_credential_types::Credentials; -use aws_sdk_s3::config::Region; +use std::time::Duration; + +use nvisy_object_store::client::ObjectStoreClient; +use object_store::ClientOptions; +use object_store::aws::{AmazonS3Builder, AmazonS3ConfigKey}; +use url::Url; use super::{BlobStore, S3Config}; use crate::error::{Error, Result}; @@ -10,68 +13,174 @@ use crate::error::{Error, Result}; /// Tracing target for connection setup. const TRACING_TARGET: &str = "nvisy_s3::connect"; -/// Static-credentials provider name used when the config supplies a key pair. -const STATIC_PROVIDER: &str = "nvisy-s3-static"; +/// How long a response body read may wait for the next bytes before failing. +const READ_TIMEOUT: Duration = Duration::from_secs(30); impl BlobStore { - /// Connects a [`BlobStore`] to the S3-compatible service described by `config`. + /// Builds a [`BlobStore`] for the S3-compatible service described by + /// `config`. /// - /// When both `access_key_id` and `secret_access_key` are set, static - /// credentials are used; otherwise the SDK's default credential chain applies - /// (environment, profile, container/instance role). `endpoint` targets an - /// S3-compatible server; unset targets AWS S3. + /// When both `access_key_id` and `secret_access_key` are set, those static + /// credentials are used. Otherwise credentials come from the environment + /// chain: the `AWS_*` variables, then web identity (EKS), ECS container + /// credentials, and EC2 instance metadata; shared profile files (`~/.aws`) + /// are not read. `endpoint` targets an S3-compatible server, falling back to + /// `AWS_ENDPOINT_URL_S3` or `AWS_ENDPOINT` from the environment chain, with + /// plaintext HTTP allowed only when it is an `http://` URL; with none of + /// these set, the client targets AWS S3. /// - /// This method does not contact the service — it only builds the client. Call - /// [`ping`](Self::ping) to verify endpoint reachability, credentials, and - /// bucket access. + /// This does not contact the service. Call [`ping`](Self::ping) to verify + /// endpoint reachability, credentials, and bucket access. /// /// # Errors /// /// `Config` if the credentials are incomplete (only one of the access key id - /// and secret access key is set). + /// and secret access key is set) or the client cannot be built. #[tracing::instrument(name = "s3.connect", skip_all, fields(bucket = %config.bucket))] - pub async fn connect(config: &S3Config) -> Result { + pub fn connect(config: &S3Config) -> Result { tracing::debug!( target: TRACING_TARGET, endpoint = ?config.endpoint, region = %config.region, path_style = config.force_path_style, - "Connecting to the blob store", + "Building the blob store client", ); - let mut loader = aws_config::defaults(BehaviorVersion::latest()) - .region(Region::new(config.region.clone())); - - match (&config.access_key_id, &config.secret_access_key) { - (Some(access_key_id), Some(secret_access_key)) => { - loader = loader.credentials_provider(Credentials::new( - access_key_id.expose(), - secret_access_key.expose(), - None, - None, - STATIC_PROVIDER, - )); - } - (None, None) => {} + // Static credentials stand alone; only without them does the builder read + // the `AWS_*` environment, so an unrelated session token or signing + // override there never mixes into a configured key pair. + let mut builder = match (&config.access_key_id, &config.secret_access_key) { + (Some(access_key_id), Some(secret_access_key)) => AmazonS3Builder::new() + .with_access_key_id(access_key_id.expose()) + .with_secret_access_key(secret_access_key.expose()), + (None, None) => AmazonS3Builder::from_env(), _ => { return Err(Error::Config( "S3 credentials incomplete: set both an access key id and a secret access key, \ - or neither (to use the default credential chain)" + or neither to use the environment credential chain" .to_owned(), )); } + }; + + builder = builder + .with_bucket_name(&config.bucket) + .with_region(&config.region) + // S3-compatible servers address as `endpoint/bucket/key`; AWS S3 uses + // `bucket.endpoint/key`. + .with_virtual_hosted_style_request(!config.force_path_style) + // Each call deletes one key, so plain `DeleteObject` suffices and + // works on servers without the bulk `DeleteObjects` API. + .with_disable_bulk_delete(true) + // A streamed download is read at the consumer's pace, so no + // whole-request timeout; connecting is bounded, and a body that + // stops sending data fails after the read timeout. + .with_client_options( + ClientOptions::new() + .with_timeout_disabled() + .with_read_timeout(READ_TIMEOUT), + ); + + if let Some(endpoint) = resolve_endpoint(config, &builder)? { + // The S3-specific key outranks the generic one, so the resolved + // endpoint is the one the client uses. + builder = builder + .with_allow_http(endpoint.starts_with("http://")) + .with_config(AmazonS3ConfigKey::S3Endpoint, endpoint); } - let shared = loader.load().await; - let mut builder = aws_sdk_s3::config::Builder::from(&shared); - if let Some(endpoint) = &config.endpoint { - builder = builder.endpoint_url(endpoint); + let store = builder + .build() + .map_err(|err| Error::Config(err.to_string()))?; + Ok(Self::new(ObjectStoreClient::new(store))) + } +} + +/// The endpoint the client should use, already shaped for the addressing style: +/// the configured endpoint, else one `builder` read from the environment +/// (`AWS_ENDPOINT_URL_S3`, then `AWS_ENDPOINT`), else `None` for AWS S3. +fn resolve_endpoint(config: &S3Config, builder: &AmazonS3Builder) -> Result> { + let endpoint = config + .endpoint + .clone() + .or_else(|| builder.get_config_value(&AmazonS3ConfigKey::S3Endpoint)) + .or_else(|| builder.get_config_value(&AmazonS3ConfigKey::Endpoint)); + match endpoint { + Some(endpoint) if !config.force_path_style => { + virtual_hosted_endpoint(&endpoint, &config.bucket).map(Some) } - // S3-compatible servers address as `endpoint/bucket/key`; AWS S3 uses - // `bucket.endpoint/key`. - builder = builder.force_path_style(config.force_path_style); + endpoint => Ok(endpoint), + } +} + +/// Puts `bucket` in front of `endpoint`'s host for virtual-hosted-style +/// addressing, which `object_store` expects the endpoint to carry already. +fn virtual_hosted_endpoint(endpoint: &str, bucket: &str) -> Result { + let mut url = Url::parse(endpoint) + .map_err(|err| Error::Config(format!("invalid S3 endpoint {endpoint:?}: {err}")))?; + let host = url + .host_str() + .ok_or_else(|| Error::Config(format!("S3 endpoint {endpoint:?} has no host")))?; + let host = format!("{bucket}.{host}"); + url.set_host(Some(&host)) + .map_err(|err| Error::Config(format!("invalid S3 endpoint host {host:?}: {err}")))?; + Ok(url.as_str().trim_end_matches('/').to_owned()) +} + +#[cfg(test)] +mod tests { + use object_store::aws::{AmazonS3Builder, AmazonS3ConfigKey}; - let client = aws_sdk_s3::Client::from_conf(builder.build()); - Ok(Self::new(client, config.bucket.clone())) + use super::{S3Config, resolve_endpoint, virtual_hosted_endpoint}; + + fn config(endpoint: Option<&str>, force_path_style: bool) -> S3Config { + S3Config { + bucket: "blobs".to_owned(), + region: "us-east-1".to_owned(), + endpoint: endpoint.map(str::to_owned), + force_path_style, + access_key_id: None, + secret_access_key: None, + } + } + + #[test] + fn virtual_hosted_endpoint_prefixes_the_bucket() { + assert_eq!( + virtual_hosted_endpoint("https://s3.eu-west-1.amazonaws.com", "blobs").unwrap(), + "https://blobs.s3.eu-west-1.amazonaws.com" + ); + assert_eq!( + virtual_hosted_endpoint("https://acct.r2.cloudflarestorage.com:8443/", "blobs") + .unwrap(), + "https://blobs.acct.r2.cloudflarestorage.com:8443" + ); + } + + #[test] + fn environment_endpoints_get_the_same_addressing_as_configured_ones() { + let env = AmazonS3Builder::new() + .with_config(AmazonS3ConfigKey::Endpoint, "https://generic.example.com") + .with_config(AmazonS3ConfigKey::S3Endpoint, "https://s3.example.com"); + let none = AmazonS3Builder::new(); + + // The configured endpoint wins over the environment's. + assert_eq!( + resolve_endpoint(&config(Some("https://cfg.example.com"), false), &env).unwrap(), + Some("https://blobs.cfg.example.com".to_owned()) + ); + // The S3-specific environment key wins over the generic one, and is + // prefixed with the bucket in virtual-hosted mode. + assert_eq!( + resolve_endpoint(&config(None, false), &env).unwrap(), + Some("https://blobs.s3.example.com".to_owned()) + ); + let generic = AmazonS3Builder::new() + .with_config(AmazonS3ConfigKey::Endpoint, "http://localhost:9000"); + assert_eq!( + resolve_endpoint(&config(None, true), &generic).unwrap(), + Some("http://localhost:9000".to_owned()) + ); + assert_eq!(resolve_endpoint(&config(None, false), &none).unwrap(), None); } } diff --git a/crates/nvisy-s3/src/client/store.rs b/crates/nvisy-s3/src/client/store.rs index 55b32e2b..27cee333 100644 --- a/crates/nvisy-s3/src/client/store.rs +++ b/crates/nvisy-s3/src/client/store.rs @@ -1,9 +1,10 @@ //! The S3-compatible blob store. -use aws_sdk_s3::Client; -use aws_sdk_s3::primitives::ByteStream; -use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart}; +use futures::TryStreamExt; +use nvisy_core::{Error as CoreError, ErrorKind}; +use nvisy_object_store::client::ObjectStoreClient; use tokio::io::{AsyncRead, AsyncReadExt}; +use tokio_util::io::{ReaderStream, StreamReader}; use crate::error::{Error, Result}; use crate::key::ObjectKey; @@ -11,15 +12,8 @@ use crate::key::ObjectKey; /// Tracing target for blob-store operations. const TRACING_TARGET: &str = "nvisy_s3::store"; -/// Size of each multipart-upload part. S3 requires every part except the last to -/// be at least 5 MiB; 8 MiB keeps part counts low for large objects while staying -/// comfortably above the floor. -const PART_SIZE: usize = 8 * 1024 * 1024; - -/// S3 accepts at most 10,000 parts per multipart upload. With [`PART_SIZE`] parts -/// that caps a single object at ~78 GiB; an upload that would exceed the limit is -/// rejected (and aborted) rather than submitting a part S3 refuses. -const MAX_PARTS: i32 = 10_000; +/// Size of each read from an upload's reader. +const READ_CHUNK_SIZE: usize = 64 * 1024; /// A handle to a stored object's content and size. /// @@ -48,20 +42,19 @@ impl GetObject { /// /// One S3 bucket holds every logical [`Bucket`]; each object is addressed by /// `"{bucket.prefix()}/{key}"`, and the bucket is derived from the key's -/// [`ObjectKey::BUCKET`]. Cloneable and cheap to pass around — it wraps an -/// `Arc`-backed SDK client. +/// [`ObjectKey::BUCKET`]. Cloneable and cheap to pass around: it wraps an +/// `Arc`-backed [`ObjectStoreClient`]. /// /// [`Bucket`]: crate::Bucket #[derive(Clone)] pub struct BlobStore { - client: Client, - bucket: String, + client: ObjectStoreClient, } impl BlobStore { - /// Wraps an already-built S3 client for `bucket`. - pub(crate) fn new(client: Client, bucket: String) -> Self { - Self { client, bucket } + /// Wraps a client already scoped to the configured bucket. + pub(crate) fn new(client: ObjectStoreClient) -> Self { + Self { client } } /// The full S3 object key for `key`, namespaced under its store's prefix. @@ -72,16 +65,14 @@ impl BlobStore { /// Streams `reader` into `key`'s store, returning the number of bytes written. /// /// The target store is [`K::BUCKET`], so a key can only be written to its own - /// store. Uploads as a single S3 object when the content fits one part, and as - /// a multipart upload otherwise, so an object of unknown length streams without - /// being buffered whole in memory. A failure after the multipart upload begins - /// aborts it so no partial upload lingers. + /// store. Small content is written with a single put and larger content as a + /// multipart upload, so an object of unknown length streams without being + /// buffered whole in memory; a failed upload is aborted so nothing partial + /// lingers. /// /// # Errors /// - /// - `Body` if reading from `reader` fails. - /// - `Operation` if the store rejects the upload (a single-part put, or any - /// part of a multipart upload). + /// `Operation` if reading from `reader` fails or the store rejects the upload. /// /// [`K::BUCKET`]: ObjectKey::BUCKET pub async fn put(&self, key: &K, reader: R) -> Result @@ -92,198 +83,38 @@ impl BlobStore { let object_key = Self::object_key(key); tracing::debug!(target: TRACING_TARGET, key = %object_key, "Uploading object"); - let mut reader = reader; - let first = read_part(&mut reader).await?; - - // Small object: one PutObject, no multipart bookkeeping. - if first.len() < PART_SIZE { - let size = u64::try_from(first.len()).unwrap_or(u64::MAX); - self.client - .put_object() - .bucket(&self.bucket) - .key(&object_key) - .body(ByteStream::from(first)) - .send() - .await - .map_err(|err| Error::operation("put", err.into_service_error()))?; - tracing::debug!(target: TRACING_TARGET, key = %object_key, size, "Object uploaded"); - return Ok(size); - } - - // Box the multipart future so it is heap-allocated rather than inlined - // into `put`'s own future. With a deeply-nested reader type the combined - // future is otherwise large enough to overflow a worker thread's stack - // just being constructed, even for the small-object path that never runs - // this branch. - Box::pin(self.put_multipart(&object_key, first, reader)).await - } - - /// Streams the remainder of `reader` after `first` as a multipart upload. - async fn put_multipart(&self, object_key: &str, first: Vec, mut reader: R) -> Result - where - R: AsyncRead + Unpin + Send, - { - let created = self - .client - .create_multipart_upload() - .bucket(&self.bucket) - .key(object_key) - .send() + let body = ReaderStream::with_capacity(reader, READ_CHUNK_SIZE) + .map_err(|err| CoreError::runtime("failed to read the upload body").with_source(err)); + // Box the upload future so it is heap-allocated rather than inlined into + // `put`'s own future: with a deeply nested reader type the combined future + // is otherwise large enough to overflow a worker thread's stack. + let size = Box::pin(self.client.put_stream(&object_key, None, body)) .await - .map_err(|err| Error::operation("put", err.into_service_error()))?; - let upload_id = created.upload_id().ok_or_else(|| { - Error::operation_msg("put", "S3 create_multipart_upload returned no upload id") - })?; - - // Upload every part; on any failure, abort so no partial upload lingers. - let result = self - .upload_parts(object_key, upload_id, first, &mut reader) - .await; - let (parts, size) = match result { - Ok(uploaded) => uploaded, - Err(err) => { - self.abort_multipart(object_key, upload_id).await; - return Err(err); - } - }; + .map_err(|err| Error::operation("put", err))?; - // Parts uploaded; completing them can still fail. Abort on that too, so a - // failure never leaves the uploaded parts billing until S3 lifecycle reaps - // them. - let completed = self - .client - .complete_multipart_upload() - .bucket(&self.bucket) - .key(object_key) - .upload_id(upload_id) - .multipart_upload( - CompletedMultipartUpload::builder() - .set_parts(Some(parts)) - .build(), - ) - .send() - .await; - if let Err(err) = completed { - self.abort_multipart(object_key, upload_id).await; - return Err(Error::operation("put", err.into_service_error())); - } - - tracing::debug!(target: TRACING_TARGET, key = %object_key, size, "Object uploaded (multipart)"); + tracing::debug!(target: TRACING_TARGET, key = %object_key, size, "Object uploaded"); Ok(size) } - /// Uploads `first` and every subsequent part read from `reader`, returning the - /// completed parts and the total byte count. - async fn upload_parts( - &self, - object_key: &str, - upload_id: &str, - first: Vec, - reader: &mut R, - ) -> Result<(Vec, u64)> - where - R: AsyncRead + Unpin + Send, - { - let mut parts = Vec::new(); - let mut total: u64 = 0; - let mut part = first; - let mut part_number = 1; - - loop { - if part_number > MAX_PARTS { - return Err(Error::operation_msg( - "put", - format!("object exceeds the maximum of {MAX_PARTS} upload parts"), - )); - } - - total += u64::try_from(part.len()).unwrap_or(u64::MAX); - let uploaded = self - .client - .upload_part() - .bucket(&self.bucket) - .key(object_key) - .upload_id(upload_id) - .part_number(part_number) - .body(ByteStream::from(part)) - .send() - .await - .map_err(|err| Error::operation("put", err.into_service_error()))?; - parts.push( - CompletedPart::builder() - .part_number(part_number) - .set_e_tag(uploaded.e_tag().map(str::to_owned)) - .build(), - ); - - // The next part; an empty read means the stream is exhausted. - let next = read_part(reader).await?; - if next.is_empty() { - break; - } - part = next; - part_number += 1; - } - - Ok((parts, total)) - } - - /// Aborts a multipart upload, best-effort — a failure only leaves an - /// incomplete upload for S3's own lifecycle rules to reap, so it is logged - /// rather than propagated over the original error. - async fn abort_multipart(&self, object_key: &str, upload_id: &str) { - if let Err(err) = self - .client - .abort_multipart_upload() - .bucket(&self.bucket) - .key(object_key) - .upload_id(upload_id) - .send() - .await - { - tracing::warn!( - target: TRACING_TARGET, - key = %object_key, - error = %err.into_service_error(), - "Failed to abort a multipart upload; left for S3 lifecycle cleanup", - ); - } - } - /// Fetches an object as a stream, or `None` if it does not exist. /// /// # Errors /// - /// `Operation` if the fetch fails for any reason other than a missing object - /// (a missing object is reported as `Ok(None)`). + /// `Operation` if the fetch fails for any reason other than a missing object. pub async fn get(&self, key: &K) -> Result> { let object_key = Self::object_key(key); tracing::debug!(target: TRACING_TARGET, key = %object_key, "Fetching object"); - let output = match self - .client - .get_object() - .bucket(&self.bucket) - .key(&object_key) - .send() - .await - { - Ok(output) => output, - Err(err) => { - let service = err.into_service_error(); - if service.is_no_such_key() { - return Ok(None); - } - return Err(Error::operation("get", service)); - } - }; - - let size = u64::try_from(output.content_length().unwrap_or_default().max(0)).unwrap_or(0); - let reader = output.body.into_async_read(); - Ok(Some(GetObject { - reader: Box::new(reader), - size, - })) + match self.client.get_stream(&object_key).await { + Ok(object) => Ok(Some(GetObject { + reader: Box::new(StreamReader::new( + object.body.map_err(std::io::Error::other), + )), + size: object.size, + })), + Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), + Err(err) => Err(Error::operation("get", err)), + } } /// Fetches an object's whole content, or `None` if it does not exist. @@ -301,7 +132,10 @@ impl BlobStore { .into_reader() .read_to_end(&mut bytes) .await - .map_err(|err| Error::operation("read", err))?; + .map_err(|err| { + let source = CoreError::runtime("failed to read the object body").with_source(err); + Error::operation("read", source) + })?; Ok(Some(bytes)) } @@ -315,19 +149,16 @@ impl BlobStore { tracing::debug!(target: TRACING_TARGET, key = %object_key, "Deleting object"); self.client - .delete_object() - .bucket(&self.bucket) - .key(&object_key) - .send() + .delete(&object_key) .await - .map_err(|err| Error::operation("delete", err.into_service_error()))?; - Ok(()) + .map_err(|err| Error::operation("delete", err)) } - /// Probes the store's liveness by heading the configured bucket. + /// Probes the store's liveness with a bounded top-level listing of the + /// configured bucket. /// /// Succeeds when the endpoint is reachable and the bucket exists and is - /// accessible with the current credentials — the same preconditions every + /// listable with the current credentials, the same preconditions every /// object operation needs, so it doubles as a readiness check. /// /// # Errors @@ -336,82 +167,8 @@ impl BlobStore { /// or the bucket is missing or inaccessible. pub async fn ping(&self) -> Result<()> { self.client - .head_bucket() - .bucket(&self.bucket) - .send() - .await - .map_err(|err| Error::operation("head_bucket", err.into_service_error()))?; - Ok(()) - } - - /// Creates the configured bucket, for test setup against an empty store. - /// - /// Deployments provision their bucket out of band, so this is test-only: - /// gated on the `test_util` feature and never part of the normal API. - /// - /// # Errors - /// - /// `Operation` if the bucket cannot be created (already exists, or the store - /// rejects the request). - #[cfg(feature = "test_util")] - pub async fn create_bucket(&self) -> Result<()> { - self.client - .create_bucket() - .bucket(&self.bucket) - .send() - .await - .map_err(|err| Error::operation("create_bucket", err.into_service_error()))?; - Ok(()) - } - - /// Whether an object exists, via a HEAD request. - /// - /// # Errors - /// - /// `Operation` if the HEAD request fails for any reason other than the object - /// being absent (a missing object is reported as `Ok(false)`). - pub async fn exists(&self, key: &K) -> Result { - let object_key = Self::object_key(key); - match self - .client - .head_object() - .bucket(&self.bucket) - .key(&object_key) - .send() + .verify_reachable() .await - { - Ok(_) => Ok(true), - Err(err) => { - let service = err.into_service_error(); - if service.is_not_found() { - Ok(false) - } else { - Err(Error::operation("head", service)) - } - } - } - } -} - -/// Reads up to [`PART_SIZE`] bytes from `reader`, returning fewer only at EOF. -/// -/// An empty return means the stream is exhausted. Reading the whole part up front -/// is what lets a small object take the single-`PutObject` path and lets each -/// multipart part meet S3's minimum size. -async fn read_part(reader: &mut R) -> Result> { - let mut buffer = Vec::with_capacity(PART_SIZE); - // Heap-allocate the scratch chunk: as a stack array it would be embedded in - // this future (and transitively in `put`'s), enlarging it needlessly. - let mut chunk = vec![0u8; 64 * 1024]; - while buffer.len() < PART_SIZE { - let read = reader - .read(&mut chunk) - .await - .map_err(|err| Error::Body(err.to_string()))?; - if read == 0 { - break; - } - buffer.extend_from_slice(&chunk[..read]); + .map_err(|err| Error::operation("ping", err)) } - Ok(buffer) } diff --git a/crates/nvisy-s3/src/error.rs b/crates/nvisy-s3/src/error.rs index 996414db..7c37dbff 100644 --- a/crates/nvisy-s3/src/error.rs +++ b/crates/nvisy-s3/src/error.rs @@ -1,11 +1,5 @@ //! Error types for the blob store. -use std::error::Error as StdError; - -/// A boxed underlying error, retained so callers can downcast to the SDK's typed -/// service error rather than only reading its rendered message. -type BoxError = Box; - /// Result alias for blob-store operations. pub type Result = std::result::Result; @@ -16,50 +10,23 @@ pub enum Error { /// The client could not be built from the supplied configuration. #[error("failed to configure the blob store: {0}")] Config(String), - - /// A storage operation (put, get, delete, head) failed. - /// - /// Carries the operation name and the underlying message so a caller can log - /// what failed without matching on the SDK's error types, and keeps the - /// underlying error as the [`source`](StdError::source) so a caller that - /// wants the typed SDK error can downcast to it. - #[error("blob store {operation} failed: {message}")] + /// A string did not parse as an object key. + #[error("invalid object key: {0}")] + InvalidKey(String), + /// A storage operation (put, get, read, delete, ping) failed. + #[error("blob store {operation} failed: {source}")] Operation { - /// The operation that failed (`put`, `get`, `delete`, `head`). + /// The operation that failed. operation: &'static str, - /// The underlying error message. - message: String, - /// The underlying error, when the failure wraps one. + /// The classified underlying error. #[source] - source: Option, + source: nvisy_core::Error, }, - - /// The stored object's bytes could not be read from the response stream. - #[error("failed to read object body: {0}")] - Body(String), } impl Error { - /// Builds an [`Error::Operation`] for `operation`, keeping `error` as the - /// message and its source so a caller can downcast to the typed SDK error. - pub(crate) fn operation( - operation: &'static str, - error: impl StdError + Send + Sync + 'static, - ) -> Self { - Self::Operation { - operation, - message: error.to_string(), - source: Some(Box::new(error)), - } - } - - /// Builds an [`Error::Operation`] for `operation` from a message alone, - /// for failures that do not wrap an underlying error. - pub(crate) fn operation_msg(operation: &'static str, message: impl Into) -> Self { - Self::Operation { - operation, - message: message.into(), - source: None, - } + /// Builds an [`Error::Operation`] for `operation`. + pub(crate) fn operation(operation: &'static str, source: nvisy_core::Error) -> Self { + Self::Operation { operation, source } } } diff --git a/crates/nvisy-s3/src/key/avatar_key.rs b/crates/nvisy-s3/src/key/avatar_key.rs index d6a24352..fc573d04 100644 --- a/crates/nvisy-s3/src/key/avatar_key.rs +++ b/crates/nvisy-s3/src/key/avatar_key.rs @@ -9,93 +9,69 @@ use super::bucket::Bucket; use super::object_key::{ObjectKey, parse_error, split_id_version}; use crate::error::{Error, Result}; -/// A validated key for an account-scoped object (an avatar). -/// -/// The key format is `account_{account_id}_{version}`, where `version` is a -/// random version drawn per upload. Each avatar version is a distinct object, so +/// Defines an owner-scoped avatar key, `{prefix}{owner_id}_{version}`, where +/// `version` is drawn randomly per upload. Each version is a distinct object, so /// a versioned URL maps to immutable bytes and a stale version simply does not /// exist. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct AccountAvatarKey { - pub account_id: Uuid, - pub version: String, -} - -impl ObjectKey for AccountAvatarKey { - const BUCKET: Bucket = Bucket::Avatars; - const PREFIX: &'static str = "account_"; -} - -impl AccountAvatarKey { - /// Creates a new account key for a specific avatar version. - pub fn new(account_id: Uuid, version: impl Into) -> Self { - Self { - account_id, - version: version.into(), +macro_rules! avatar_key { + ($(#[$meta:meta])* $name:ident, $owner:ident, $prefix:literal) => { + $(#[$meta])* + #[derive(Debug, Clone, PartialEq, Eq, Hash)] + pub struct $name { + /// The avatar's owner. + pub $owner: Uuid, + /// The avatar version. + pub version: String, } - } -} -impl fmt::Display for AccountAvatarKey { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}{}_{}", Self::PREFIX, self.account_id, self.version) - } -} - -impl FromStr for AccountAvatarKey { - type Err = Error; + impl ObjectKey for $name { + const BUCKET: Bucket = Bucket::Avatars; + const PREFIX: &'static str = $prefix; + } - fn from_str(s: &str) -> Result { - let (id, version) = split_id_version::(s)?; - let account_id = - Uuid::parse_str(id).map_err(|e| parse_error(format!("Invalid account UUID: {e}")))?; - Ok(Self::new(account_id, version)) - } -} + impl $name { + /// A key for one version of the owner's avatar. + pub fn new($owner: Uuid, version: impl Into) -> Self { + Self { + $owner, + version: version.into(), + } + } + } -/// A validated key for a workspace-scoped object (an avatar/logo). -/// -/// The key format is `workspace_{workspace_id}_{version}`, where `version` is a -/// random version drawn per upload. Each avatar version is a distinct object, so -/// a versioned URL maps to immutable bytes and a stale version simply does not -/// exist. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct WorkspaceAvatarKey { - pub workspace_id: Uuid, - pub version: String, -} + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}{}_{}", Self::PREFIX, self.$owner, self.version) + } + } -impl ObjectKey for WorkspaceAvatarKey { - const BUCKET: Bucket = Bucket::Avatars; - const PREFIX: &'static str = "workspace_"; -} + impl FromStr for $name { + type Err = Error; -impl WorkspaceAvatarKey { - /// Creates a new workspace key for a specific avatar version. - pub fn new(workspace_id: Uuid, version: impl Into) -> Self { - Self { - workspace_id, - version: version.into(), + fn from_str(s: &str) -> Result { + let (id, version) = split_id_version::(s)?; + let $owner = + Uuid::parse_str(id).map_err(|e| parse_error(format!("Invalid owner UUID: {e}")))?; + Ok(Self::new($owner, version)) + } } - } + }; } -impl fmt::Display for WorkspaceAvatarKey { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}{}_{}", Self::PREFIX, self.workspace_id, self.version) - } -} - -impl FromStr for WorkspaceAvatarKey { - type Err = Error; - - fn from_str(s: &str) -> Result { - let (id, version) = split_id_version::(s)?; - let workspace_id = - Uuid::parse_str(id).map_err(|e| parse_error(format!("Invalid workspace UUID: {e}")))?; - Ok(Self::new(workspace_id, version)) - } -} +avatar_key!( + /// A key for one version of an account's avatar, `account_{account_id}_{version}`. + AccountAvatarKey, + account_id, + "account_" +); + +avatar_key!( + /// A key for one version of a workspace's avatar, + /// `workspace_{workspace_id}_{version}`. + WorkspaceAvatarKey, + workspace_id, + "workspace_" +); #[cfg(test)] mod tests { @@ -106,22 +82,17 @@ mod tests { let account_id = Uuid::new_v4(); let key = AccountAvatarKey::new(account_id, "abc123"); assert_eq!(key.to_string(), format!("account_{account_id}_abc123")); - let decoded: AccountAvatarKey = key.to_string().parse().unwrap(); - assert_eq!(decoded.account_id, account_id); - assert_eq!(decoded.version, "abc123"); + assert_eq!(key.to_string().parse::().unwrap(), key); } #[test] fn workspace_avatar_round_trips() { - let workspace_id = Uuid::new_v4(); - let key = WorkspaceAvatarKey::new(workspace_id, "v9"); - let decoded: WorkspaceAvatarKey = key.to_string().parse().unwrap(); - assert_eq!(decoded.workspace_id, workspace_id); - assert_eq!(decoded.version, "v9"); + let key = WorkspaceAvatarKey::new(Uuid::new_v4(), "v9"); + assert_eq!(key.to_string().parse::().unwrap(), key); } #[test] - fn account_avatar_rejects_bad_input() { + fn avatar_rejects_bad_input() { assert!(AccountAvatarKey::from_str("file_abc").is_err()); assert!(AccountAvatarKey::from_str("account_not-a-uuid").is_err()); } diff --git a/crates/nvisy-s3/src/key/document_key.rs b/crates/nvisy-s3/src/key/document_key.rs index 95e03cbb..dfa66b1c 100644 --- a/crates/nvisy-s3/src/key/document_key.rs +++ b/crates/nvisy-s3/src/key/document_key.rs @@ -9,208 +9,89 @@ use super::bucket::Bucket; use super::object_key::{ObjectKey, decode_ids, encode_ids, strip_prefix}; use crate::error::{Error, Result}; -/// A validated key for document objects. -/// -/// The key is encoded as a `document_` prefix followed by URL-safe base64 of the -/// concatenated workspace ID and object ID. This produces a key like -/// `document_ABC123...` from two UUIDs (32 bytes → base64). -/// -/// The `object_id` is a UUID v7 generated at upload time, providing: -/// - Time-ordered keys for efficient storage and retrieval -/// - Guaranteed uniqueness within the workspace -/// - No collision with database-generated IDs -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct DocumentKey { - pub workspace_id: Uuid, - pub object_id: Uuid, -} - -impl ObjectKey for DocumentKey { - const BUCKET: Bucket = Bucket::Documents; - const PREFIX: &'static str = "document_"; -} - -impl DocumentKey { - /// Generates a new document key with a fresh UUID v7 object ID. - /// - /// Uses UUID v7, which is time-ordered and contains randomness, making keys - /// both sortable and collision-resistant. - #[must_use] - pub fn generate(workspace_id: Uuid) -> Self { - Self { - workspace_id, - object_id: Uuid::now_v7(), +/// Defines a workspace-scoped key: a prefix followed by URL-safe base64 of the +/// concatenated workspace id and object id (32 bytes → 43 characters). +macro_rules! workspace_object_key { + ($(#[$meta:meta])* $name:ident, $prefix:literal, $bucket:expr) => { + $(#[$meta])* + #[derive(Debug, Clone, PartialEq, Eq, Hash)] + pub struct $name { + /// The workspace the object belongs to. + pub workspace_id: Uuid, + /// The object's own id, a UUID v7. + pub object_id: Uuid, } - } - /// Creates a document key from existing IDs (for parsing stored keys). - #[must_use] - pub fn from_parts(workspace_id: Uuid, object_id: Uuid) -> Self { - Self { - workspace_id, - object_id, + impl ObjectKey for $name { + const BUCKET: Bucket = $bucket; + const PREFIX: &'static str = $prefix; } - } - - /// Regenerates the object ID with a fresh UUID v7. - /// - /// Useful when creating a new version of a document while keeping the same - /// workspace association. - pub fn regenerate(&mut self) { - self.object_id = Uuid::now_v7(); - } - - /// Encodes the key payload as URL-safe base64. - fn encode_payload(&self) -> String { - encode_ids(self.workspace_id, self.object_id) - } - - /// Decodes a key payload from URL-safe base64. - fn decode_payload(s: &str) -> Result { - let (workspace_id, object_id) = decode_ids(s)?; - Ok(Self::from_parts(workspace_id, object_id)) - } -} - -impl fmt::Display for DocumentKey { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}{}", Self::PREFIX, self.encode_payload()) - } -} - -impl FromStr for DocumentKey { - type Err = Error; - - fn from_str(s: &str) -> Result { - Self::decode_payload(strip_prefix::(s)?) - } -} - -/// A validated key for a redaction audit object. -/// -/// Addresses a detection's analyzed document — the engine's detection result -/// (the audit of what was found and redacted). Encoded as an `audit_` prefix -/// followed by URL-safe base64 of the concatenated workspace ID and object ID -/// (32 bytes → base64), like [`DocumentKey`]. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct AuditKey { - pub workspace_id: Uuid, - pub object_id: Uuid, -} - -impl ObjectKey for AuditKey { - const BUCKET: Bucket = Bucket::Audits; - const PREFIX: &'static str = "audit_"; -} -impl AuditKey { - /// Generates a new audit key with a fresh UUID v7 object ID. - #[must_use] - pub fn generate(workspace_id: Uuid) -> Self { - Self { - workspace_id, - object_id: Uuid::now_v7(), + impl $name { + /// A new key in `workspace_id` with a fresh UUID v7 object id, so keys + /// are time-ordered and collision-resistant. + #[must_use] + pub fn generate(workspace_id: Uuid) -> Self { + Self { + workspace_id, + object_id: Uuid::now_v7(), + } + } } - } - /// Creates an audit key from existing IDs (for parsing stored keys). - #[must_use] - pub fn from_parts(workspace_id: Uuid, object_id: Uuid) -> Self { - Self { - workspace_id, - object_id, + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}{}", Self::PREFIX, encode_ids(self.workspace_id, self.object_id)) + } } - } -} - -impl fmt::Display for AuditKey { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}{}", - Self::PREFIX, - encode_ids(self.workspace_id, self.object_id) - ) - } -} -impl FromStr for AuditKey { - type Err = Error; + impl FromStr for $name { + type Err = Error; - fn from_str(s: &str) -> Result { - let (workspace_id, object_id) = decode_ids(strip_prefix::(s)?)?; - Ok(Self::from_parts(workspace_id, object_id)) - } -} - -/// A validated key for a transient pipeline-intermediate object. -/// -/// Addresses a detection's enrichment intermediates (an image's OCR layout, an -/// audio transcript). Encoded as an `intermediate_` prefix followed by URL-safe -/// base64 of the concatenated workspace ID and object ID (32 bytes → base64), -/// like [`DocumentKey`]. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct IntermediateKey { - pub workspace_id: Uuid, - pub object_id: Uuid, -} - -impl ObjectKey for IntermediateKey { - const BUCKET: Bucket = Bucket::Intermediates; - const PREFIX: &'static str = "intermediate_"; -} - -impl IntermediateKey { - /// Generates a new intermediate key with a fresh UUID v7 object ID. - #[must_use] - pub fn generate(workspace_id: Uuid) -> Self { - Self { - workspace_id, - object_id: Uuid::now_v7(), - } - } - - /// Creates an intermediate key from existing IDs (for parsing stored keys). - #[must_use] - pub fn from_parts(workspace_id: Uuid, object_id: Uuid) -> Self { - Self { - workspace_id, - object_id, + fn from_str(s: &str) -> Result { + let (workspace_id, object_id) = decode_ids(strip_prefix::(s)?)?; + Ok(Self { + workspace_id, + object_id, + }) + } } - } -} - -impl fmt::Display for IntermediateKey { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}{}", - Self::PREFIX, - encode_ids(self.workspace_id, self.object_id) - ) - } -} - -impl FromStr for IntermediateKey { - type Err = Error; - - fn from_str(s: &str) -> Result { - let (workspace_id, object_id) = decode_ids(strip_prefix::(s)?)?; - Ok(Self::from_parts(workspace_id, object_id)) - } -} + }; +} + +workspace_object_key!( + /// A key for an uploaded or redacted document, `document_{ids}`. + DocumentKey, + "document_", + Bucket::Documents +); + +workspace_object_key!( + /// A key for a detection's audit: the engine's record of what was found and + /// redacted, `audit_{ids}`. + AuditKey, + "audit_", + Bucket::Audits +); + +workspace_object_key!( + /// A key for a detection's transient enrichment intermediates (an image's + /// OCR layout, an audio transcript), `intermediate_{ids}`. + IntermediateKey, + "intermediate_", + Bucket::Intermediates +); #[cfg(test)] mod tests { use super::*; - #[test] - fn document_key_prefix_is_document() { - assert_eq!(DocumentKey::PREFIX, "document_"); + fn key(build: impl Fn(Uuid, Uuid) -> K) -> K { + build(Uuid::new_v4(), Uuid::now_v7()) } #[test] - fn document_key_generate_uses_uuid_v7() { + fn generate_uses_uuid_v7() { let workspace_id = Uuid::new_v4(); let key = DocumentKey::generate(workspace_id); assert_eq!(key.workspace_id, workspace_id); @@ -218,42 +99,40 @@ mod tests { } #[test] - fn document_key_display_has_prefix_and_expected_length() { - let key = DocumentKey::generate(Uuid::new_v4()); - let encoded = key.to_string(); + fn display_is_prefix_then_43_base64_characters() { + let encoded = DocumentKey::generate(Uuid::new_v4()).to_string(); assert!(encoded.starts_with("document_")); - // prefix (9) + base64 of 32 bytes (43) = 52. - assert_eq!(encoded.len(), 52); + assert_eq!(encoded.len(), "document_".len() + 43); } #[test] - fn document_key_round_trips_through_string() { - let key = DocumentKey::from_parts(Uuid::new_v4(), Uuid::new_v4()); - let decoded: DocumentKey = key.to_string().parse().unwrap(); - assert_eq!(key, decoded); - } - - #[test] - fn document_key_rejects_wrong_prefix() { + fn every_key_round_trips_and_rejects_another_prefix() { + let document = key(|workspace_id, object_id| DocumentKey { + workspace_id, + object_id, + }); + assert_eq!( + document.to_string().parse::().unwrap(), + document + ); assert!(DocumentKey::from_str("audit_abc").is_err()); assert!(DocumentKey::from_str("abc").is_err()); - } - #[test] - fn audit_key_round_trips_and_rejects_wrong_prefix() { - let key = AuditKey::from_parts(Uuid::new_v4(), Uuid::new_v4()); - let decoded: AuditKey = key.to_string().parse().unwrap(); - assert_eq!(key, decoded); - assert!(key.to_string().starts_with("audit_")); + let audit = key(|workspace_id, object_id| AuditKey { + workspace_id, + object_id, + }); + assert_eq!(audit.to_string().parse::().unwrap(), audit); assert!(AuditKey::from_str("document_abc").is_err()); - } - #[test] - fn intermediate_key_round_trips_and_rejects_wrong_prefix() { - let key = IntermediateKey::from_parts(Uuid::new_v4(), Uuid::new_v4()); - let decoded: IntermediateKey = key.to_string().parse().unwrap(); - assert_eq!(key, decoded); - assert!(key.to_string().starts_with("intermediate_")); + let intermediate = key(|workspace_id, object_id| IntermediateKey { + workspace_id, + object_id, + }); + assert_eq!( + intermediate.to_string().parse::().unwrap(), + intermediate + ); assert!(IntermediateKey::from_str("audit_abc").is_err()); } } diff --git a/crates/nvisy-s3/src/key/object_key.rs b/crates/nvisy-s3/src/key/object_key.rs index 2bf31c8f..3af70756 100644 --- a/crates/nvisy-s3/src/key/object_key.rs +++ b/crates/nvisy-s3/src/key/object_key.rs @@ -25,7 +25,7 @@ pub trait ObjectKey: fmt::Display + FromStr + Clone + Send + Sync + /// Builds a key-parse error from any displayable cause. pub(super) fn parse_error(message: impl std::fmt::Display) -> Error { - Error::operation_msg("parse_key", message.to_string()) + Error::InvalidKey(message.to_string()) } /// Strips a key type's prefix, erroring if it is absent. diff --git a/crates/nvisy-s3/src/lib.rs b/crates/nvisy-s3/src/lib.rs index fe43c9fc..43f613fa 100644 --- a/crates/nvisy-s3/src/lib.rs +++ b/crates/nvisy-s3/src/lib.rs @@ -6,8 +6,9 @@ //! //! Holds Nvisy's own objects — uploaded files, detection audits, enrichment //! intermediates, redacted output, and avatars — in a single S3 bucket, one -//! logical [`Bucket`] per key prefix. Backed by the AWS S3 SDK, so it targets AWS -//! S3 or any S3-compatible server (`RustFS`, `MinIO`, R2, …) by endpoint. +//! logical [`Bucket`] per key prefix. Built on `nvisy-object-store`'s +//! `object_store` client, so it targets AWS S3 or any S3-compatible server +//! (`RustFS`, `MinIO`, R2, …) by endpoint. //! //! Objects are already encrypted by the caller before they reach [`BlobStore`], //! so the store only ever sees ciphertext. diff --git a/crates/nvisy-s3/src/test_util.rs b/crates/nvisy-s3/src/test_util.rs index 0df551a9..737fb676 100644 --- a/crates/nvisy-s3/src/test_util.rs +++ b/crates/nvisy-s3/src/test_util.rs @@ -1,18 +1,19 @@ //! Test-only support for integration tests that need a real S3-compatible store. //! //! Starts an ephemeral `RustFS` container (the same S3-compatible backend the -//! dev stack uses), connects a [`BlobStore`], and creates its bucket — so the +//! dev stack uses), creates its bucket, and builds a [`BlobStore`], so the //! storage code can be exercised against a real backend without any external //! setup. Gated on the `test_util` feature, so it never ships in a default build. -use std::sync::OnceLock; - use nvisy_core::Secret; +use nvisy_core::test_util::boot_permit; +use object_store::aws::{AwsAuthorizer, AwsCredential}; +use object_store::client::{HttpRequest, HttpRequestBody}; +use reqwest::Method; use testcontainers_modules::testcontainers::core::wait::HttpWaitStrategy; use testcontainers_modules::testcontainers::core::{IntoContainerPort, WaitFor}; use testcontainers_modules::testcontainers::runners::AsyncRunner; use testcontainers_modules::testcontainers::{ContainerAsync, GenericImage, ImageExt}; -use tokio::sync::Semaphore; use crate::{BlobStore, S3Config}; @@ -27,22 +28,6 @@ const RUSTFS_TAG: &str = "1.0.0-rc.5"; const S3_ACCESS_KEY: &str = "rustfsadmin"; const S3_SECRET_KEY: &str = "rustfsadmin"; -/// Caps how many storage containers may boot at once, across the whole test -/// binary — booting all at once can overwhelm the Docker daemon and flake the -/// readiness probes. Serializes only the boot; the containers then run in -/// parallel. Raise with `NVISY_TEST_BOOT_CONCURRENCY`. -fn boot_semaphore() -> &'static Semaphore { - static BOOT: OnceLock = OnceLock::new(); - BOOT.get_or_init(|| { - let permits = std::env::var("NVISY_TEST_BOOT_CONCURRENCY") - .ok() - .and_then(|value| value.parse::().ok()) - .filter(|&n| n >= 1) - .unwrap_or(1); - Semaphore::new(permits) - }) -} - /// A running `RustFS` container paired with a connected [`BlobStore`] whose /// bucket ([`TEST_BUCKET`]) has been created. /// @@ -59,19 +44,16 @@ pub struct TestBlobStore { } impl TestBlobStore { - /// Starts a fresh `RustFS` container, connects a [`BlobStore`], and creates - /// the test bucket. + /// Starts a fresh `RustFS` container, creates the test bucket, and builds a + /// [`BlobStore`] for it. /// /// # Panics /// - /// Panics if the container cannot start, the store cannot connect, or the - /// bucket cannot be created — a test cannot proceed without a working store. + /// Panics if the container cannot start, the bucket cannot be created, or the + /// store cannot be built: a test cannot proceed without a working store. pub async fn start() -> Self { - let (container, port) = { - let _permit = boot_semaphore() - .acquire() - .await - .expect("boot semaphore is never closed"); + let (container, config) = { + let _permit = boot_permit().await; // Ready only once `/health/ready` serves 200 — RustFS serves requests // (and accepts bucket creation) only after storage has initialized. let ready = HttpWaitStrategy::new("/health/ready") @@ -88,25 +70,19 @@ impl TestBlobStore { .get_host_port_ipv4(9000) .await .expect("failed to resolve container port"); - (container, port) + let config = S3Config { + bucket: TEST_BUCKET.to_owned(), + region: "us-east-1".to_owned(), + endpoint: Some(format!("http://127.0.0.1:{port}")), + force_path_style: true, + access_key_id: Some(Secret::new(S3_ACCESS_KEY.to_owned())), + secret_access_key: Some(Secret::new(S3_SECRET_KEY.to_owned())), + }; + // The first request: the store is usable once its bucket exists. + create_bucket(&config).await; + (container, config) }; - - let config = S3Config { - bucket: TEST_BUCKET.to_owned(), - region: "us-east-1".to_owned(), - endpoint: Some(format!("http://127.0.0.1:{port}")), - force_path_style: true, - access_key_id: Some(Secret::new(S3_ACCESS_KEY.to_owned())), - secret_access_key: Some(Secret::new(S3_SECRET_KEY.to_owned())), - }; - - let store = BlobStore::connect(&config) - .await - .expect("failed to connect to the test blob store"); - store - .create_bucket() - .await - .expect("failed to create the test bucket"); + let store = BlobStore::connect(&config).expect("failed to build the test blob store"); Self { _container: container, @@ -116,6 +92,43 @@ impl TestBlobStore { } } +/// Creates the configured bucket with a SigV4-signed `PUT /{bucket}`. +/// +/// Deployments provision their bucket out of band, so the store has no +/// bucket-creation API; the harness signs the request with the store client's +/// own signer instead. +async fn create_bucket(config: &S3Config) { + let endpoint = config + .endpoint + .as_deref() + .expect("the test store has an endpoint"); + let url = format!("{endpoint}/{}", config.bucket); + let credential = AwsCredential { + key_id: S3_ACCESS_KEY.to_owned(), + secret_key: S3_SECRET_KEY.to_owned(), + token: None, + }; + + let mut request = HttpRequest::new(HttpRequestBody::empty()); + *request.method_mut() = Method::PUT; + *request.uri_mut() = url.parse().expect("a valid bucket URL"); + AwsAuthorizer::new(&credential, "s3", &config.region) + .try_authorize(&mut request, None) + .expect("sign the create-bucket request"); + + let response = reqwest::Client::new() + .put(&url) + .headers(request.headers().clone()) + .send() + .await + .expect("send the create-bucket request"); + assert!( + response.status().is_success(), + "creating the test bucket failed with {}", + response.status(), + ); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/nvisy-server/Cargo.toml b/crates/nvisy-server/Cargo.toml index 6b6e62cc..35bcd9e5 100644 --- a/crates/nvisy-server/Cargo.toml +++ b/crates/nvisy-server/Cargo.toml @@ -49,9 +49,7 @@ test_util = [ ] [dependencies] -# Elide crates. The workspace dep disables default features, so re-enable every -# modality (all-modalities: tabular/image/audio/document) plus JSON/CSV audit -# export. elide-pipeline re-exports every engine type this crate uses. +# Elide crates elide-pipeline = { workspace = true, features = [ "all-modalities", "audit-json", @@ -60,7 +58,7 @@ elide-pipeline = { workspace = true, features = [ ] } # Internal crates -nvisy-core = { workspace = true, features = ["schema"] } +nvisy-core = { workspace = true, features = ["schema", "oauth2"] } nvisy-nats = { workspace = true, features = [] } nvisy-assistant = { workspace = true, features = ["schema"] } nvisy-object-store = { workspace = true, features = ["schema"] } @@ -69,13 +67,21 @@ nvisy-postgres = { workspace = true, features = ["schema"] } nvisy-s3 = { workspace = true, features = [] } nvisy-webhook = { workspace = true, features = ["schema"] } +# CLI +clap = { workspace = true, features = ["derive", "env"], optional = true } + # Async runtime tokio = { workspace = true, features = [] } tokio-util = { workspace = true, features = ["io"] } futures = { workspace = true, features = [] } async-trait = { workspace = true, features = [] } async-stream = { workspace = true, features = [] } -pin-project-lite = { workspace = true, features = [] } + +# HTTP client & middleware +reqwest = { workspace = true, features = [] } + +# OAuth & OIDC +openidconnect = { workspace = true, features = [] } # HTTP server & middleware axum = { workspace = true, features = ["http2", "macros", "multipart"] } @@ -83,6 +89,7 @@ axum-client-ip = { workspace = true, features = [] } axum-extra = { workspace = true, features = ["typed-header", "attachment", "query", "cookie"] } tower = { workspace = true, features = [] } tower-http = { workspace = true, features = [] } +axum-test = { workspace = true, features = [], optional = true } # OpenAPI/Documentation aide = { workspace = true, features = ["axum", "axum-query", "axum-extra-query", "axum-form", "axum-json", "axum-multipart", "axum-extra", "bytes", "http"] } @@ -93,10 +100,9 @@ indexmap = { workspace = true, features = [] } jsonwebtoken = { workspace = true, features = [] } argon2 = { workspace = true, features = [] } zxcvbn = { workspace = true, features = [] } -sha2 = { workspace = true, features = [] } -openidconnect = { workspace = true, features = ["reqwest", "rustls-tls"] } # Encryption & Cryptography +sha2 = { workspace = true, features = [] } chacha20poly1305 = { workspace = true, features = [] } aead-stream = { workspace = true, features = ["alloc"] } hkdf = { workspace = true, features = [] } @@ -104,7 +110,7 @@ hkdf = { workspace = true, features = [] } # Encoding base64 = { workspace = true, features = ["std"] } hex = { workspace = true, features = [] } -mime_guess = { workspace = true } +mime_guess = { workspace = true, features = [] } # Randomness rand = { workspace = true, features = [] } @@ -112,56 +118,62 @@ rand = { workspace = true, features = [] } # Observability tracing = { workspace = true, features = [] } -# CLI -clap = { workspace = true, features = ["derive", "env"], optional = true } - # (De)serialization csv = { workspace = true, features = [] } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = [] } -bytes = { workspace = true, features = [] } -http-body = { workspace = true, features = [] } garde = { workspace = true, features = [] } # Text processing woothee = { workspace = true, features = [] } # Derive macros & utilities +pin-project-lite = { workspace = true, features = [] } +http-body = { workspace = true, features = [] } thiserror = { workspace = true, features = [] } derive_more = { workspace = true, features = ["full"] } strum = { workspace = true, features = ["derive"] } anyhow = { workspace = true, features = [] } # Primitive datatypes +bytes = { workspace = true, features = [] } uuid = { workspace = true, features = ["serde", "v4", "v7"] } jiff = { workspace = true, features = ["serde"] } time = { workspace = true, features = [] } -ipnet = { workspace = true, features = [] } # Image processing -image = { workspace = true } +image = { workspace = true, features = [] } # Cron parsing croner = { workspace = true, features = [] } chrono = { workspace = true, features = [] } # Domain datatypes & data structures +ipnet = { workspace = true, features = [] } url = { workspace = true, features = [] } -# Test-only harness dep (gated on the `test_util` feature). -axum-test = { workspace = true, features = [], optional = true } - [dev-dependencies] # Internal crates nvisy-nats = { workspace = true, features = [] } nvisy-postgres = { workspace = true, features = ["schema", "test_util"] } nvisy-webhook = { workspace = true, features = ["reqwest"] } -axum-test = { workspace = true, features = [] } -anyhow = { workspace = true, features = ["backtrace"] } -tempfile = { workspace = true, features = [] } +# CLI dotenvy = { workspace = true, features = [] } + +# Async runtime tokio = { workspace = true, features = ["macros", "rt"] } + +# HTTP server & middleware +axum-test = { workspace = true, features = [] } + +# Testing utilities +tempfile = { workspace = true, features = [] } + +# Derive macros & utilities +anyhow = { workspace = true, features = ["backtrace"] } + +# Primitive datatypes uuid = { workspace = true, features = ["v7"] } [lints] diff --git a/crates/nvisy-server/src/domain/account_notifications.rs b/crates/nvisy-server/src/domain/account_notifications.rs index d0b29088..4ff45938 100644 --- a/crates/nvisy-server/src/domain/account_notifications.rs +++ b/crates/nvisy-server/src/domain/account_notifications.rs @@ -3,9 +3,10 @@ //! Owns the read-status rules a handler would otherwise inline — marking one or //! all notifications read (scoped to the owning account) and broadcasting the //! resulting unread count so a watching badge updates live. The unread-count SSE -//! stream stays in the handler (it is transport), subscribing through the same -//! [`NotificationEmitter`]. +//! stream stays in the handler (it is transport), subscribing and re-reading +//! through this service. +use nvisy_nats::stream::BroadcastStream; use nvisy_postgres::PgClient; use nvisy_postgres::model::AccountNotification; use nvisy_postgres::query::AccountNotificationRepository; @@ -13,7 +14,7 @@ use nvisy_postgres::types::{CursorPage, CursorPagination, TimeCursor}; use uuid::Uuid; use crate::response::{Error, Resource, Result}; -use crate::service::NotificationEmitter; +use crate::service::{NotificationEmitter, UnreadCountEvent}; /// Tracing target for account notification domain operations. const TRACING_TARGET: &str = "nvisy_server::domain::account"; @@ -55,6 +56,18 @@ impl AccountNotificationService { .await?) } + /// Subscribes to the account's live unread-count broadcasts. + /// + /// # Errors + /// + /// - A NATS error if the subscription cannot be opened. + pub async fn subscribe_unread( + &self, + account_id: Uuid, + ) -> Result> { + self.emitter.subscribe_unread(account_id).await + } + /// Returns the account's unread notification count. /// /// # Errors diff --git a/crates/nvisy-server/src/domain/mod.rs b/crates/nvisy-server/src/domain/mod.rs index a7b0fe9d..036c3b1b 100644 --- a/crates/nvisy-server/src/domain/mod.rs +++ b/crates/nvisy-server/src/domain/mod.rs @@ -23,6 +23,7 @@ mod account_notifications; mod config; mod json; mod workspace_activities; +mod workspace_analytics; mod workspace_connection_syncs; mod workspace_connections; mod workspace_detections; @@ -41,6 +42,7 @@ pub use account_api_tokens::AccountApiTokenService; pub use account_identities::{AccountIdentityService, ReauthVerified}; pub use account_notifications::AccountNotificationService; pub use workspace_activities::{ActivityExport, WorkspaceActivityService}; +pub use workspace_analytics::WorkspaceAnalyticsService; pub use workspace_connection_syncs::{SyncRequest, WorkspaceConnectionSyncService}; pub use workspace_connections::WorkspaceConnectionService; pub use workspace_detections::WorkspaceDetectionService; diff --git a/crates/nvisy-server/src/domain/output/workspace_connections.rs b/crates/nvisy-server/src/domain/output/workspace_connections.rs index 53fbdc6a..0d95d986 100644 --- a/crates/nvisy-server/src/domain/output/workspace_connections.rs +++ b/crates/nvisy-server/src/domain/output/workspace_connections.rs @@ -1,5 +1,6 @@ //! Connection service outputs. +use nvisy_core::Secret; use nvisy_postgres::model::{ WorkspaceConnection as WorkspaceConnectionModel, WorkspaceConnectionSchedule, }; @@ -15,3 +16,23 @@ pub struct FoundConnection { /// When the connection last synced successfully, if ever. pub last_synced_at: Option, } + +/// The result of checking a connection against its backing store. +pub enum ConnectionCheck { + /// The store is reachable with the stored credentials. + Reachable, + /// The store could not be reached or rejected the credentials. + Unreachable { + /// A safe reason for the caller, naming no URL, bucket, or other + /// infrastructure detail. + reason: &'static str, + }, +} + +/// A short-lived provider access token for a browser file picker. +pub struct PickerToken { + /// The access token. + pub access_token: Secret, + /// Expiry as a Unix timestamp, if the provider reported one. + pub expires_at: Option, +} diff --git a/crates/nvisy-server/src/domain/workspace_analytics.rs b/crates/nvisy-server/src/domain/workspace_analytics.rs new file mode 100644 index 00000000..2b6d157a --- /dev/null +++ b/crates/nvisy-server/src/domain/workspace_analytics.rs @@ -0,0 +1,53 @@ +//! Workspace analytics domain logic: the dashboard snapshot and the daily +//! detection series. + +use jiff::Timestamp; +use nvisy_postgres::PgClient; +use nvisy_postgres::query::{AnalyticsSnapshot, DetectionDayPoint, WorkspaceAnalyticsRepository}; +use uuid::Uuid; + +use crate::response::Result; + +/// Reads a workspace's aggregate analytics. +/// +/// Holds the Postgres client, acquiring its own connection per call. Resolved per +/// request from [`ServiceState`]. +/// +/// [`ServiceState`]: crate::service::ServiceState +#[derive(Clone)] +pub struct WorkspaceAnalyticsService { + postgres: PgClient, +} + +impl WorkspaceAnalyticsService { + /// Creates a [`WorkspaceAnalyticsService`] over the Postgres client. + #[must_use] + pub fn new(postgres: PgClient) -> Self { + Self { postgres } + } + + /// A workspace's stored-file and detection-health snapshot. + /// + /// # Errors + /// + /// - A database error if the connection or query fails. + pub async fn snapshot(&self, workspace_id: Uuid) -> Result { + let mut conn = self.postgres.get_connection().await?; + Ok(conn.snapshot(workspace_id).await?) + } + + /// A workspace's detection activity per day between `from` and `to`. + /// + /// # Errors + /// + /// - A database error if the connection or query fails. + pub async fn detections_by_day( + &self, + workspace_id: Uuid, + from: Timestamp, + to: Timestamp, + ) -> Result> { + let mut conn = self.postgres.get_connection().await?; + Ok(conn.detections_by_day(workspace_id, from, to).await?) + } +} diff --git a/crates/nvisy-server/src/domain/workspace_connections.rs b/crates/nvisy-server/src/domain/workspace_connections.rs index 92c47345..8a64a01d 100644 --- a/crates/nvisy-server/src/domain/workspace_connections.rs +++ b/crates/nvisy-server/src/domain/workspace_connections.rs @@ -3,14 +3,14 @@ //! Holds the connection rules — endpoint-policy validation, sync-schedule //! validation and pairing, config encryption, and the config-replacement guard //! that a connection's provider is fixed at creation (carrying stored OAuth tokens -//! onto a replacement config) — in one place, factored out of the handler. The -//! service owns the crypto service and the endpoint policy. The external-store -//! actions (verify, picker token) stay in the handler; they load a connection -//! through [`find`]. -//! -//! [`find`]: WorkspaceConnectionService::find +//! onto a replacement config) — in one place, factored out of the handler — plus +//! the actions that reach a connection's backing store: verifying it, minting a +//! browser-picker token, and recording a connection authorized through OAuth. use nvisy_core::net::EndpointPolicy; +use nvisy_file_service::FileService; +use nvisy_file_service::oauth::OAuthTokens; +use nvisy_file_service::provider::FileServiceConfig; use nvisy_postgres::model::{NewWorkspaceConnection, WorkspaceConnectionSchedule}; use nvisy_postgres::query::{ WorkspaceConnectionRepository, WorkspaceConnectionScheduleRepository, @@ -22,10 +22,12 @@ use uuid::Uuid; use crate::domain::config::replace_config; use crate::domain::input::{CreateConnectionInput, UpdateConnectionInput}; -use crate::domain::output::FoundConnection; -use crate::response::{Error, Resource, Result}; +use crate::domain::output::{ConnectionCheck, FoundConnection, PickerToken}; +use crate::response::{Error, ErrorKind, Resource, Result}; use crate::service::event::EventEmitter; -use crate::service::{CryptoService, event}; +use crate::service::{ + ConnectionConfig, CryptoService, ExternalObjectStore, event, persist_refreshed_tokens, +}; /// Tracing target for connection domain operations. const TRACING_TARGET: &str = "nvisy_server::domain::connection"; @@ -33,8 +35,9 @@ const TRACING_TARGET: &str = "nvisy_server::domain::connection"; /// Creates, reads, updates, and deletes workspace connections. /// /// Holds the Postgres client (acquiring its own connection per call), the crypto -/// service (to encrypt and decrypt the connection config), and the endpoint policy -/// (to validate custom endpoints at write time). Resolved per request from +/// service (to encrypt and decrypt the connection config), the endpoint policy +/// (to validate custom endpoints), and the cloud file service (to reach and +/// refresh file-service connections). Resolved per request from /// [`ServiceState`]. /// /// [`ServiceState`]: crate::service::ServiceState @@ -43,16 +46,23 @@ pub struct WorkspaceConnectionService { postgres: PgClient, crypto: CryptoService, endpoint_policy: EndpointPolicy, + files: FileService, } impl WorkspaceConnectionService { /// Creates a [`WorkspaceConnectionService`] over its clients. #[must_use] - pub fn new(postgres: PgClient, crypto: CryptoService, endpoint_policy: EndpointPolicy) -> Self { + pub fn new( + postgres: PgClient, + crypto: CryptoService, + endpoint_policy: EndpointPolicy, + files: FileService, + ) -> Self { Self { postgres, crypto, endpoint_policy, + files, } } @@ -321,6 +331,175 @@ impl WorkspaceConnectionService { tracing::info!(target: TRACING_TARGET, "Connection deleted"); Ok(()) } + + /// Checks a connection against its backing store: an object store must be + /// reachable, a file service must accept its credentials (refreshed if + /// expired, with the refreshed tokens stored). + /// + /// The provider I/O runs with no pooled connection held: it reaches external + /// services with no total timeout, so holding one could exhaust the pool. + /// A failure is a [`ConnectionCheck::Unreachable`] with a safe reason; the + /// full error is only logged. + /// + /// # Errors + /// + /// - `NotFound` if the connection does not exist in the workspace. + /// - A crypto or database error if the config cannot be read, or refreshed + /// tokens cannot be stored. + pub async fn verify( + &self, + workspace_id: Uuid, + connection_id: ConnectionId, + ) -> Result { + let connection = self + .find(workspace_id, connection_id) + .await? + .connection + .item; + let config: ConnectionConfig = self + .crypto + .decrypt_json(workspace_id, &connection.encrypted_data)?; + + let checked = match config { + ConnectionConfig::ObjectStore(config) => { + match ExternalObjectStore::new(self.endpoint_policy) + .connect(&config) + .await + { + Ok(client) => client.verify_reachable().await, + Err(err) => Err(err), + } + } + ConnectionConfig::FileService(config) => match self.files.connect(&config).await { + Ok(connected) => { + // A refresh during verification produces fresh tokens; store + // them so the renewed credentials are not thrown away. + if let Some(refreshed) = connected.refreshed { + self.store_tokens(workspace_id, connection.id, refreshed.tokens().clone()) + .await?; + } + connected.client.verify().await + } + Err(err) => Err(err), + }, + }; + + Ok(match checked { + Ok(()) => { + tracing::info!(target: TRACING_TARGET, %connection_id, "Connection verified"); + ConnectionCheck::Reachable + } + Err(err) => { + tracing::warn!(target: TRACING_TARGET, %connection_id, error = %err, "Connection unreachable"); + ConnectionCheck::Unreachable { + reason: err.kind().reason(), + } + } + }) + } + + /// Mints a short-lived provider access token for a browser file picker, + /// scoped to `resource` when the picker names one (`OneDrive`). A refreshed + /// token set is stored; the refresh token never leaves the server. + /// + /// # Errors + /// + /// - `NotFound` if the connection does not exist in the workspace. + /// - `BadRequest` if the connection is inactive, is not a file service, or + /// its provider's picker uses a client-side app key. + /// - A provider, crypto, or database error if minting or storing fails. + pub async fn picker_token( + &self, + workspace_id: Uuid, + connection_id: ConnectionId, + resource: Option<&str>, + ) -> Result { + let connection = self + .find(workspace_id, connection_id) + .await? + .connection + .item; + if !connection.is_active { + return Err(ErrorKind::BadRequest.with_message("Connection is not active")); + } + + let config: ConnectionConfig = self + .crypto + .decrypt_json(workspace_id, &connection.encrypted_data)?; + let ConnectionConfig::FileService(config) = config else { + return Err(ErrorKind::BadRequest + .with_message("Picker tokens are only available for file services")); + }; + if !config.provider.picker_needs_user_token() { + return Err(ErrorKind::BadRequest.with_message( + "This provider's picker uses a client-side app key, not a server token", + )); + } + + let picker = self.files.mint_picker_token(&config, resource).await?; + if let Some(refreshed) = picker.refreshed { + self.store_tokens(workspace_id, connection.id, refreshed.tokens().clone()) + .await?; + } + Ok(PickerToken { + access_token: picker.access_token, + expires_at: picker.expires_at, + }) + } + + /// Records a file-service connection whose credentials an OAuth flow just + /// obtained, with its created event, in one transaction. A file service is + /// request-time only (picker-driven import, per-file export), so it gets no + /// schedule. + /// + /// # Errors + /// + /// - A crypto error if the config cannot be encrypted. + /// - A database error if the insert or the event fails. + pub async fn create_authorized( + &self, + origin: event::EventOrigin<'_>, + display_name: String, + config: FileServiceConfig, + ) -> Result { + let config = ConnectionConfig::FileService(config); + let new_connection = NewWorkspaceConnection { + workspace_id: origin.workspace_id, + account_id: origin.account_id, + display_name, + provider: config.provider_id().to_owned(), + connection_type: config.connection_type(), + encrypted_data: self.crypto.encrypt_json(origin.workspace_id, &config)?, + is_active: Some(true), + metadata: None, + }; + + let mut conn = self.postgres.get_connection().await?; + conn.transaction(async |conn| { + let connection = conn.create_workspace_connection(new_connection).await?; + conn.emit_event( + origin, + event::ConnectionCreated { + connection_id: connection.id, + connection_name: connection.display_name.clone(), + }, + ) + .await?; + Ok::<_, Error>(connection.id) + }) + .await + } + + /// Stores a connection's refreshed OAuth tokens. + async fn store_tokens( + &self, + workspace_id: Uuid, + connection_id: Uuid, + tokens: OAuthTokens, + ) -> Result<()> { + let mut conn = self.postgres.get_connection().await?; + persist_refreshed_tokens(&mut conn, &self.crypto, workspace_id, connection_id, tokens).await + } } /// Finds a connection within a workspace by id, with its creator, schedule, and diff --git a/crates/nvisy-server/src/domain/workspace_detections.rs b/crates/nvisy-server/src/domain/workspace_detections.rs index 94424698..7b879871 100644 --- a/crates/nvisy-server/src/domain/workspace_detections.rs +++ b/crates/nvisy-server/src/domain/workspace_detections.rs @@ -15,6 +15,7 @@ use elide_pipeline::entity::EditSet; use elide_pipeline::governance::policy::Policy; use elide_pipeline::provider::DocumentContext; +use elide_pipeline::{ArtifactSet, Audit}; use nvisy_postgres::model::{ NewWorkspaceDetection, NewWorkspaceDetectionJob, WorkspaceDetection as WorkspaceDetectionModel, }; @@ -287,6 +288,57 @@ impl WorkspaceDetectionService { .ok_or_else(|| Error::not_found(Resource::Detection)) } + /// Loads a detection's audit: the analyzed document with every finding. + /// + /// The audit's blob row is resolved on a connection released before the + /// object-store load, so no pooled connection is held across it. + /// + /// # Errors + /// + /// - `NotFound` if the detection does not exist in the workspace. + /// - `Conflict` if the detection has no audit yet. + /// - A database, storage, or decoding error if loading it fails. + pub async fn audit(&self, workspace_id: Uuid, detection_id: Uuid) -> Result { + let detection = self.find(workspace_id, detection_id).await?; + let blob = { + let mut conn = self.postgres.get_connection().await?; + self.reader + .resolve_audit_blob(&mut conn, &detection) + .await? + }; + self.reader + .load_audit(&self.engine, workspace_id, &blob) + .await + } + + /// Loads a detection's enrichment intermediates (an image's OCR layout, an + /// audio transcript, tokenized text). + /// + /// The intermediates' blob row is resolved on a connection released before + /// the object-store load, so no pooled connection is held across it. + /// + /// # Errors + /// + /// - `NotFound` if the detection does not exist in the workspace, or its + /// analysis ran no enricher. + /// - A database, storage, or decoding error if loading them fails. + pub async fn intermediates( + &self, + workspace_id: Uuid, + detection_id: Uuid, + ) -> Result { + let detection = self.find(workspace_id, detection_id).await?; + let blob = { + let mut conn = self.postgres.get_connection().await?; + self.reader + .resolve_intermediates_blob(&mut conn, &detection) + .await? + }; + self.reader + .load_intermediates(&self.engine, workspace_id, &blob) + .await + } + /// Persists a detection's accumulated reviewer edits (`edit_set`) under an /// optimistic-concurrency guard, the manual corrections layered over the base /// analysis at redact time. Passing `None` clears them. `expected_rev` is the diff --git a/crates/nvisy-server/src/handler/account_identities.rs b/crates/nvisy-server/src/handler/account_identities.rs index 181ad20c..318f7494 100644 --- a/crates/nvisy-server/src/handler/account_identities.rs +++ b/crates/nvisy-server/src/handler/account_identities.rs @@ -3,7 +3,7 @@ //! //! An account authenticates through one or more identities — a local password //! and/or linked OIDC providers — and this module manages them uniformly under -//! the singular `/account/` self-resource: +//! the singular `/account` self-resource: //! //! - `GET /account/identities` — list the account's sign-in methods. //! - `PUT /account/identities/password` — set or change the password. @@ -178,8 +178,8 @@ fn unlink_provider_docs(op: TransformOperation) -> TransformOperation { /// Returns the authenticated account-identity routes. /// -/// Mounted under the singular `/account/` self-resource (matching `/account/` -/// for the profile), not the plural `/accounts/{accountId}/` collection that +/// Mounted under the singular `/account` self-resource (matching `/account` +/// for the profile), not the plural `/accounts/{accountId}` collection that /// addresses other accounts — the identity is always the authenticated caller's. pub fn routes() -> ApiRouter { ApiRouter::new() diff --git a/crates/nvisy-server/src/handler/account_notifications.rs b/crates/nvisy-server/src/handler/account_notifications.rs index bde29f0e..4e1a32fd 100644 --- a/crates/nvisy-server/src/handler/account_notifications.rs +++ b/crates/nvisy-server/src/handler/account_notifications.rs @@ -11,8 +11,6 @@ use async_stream::stream; use axum::extract::State; use axum::http::StatusCode; use axum::response::sse::Event; -use nvisy_postgres::PgClient; -use nvisy_postgres::query::AccountNotificationRepository; use tokio_util::sync::CancellationToken; use uuid::Uuid; @@ -23,7 +21,7 @@ use crate::handler::response::{ AccountMarkedReadStatus, AccountNotification, AccountNotificationsPage, AccountUnreadStatus, }; use crate::response::{ErrorResponse, Result, SseResponse, Watch, sse_event, watch}; -use crate::service::{NotificationEmitter, ServiceState, UnreadCountEvent}; +use crate::service::{ServiceState, UnreadCountEvent}; /// Tracing target for notification operations. const TRACING_TARGET: &str = "nvisy_server::handler::account_notifications"; @@ -113,8 +111,7 @@ const UNREAD_POLL_INTERVAL: Duration = Duration::from_secs(30); /// `Authorization` header. #[tracing::instrument(skip_all)] async fn stream_unread_status( - State(pg_client): State, - State(notification_emitter): State, + State(notifications): State, State(shutdown): State, auth_state: AuthState, ) -> Result> { @@ -125,11 +122,9 @@ async fn stream_unread_status( // Subscribe BEFORE reading the current count: core-NATS broadcasts are not // replayed, so a change published between the read and the subscription going // live would otherwise be missed until the next change. - let mut updates = notification_emitter.subscribe_unread(account_id).await?; + let mut updates = notifications.subscribe_unread(account_id).await?; - let mut conn = pg_client.get_connection().await?; - let current = conn.count_unread_account_notifications(account_id).await?; - drop(conn); + let current = notifications.unread_count(account_id).await?; let stream = stream! { // Emit the current count first so a client that connects between changes @@ -141,7 +136,7 @@ async fn stream_unread_status( match watched { Watch::Live(event) => yield unread_event(event), Watch::Reread | Watch::Closed => { - if let Some(unread_count) = reread_unread_count(&pg_client, account_id).await { + if let Some(unread_count) = reread_unread_count(¬ifications, account_id).await { yield unread_event(UnreadCountEvent { unread_count }); } if closed { @@ -157,9 +152,11 @@ async fn stream_unread_status( /// Re-reads an account's unread count from the database, returning `None` if the /// count can no longer be read (a transient error — the next poll retries). -async fn reread_unread_count(pg_client: &PgClient, account_id: Uuid) -> Option { - let mut conn = pg_client.get_connection().await.ok()?; - match conn.count_unread_account_notifications(account_id).await { +async fn reread_unread_count( + notifications: &AccountNotificationService, + account_id: Uuid, +) -> Option { + match notifications.unread_count(account_id).await { Ok(count) => Some(count), Err(err) => { tracing::debug!(target: TRACING_TARGET, error = %err, %account_id, "Failed to re-read unread count"); diff --git a/crates/nvisy-server/src/handler/accounts.rs b/crates/nvisy-server/src/handler/accounts.rs index 829b70d7..52dcc33c 100644 --- a/crates/nvisy-server/src/handler/accounts.rs +++ b/crates/nvisy-server/src/handler/accounts.rs @@ -50,7 +50,7 @@ fn get_own_account_docs(op: TransformOperation) -> TransformOperation { /// The requester must share at least one workspace with the target account; /// otherwise the account is reported as not found. Only public fields are /// returned — private details (email) are available solely through the -/// caller's own `/account/` view. +/// caller's own `/account` view. #[tracing::instrument( skip_all, fields( diff --git a/crates/nvisy-server/src/handler/analytics.rs b/crates/nvisy-server/src/handler/analytics.rs index 5383d9e8..701cb028 100644 --- a/crates/nvisy-server/src/handler/analytics.rs +++ b/crates/nvisy-server/src/handler/analytics.rs @@ -4,9 +4,8 @@ use aide::axum::ApiRouter; use aide::transform::TransformOperation; use axum::extract::State; -use nvisy_postgres::PgClient; -use nvisy_postgres::query::WorkspaceAnalyticsRepository; +use crate::domain::WorkspaceAnalyticsService; use crate::extract::{Authorized, Json, Query, markers}; use crate::handler::ServiceState; use crate::handler::request::DateWindow; @@ -19,18 +18,13 @@ const TRACING_TARGET: &str = "nvisy_server::handler::analytics"; /// Returns aggregate analytics for a workspace. #[tracing::instrument(skip_all)] async fn get_analytics( - State(pg_client): State, + State(analytics): State, authz: Authorized, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Computing workspace analytics"); - let mut conn = pg_client.get_connection().await?; - - let snapshot = conn.snapshot(authz.workspace.id).await?; - - let analytics = WorkspaceAnalytics::from_snapshot(snapshot); - - Ok(Json(analytics)) + let snapshot = analytics.snapshot(authz.workspace.id).await?; + Ok(Json(WorkspaceAnalytics::from_snapshot(snapshot))) } fn get_analytics_docs(op: TransformOperation) -> TransformOperation { @@ -44,7 +38,7 @@ fn get_analytics_docs(op: TransformOperation) -> TransformOperation { /// Returns a workspace's daily detection activity over a date window. #[tracing::instrument(skip_all)] async fn get_detection_timeseries( - State(pg_client): State, + State(analytics): State, authz: Authorized, Query(window): Query, ) -> Result> { @@ -52,9 +46,7 @@ async fn get_detection_timeseries( let window = window.resolve()?; - let mut conn = pg_client.get_connection().await?; - - let points = conn + let points = analytics .detections_by_day( authz.workspace.id, window.from_timestamp()?, diff --git a/crates/nvisy-server/src/handler/auth_oidc.rs b/crates/nvisy-server/src/handler/auth_oidc.rs index cc4076c8..374ce756 100644 --- a/crates/nvisy-server/src/handler/auth_oidc.rs +++ b/crates/nvisy-server/src/handler/auth_oidc.rs @@ -40,9 +40,6 @@ use aide::transform::TransformOperation; use axum::extract::State; use axum::response::{IntoResponse, Response}; use axum::routing::get; -use nvisy_postgres::PgClient; -use nvisy_postgres::query::AccountApiTokenRepository; -use nvisy_postgres::types::ApiTokenType; use crate::extract::{AuthState, Json, Path, Query, SecurityContext, ValidateJson}; use crate::handler::request::{ @@ -51,8 +48,7 @@ use crate::handler::request::{ use crate::handler::response::{AccountDesktopToken, AuthorizeRedirect}; use crate::response::{CookieConfig, ErrorKind, ErrorResponse, RedirectResult, Result, WebSession}; use crate::service::{ - AccountProvisioner, AuthIssuer, CallbackOutcome, OidcPurpose, OidcService, RedirectKind, - ServiceState, + CallbackOutcome, OidcPurpose, OidcService, RedirectKind, ServiceState, SignInService, }; /// Tracing target for OIDC sign-in operations. @@ -204,10 +200,8 @@ fn start_reauth_docs(op: TransformOperation) -> TransformOperation { /// mint a token for their own account. No cookie is set on the response. #[tracing::instrument(skip_all)] async fn mint_desktop_token( - State(pg_client): State, State(oidc): State, - State(issuer): State, - State(provisioner): State, + State(sign_in): State, auth_state: AuthState, security: SecurityContext, ValidateJson(request): ValidateJson, @@ -223,28 +217,8 @@ async fn mint_desktop_token( ); } - let mut conn = pg_client.get_connection().await?; - - // Only a browser (`web`) session may mint a desktop token: the desktop login - // completes in the browser first. Rejecting `app`/`api` tokens stops a leaked - // long-lived `app` token from renewing itself indefinitely by minting fresh - // `app` tokens. - let session = conn - .find_account_api_token_by_id(auth_state.token_id) - .await? - .ok_or_else(|| ErrorKind::Unauthorized.with_message("Session not found"))?; - if session.session_type != ApiTokenType::Web { - return Err(ErrorKind::Forbidden - .with_message("Desktop tokens can only be minted from a browser session")); - } - - let account = provisioner - .load_active(&mut conn, auth_state.account_id) - .await?; - AccountProvisioner::ensure_can_sign_in(&account)?; - - let api_token = issuer - .issue_app_token(&mut conn, &account, security) + let api_token = sign_in + .issue_desktop_token(auth_state.account_id, auth_state.token_id, security) .await?; Ok(Json(AccountDesktopToken { diff --git a/crates/nvisy-server/src/handler/capabilities.rs b/crates/nvisy-server/src/handler/capabilities.rs index d8a9dbbe..b94677a7 100644 --- a/crates/nvisy-server/src/handler/capabilities.rs +++ b/crates/nvisy-server/src/handler/capabilities.rs @@ -228,7 +228,7 @@ mod tests { }), ..Default::default() }; - let file_service = FileService::new(apps).unwrap(); + let file_service = FileService::new(&apps).unwrap(); let providers = FileProviders::from_service(&file_service); diff --git a/crates/nvisy-server/src/handler/connection_oauth.rs b/crates/nvisy-server/src/handler/connection_oauth.rs index 1e657951..b92d0ffa 100644 --- a/crates/nvisy-server/src/handler/connection_oauth.rs +++ b/crates/nvisy-server/src/handler/connection_oauth.rs @@ -20,6 +20,7 @@ //! [`create_connection`]: super::connections use std::str::FromStr; +use std::time::Duration; use aide::axum::ApiRouter; use aide::axum::routing::post_with; @@ -30,19 +31,16 @@ use axum::routing::get; use nvisy_file_service::FileService; use nvisy_file_service::provider::{ConnectionSettings, FileServiceConfig, FileServiceProvider}; use nvisy_nats::NatsClient; -use nvisy_nats::kv::{OAuthStateBucket as OAuthStateKvBucket, OAuthStateKey}; -use nvisy_postgres::model::NewWorkspaceConnection; -use nvisy_postgres::query::WorkspaceConnectionRepository; -use nvisy_postgres::{AsyncConnection, PgClient}; +use nvisy_nats::kv::TokenKey; use serde::{Deserialize, Serialize}; use uuid::Uuid; +use crate::domain::WorkspaceConnectionService; use crate::extract::{Authorized, Json, Path, Query, SecurityContext, ValidateJson, markers}; use crate::handler::request::{OAuthCallbackQuery, OAuthStartPathParams, StartFileServiceOAuth}; use crate::handler::response::AuthorizeRedirect; -use crate::response::{Error, ErrorKind, Result, connection_result_redirect}; -use crate::service::event::EventEmitter; -use crate::service::{ConnectionConfig, CryptoService, FileServiceRedirect, ServiceState, event}; +use crate::response::{ErrorKind, Result, connection_result_redirect}; +use crate::service::{FileServiceRedirect, ServiceState, event}; /// Tracing target for connection OAuth operations. const TRACING_TARGET: &str = "nvisy_server::handler::connection_oauth"; @@ -50,7 +48,7 @@ const TRACING_TARGET: &str = "nvisy_server::handler::connection_oauth"; /// The stashed state of an in-flight OAuth authorization, held between `start` /// and `callback` in the [`OAuthStateBucket`]. Keyed by the CSRF state token. #[derive(Debug, Clone, Serialize, Deserialize)] -struct OAuthFlowState { +pub(crate) struct OAuthFlowState { /// Workspace the connection will be created in. workspace_id: Uuid, /// The workspace's handle, carried so the post-auth redirect can substitute a @@ -68,10 +66,17 @@ struct OAuthFlowState { pkce_verifier: String, } -/// The OAuth-state bucket pinned to this server's flow-state value. The bucket's -/// static config (name, TTL, key) lives in the NATS layer; this alias fixes the -/// value type once so call sites need only name the bucket. -type OAuthStateBucket = OAuthStateKvBucket; +nvisy_nats::kv_bucket! { + /// In-flight OAuth authorization state (CSRF token and PKCE verifier), held + /// between starting an authorization and its callback, keyed by the state + /// token the provider echoes back. Short-lived: a user finishes the consent + /// screen within minutes, and an abandoned flow's state should not linger. + pub(crate) OAuthStateBucket: OAuthFlowState { + name: "oauth_state", + description: "In-flight OAuth authorization state", + ttl: Duration::from_mins(10), + } +} /// The result of a completed OAuth callback: the connection that was created and /// the workspace it belongs to (used to build the post-auth redirect). @@ -97,7 +102,7 @@ async fn start_oauth( tracing::debug!(target: TRACING_TARGET, "Starting cloud file OAuth"); let provider = path_params.provider; - let authorization = cloud.oauth_client(provider)?.begin_authorization()?; + let authorization = cloud.oauth_client(provider)?.begin_authorization(); let flow = OAuthFlowState { workspace_id: authz.workspace.id, @@ -110,7 +115,7 @@ async fn start_oauth( }; let store = nats.kv_store::().await?; store - .put(&authorization.csrf_state.parse::()?, &flow) + .put(&authorization.csrf_state.parse::()?, &flow) .await?; Ok(Json(AuthorizeRedirect { @@ -132,9 +137,8 @@ fn start_oauth_docs(op: TransformOperation) -> TransformOperation { /// here with the code and state. #[tracing::instrument(skip_all)] async fn oauth_callback( - State(pg_client): State, + State(connections): State, State(nats): State, - State(crypto): State, State(cloud): State, State(redirect): State, security: SecurityContext, @@ -144,7 +148,7 @@ async fn oauth_callback( // The callback is a top-level browser navigation, so its outcome is conveyed // by a redirect back to the frontend rather than a response body. - let outcome = complete_callback(&pg_client, &nats, &crypto, &cloud, &security, query).await; + let outcome = complete_callback(&connections, &nats, &cloud, &security, query).await; let (status, workspace_handle) = match outcome { Ok(outcome) => { tracing::info!( @@ -166,16 +170,15 @@ async fn oauth_callback( /// code, and create the connection. Returns the new connection id and the /// workspace handle (for the post-auth redirect) on success. async fn complete_callback( - pg_client: &PgClient, + connections: &WorkspaceConnectionService, nats: &NatsClient, - crypto: &CryptoService, cloud: &FileService, security: &SecurityContext, query: OAuthCallbackQuery, ) -> Result { // Validate the state before touching the store so a malformed value maps to // a clean BadRequest rather than a KV error. - let key = OAuthStateKey::from_str(&query.state) + let key = TokenKey::from_str(&query.state) .map_err(|_| ErrorKind::BadRequest.with_message("Invalid authorization state"))?; // Consume the pending authorization atomically, so of two concurrent @@ -207,45 +210,17 @@ async fn complete_callback( tokens, root: flow.root, }; - let config = ConnectionConfig::FileService(FileServiceConfig::new(flow.provider, settings)); - let provider = config.provider_id().to_owned(); - let connection_type = config.connection_type(); - let encrypted_data = crypto.encrypt_json(flow.workspace_id, &config)?; - - let new_connection = NewWorkspaceConnection { + let origin = event::EventOrigin { workspace_id: flow.workspace_id, account_id: flow.account_id, - display_name: flow.display_name, - provider, - connection_type, - encrypted_data, - is_active: Some(true), - metadata: None, + security, }; - - // Insert the connection and the outbox event atomically. A file service is - // request-time only — its import is picker-driven and its export per file, - // neither scheduled — so it gets no schedule row (scheduling is an - // object-store concept). Transfer capability comes from its provider_type. - // The requester's security context comes from the callback request itself. - let mut conn = pg_client.get_connection().await?; - let connection_id = conn - .transaction(async |conn| { - let connection = conn.create_workspace_connection(new_connection).await?; - conn.emit_event( - event::EventOrigin { - workspace_id: flow.workspace_id, - account_id: flow.account_id, - security, - }, - event::ConnectionCreated { - connection_id: connection.id, - connection_name: connection.display_name.clone(), - }, - ) - .await?; - Ok::<_, Error>(connection.id) - }) + let connection_id = connections + .create_authorized( + origin, + flow.display_name, + FileServiceConfig::new(flow.provider, settings), + ) .await?; Ok(CallbackOutcome { diff --git a/crates/nvisy-server/src/handler/detection_audits.rs b/crates/nvisy-server/src/handler/detection_audits.rs index 8c531ef5..84c9f0d5 100644 --- a/crates/nvisy-server/src/handler/detection_audits.rs +++ b/crates/nvisy-server/src/handler/detection_audits.rs @@ -17,14 +17,13 @@ use axum::extract::State; use axum::http::{HeaderMap, HeaderValue}; use elide_pipeline::export::{ExportCsv, ExportJson}; use elide_pipeline::{ArtifactSet, Audit}; -use nvisy_postgres::PgClient; use crate::domain; use crate::extract::{Authorized, Json, Path, Query, markers}; use crate::handler::request::{ExportFormat, ExportQuery, WorkspaceDetectionPathParams}; use crate::handler::utility::DownloadDocs; use crate::response::{Error, ErrorKind, ErrorResponse, Result, attachment_headers}; -use crate::service::{ArtifactReader, EngineService, ServiceState}; +use crate::service::ServiceState; /// Tracing target for detection audit operations. const TRACING_TARGET: &str = "nvisy_server::handler::detection_audits"; @@ -40,29 +39,15 @@ const TRACING_TARGET: &str = "nvisy_server::handler::detection_audits"; ) )] async fn get_detection_analysis( - State(pg_client): State, State(detections): State, - State(blob): State, - State(engine): State, authz: Authorized, Path(path_params): Path, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Getting detection analysis"); - let workspace = &authz.workspace; - - // Resolve the detection through the service, then resolve its audit file row on - // a scoped connection released before the object-store load below so the pooled - // connection is not held across the NATS round-trip. - let detection = detections - .find(workspace.id, path_params.detection_id.as_uuid()) + let analyzed = detections + .audit(authz.workspace.id, path_params.detection_id.as_uuid()) .await?; - let audit_blob = { - let mut conn = pg_client.get_connection().await?; - blob.resolve_audit_blob(&mut conn, &detection).await? - }; - - let analyzed = blob.load_audit(&engine, workspace.id, &audit_blob).await?; tracing::debug!(target: TRACING_TARGET, "Detection analysis retrieved"); @@ -93,32 +78,14 @@ fn get_detection_analysis_docs(op: TransformOperation) -> TransformOperation { ) )] async fn get_detection_intermediates( - State(pg_client): State, State(detections): State, - State(blob): State, - State(engine): State, authz: Authorized, Path(path_params): Path, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Getting detection intermediates"); - let workspace = &authz.workspace; - - // Resolve the detection through the service, then resolve its intermediates - // file row on a scoped connection released before the object-store load so the - // pooled connection is not held across the NATS round-trip. - let detection = detections - .find(workspace.id, path_params.detection_id.as_uuid()) - .await?; - let intermediates_blob = { - let mut conn = pg_client.get_connection().await?; - - blob.resolve_intermediates_blob(&mut conn, &detection) - .await? - }; - - let intermediates = blob - .load_intermediates(&engine, workspace.id, &intermediates_blob) + let intermediates = detections + .intermediates(authz.workspace.id, path_params.detection_id.as_uuid()) .await?; tracing::debug!(target: TRACING_TARGET, "Detection intermediates retrieved"); @@ -155,29 +122,15 @@ fn get_detection_intermediates_docs(op: TransformOperation) -> TransformOperatio ) )] async fn download_detection_audit( - State(pg_client): State, State(detections): State, - State(blob): State, - State(engine): State, authz: Authorized, Path(path_params): Path, Query(query): Query, ) -> Result<(HeaderMap, Body)> { tracing::debug!(target: TRACING_TARGET, "Downloading detection audit"); - let workspace = &authz.workspace; - - // Resolve the detection through the service, then resolve its audit file row on - // a scoped connection released before the object-store load below so the pooled - // connection is not held across the NATS round-trip. let detection_id = path_params.detection_id.as_uuid(); - let detection = detections.find(workspace.id, detection_id).await?; - let audit_blob = { - let mut conn = pg_client.get_connection().await?; - blob.resolve_audit_blob(&mut conn, &detection).await? - }; - - let audit = blob.load_audit(&engine, workspace.id, &audit_blob).await?; + let audit = detections.audit(authz.workspace.id, detection_id).await?; let (content_type, filename, body) = match query.format { ExportFormat::Json => { diff --git a/crates/nvisy-server/src/handler/mod.rs b/crates/nvisy-server/src/handler/mod.rs index 2140a899..c0a808e4 100644 --- a/crates/nvisy-server/src/handler/mod.rs +++ b/crates/nvisy-server/src/handler/mod.rs @@ -40,6 +40,7 @@ use axum::middleware::{from_fn, from_fn_with_state}; use axum::response::{IntoResponse, Response}; pub use utility::CustomRoutes; +pub(crate) use self::connection_oauth::OAuthStateBucket; use crate::middleware::{csrf_protect, require_authentication, slide_session}; use crate::response::ErrorKind; use crate::service::ServiceState; diff --git a/crates/nvisy-server/src/handler/response/accounts.rs b/crates/nvisy-server/src/handler/response/accounts.rs index eae81113..8099b793 100644 --- a/crates/nvisy-server/src/handler/response/accounts.rs +++ b/crates/nvisy-server/src/handler/response/accounts.rs @@ -57,7 +57,7 @@ impl Account { /// Public view of an account, returned when looking up someone other than the /// authenticated caller. Carries only the fields safe to share with a /// workspace peer; private details (email, account flags) are omitted -/// and remain available solely through the caller's own `/account/` view. +/// and remain available solely through the caller's own `/account` view. #[must_use] #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] diff --git a/crates/nvisy-server/src/handler/workspace_connections.rs b/crates/nvisy-server/src/handler/workspace_connections.rs index 256ef7e1..dca380aa 100644 --- a/crates/nvisy-server/src/handler/workspace_connections.rs +++ b/crates/nvisy-server/src/handler/workspace_connections.rs @@ -22,10 +22,9 @@ use aide::transform::TransformOperation; use axum::extract::State; use axum::http::header::CACHE_CONTROL; use axum::http::{HeaderMap, HeaderValue, StatusCode}; -use nvisy_file_service::FileService; -use nvisy_postgres::PgClient; use crate::domain; +use crate::domain::output::ConnectionCheck; use crate::extract::{Authorized, Json, Path, Query, ValidateJson, markers}; use crate::handler::request::{ CreateWorkspaceConnection, CursorPagination, UpdateWorkspaceConnection, @@ -35,10 +34,8 @@ use crate::handler::response::{ WorkspaceConnection, WorkspaceConnectionVerification, WorkspaceConnectionsPage, WorkspacePickerToken, WorkspaceRef, }; -use crate::response::{ErrorKind, Result}; -use crate::service::{ - ConnectionConfig, CryptoService, ExternalObjectStore, ServiceState, persist_refreshed_tokens, -}; +use crate::response::Result; +use crate::service::ServiceState; /// Tracing target for workspace connection operations. const TRACING_TARGET: &str = "nvisy_server::handler::workspace_connections"; @@ -238,88 +235,21 @@ fn delete_connection_docs(op: TransformOperation) -> TransformOperation { ) )] async fn verify_connection( - State(pg_client): State, State(connections): State, - State(crypto): State, - State(object): State, - State(cloud): State, authz: Authorized, Path(path_params): Path, ) -> Result> { tracing::debug!(target: TRACING_TARGET, "Verifying workspace connection"); - let workspace = &authz.workspace; - - // Load the connection through the service, then run the provider I/O below - // with no pooled connection held: `connect`/`verify` reach external services - // with no total timeout, so holding one could exhaust the pool. - let connection = connections - .find(workspace.id, path_params.connection_id) - .await? - .connection - .item; - - let config: ConnectionConfig = crypto.decrypt_json(workspace.id, &connection.encrypted_data)?; - - // Verification is capability-specific: object stores check reachability; - // inference providers verify their credentials. - let verification = match config { - ConnectionConfig::ObjectStore(config) => match object.connect(&config).await { - Ok(client) => match client.verify_reachable().await { - Ok(()) => { - tracing::info!(target: TRACING_TARGET, "Connection verified"); - WorkspaceConnectionVerification::reachable() - } - Err(err) => { - // Log the full error, but return only a safe kind-based reason - // so backend URLs/bucket names are not exposed to the client. - tracing::warn!(target: TRACING_TARGET, error = %err, "Connection unreachable"); - WorkspaceConnectionVerification::unreachable(err.kind().reason()) - } - }, - Err(err) => { - tracing::warn!(target: TRACING_TARGET, error = %err, "Connection setup failed"); - WorkspaceConnectionVerification::unreachable(err.kind().reason()) - } - }, - ConnectionConfig::FileService(config) => match cloud.connect(&config).await { - Ok(connected) => { - // A refresh during verification produces fresh tokens; persist - // them so the renewed credentials are not thrown away. Acquire a - // connection only for this write and release it before the - // provider `verify` I/O below. - if let Some(refreshed) = connected.refreshed { - let mut conn = pg_client.get_connection().await?; - persist_refreshed_tokens( - &mut conn, - &crypto, - workspace.id, - connection.id, - refreshed.tokens().clone(), - ) - .await?; - } - match connected.client.verify().await { - Ok(()) => { - tracing::info!(target: TRACING_TARGET, "Connection verified"); - WorkspaceConnectionVerification::reachable() - } - Err(err) => { - tracing::warn!(target: TRACING_TARGET, error = %err, "Connection unreachable"); - WorkspaceConnectionVerification::unreachable(err.kind().reason()) - } - } - } - Err(err) => { - tracing::warn!(target: TRACING_TARGET, error = %err, "Connection setup failed"); - WorkspaceConnectionVerification::unreachable( - "credentials rejected or provider unreachable", - ) - } - }, - }; - - Ok(Json(verification)) + let check = connections + .verify(authz.workspace.id, path_params.connection_id) + .await?; + Ok(Json(match check { + ConnectionCheck::Reachable => WorkspaceConnectionVerification::reachable(), + ConnectionCheck::Unreachable { reason } => { + WorkspaceConnectionVerification::unreachable(reason) + } + })) } fn verify_connection_docs(op: TransformOperation) -> TransformOperation { @@ -345,10 +275,7 @@ fn verify_connection_docs(op: TransformOperation) -> TransformOperation { ) )] async fn mint_picker_token( - State(pg_client): State, State(connections): State, - State(crypto): State, - State(cloud): State, authz: Authorized, Path(path_params): Path, // Optional body: a picker that names a resource per `authenticate` command @@ -358,50 +285,13 @@ async fn mint_picker_token( tracing::debug!(target: TRACING_TARGET, "Minting picker token"); let resource = request.and_then(|ValidateJson(body)| body.resource); - let workspace = &authz.workspace; - - // Load the connection through the service, then run the provider token refresh - // below with no pooled connection held (it reaches the provider with no total - // timeout). - let connection = connections - .find(workspace.id, path_params.connection_id) - .await? - .connection - .item; - - if !connection.is_active { - return Err(ErrorKind::BadRequest.with_message("Connection is not active")); - } - - let config: ConnectionConfig = crypto.decrypt_json(workspace.id, &connection.encrypted_data)?; - let ConnectionConfig::FileService(config) = config else { - return Err(ErrorKind::BadRequest - .with_message("Picker tokens are only available for file services")); - }; - if !config.provider.picker_needs_user_token() { - return Err(ErrorKind::BadRequest.with_message( - "This provider's picker uses a client-side app key, not a server token", - )); - } - - // Mint the picker access token for the requested resource. The provider layer - // decides what the picker needs (OneDrive: a SharePoint-audience token; Drive - // and Box: the ordinary provider token). The refresh token never leaves the - // server; a rotated refresh token comes back for persistence. - let picker = cloud - .mint_picker_token(&config, resource.as_deref()) - .await?; - if let Some(refreshed) = picker.refreshed { - let mut conn = pg_client.get_connection().await?; - persist_refreshed_tokens( - &mut conn, - &crypto, - workspace.id, - connection.id, - refreshed.tokens().clone(), + let picker = connections + .picker_token( + authz.workspace.id, + path_params.connection_id, + resource.as_deref(), ) .await?; - } // The response carries a bearer credential; keep it out of any cache. let mut headers = HeaderMap::new(); diff --git a/crates/nvisy-server/src/response/error/nats_error.rs b/crates/nvisy-server/src/response/error/nats_error.rs index a0a6fb1c..a9c85ee1 100644 --- a/crates/nvisy-server/src/response/error/nats_error.rs +++ b/crates/nvisy-server/src/response/error/nats_error.rs @@ -17,87 +17,24 @@ impl From for HttpError { } impl From for HttpError { - fn from(nats_error: nvisy_nats::Error) -> Self { - match nats_error { - // Connection and network errors -> Service Unavailable (transient, - // retryable; the messaging backend is momentarily unreachable). - nvisy_nats::Error::Connection(_) => ErrorKind::ServiceUnavailable - .with_message("Service temporarily unavailable") - .with_context("Unable to connect to messaging service"), - - nvisy_nats::Error::Timeout { .. } => ErrorKind::InternalServerError - .with_message("Request timed out") - .with_context("Operation took too long to complete"), - - nvisy_nats::Error::DeliveryFailed { ref subject, .. } => ErrorKind::InternalServerError - .with_message("Message delivery failed") - .with_context(format!("Failed to deliver message to {subject}")), - - // Serialization is an internal encode/decode fault, not a client - // input error: the caller cannot influence how we frame NATS payloads. - nvisy_nats::Error::Serialization(_) => ErrorKind::InternalServerError - .with_message("Invalid request or response data format") - .with_context("Failed to serialize data for storage"), - - // A bad messaging configuration is a server-side fault, not a client - // error. - nvisy_nats::Error::InvalidConfig { .. } => ErrorKind::InternalServerError - .with_message("Invalid configuration") - .with_context("Service configuration is invalid"), - - // Not found errors -> Not Found - nvisy_nats::Error::KvKeyNotFound { ref bucket, .. } => ErrorKind::NotFound - .with_message("Resource not found") - .with_context(format!("Key not found in storage bucket '{bucket}'")), - - nvisy_nats::Error::KvBucketNotFound { .. } => ErrorKind::NotFound - .with_message("Storage bucket not found") - .with_context("The requested storage bucket does not exist"), - - // Revision conflicts -> Conflict - nvisy_nats::Error::KvRevisionMismatch { .. } => ErrorKind::Conflict - .with_message("Resource has been modified") - .with_context("The resource was modified by another request"), - - // JetStream and streaming errors -> Internal Server Error - nvisy_nats::Error::JetstreamPublish(_) => ErrorKind::InternalServerError - .with_message("Failed to publish message") - .with_context("Unable to publish to JetStream"), - - nvisy_nats::Error::JetstreamMessage(_) => ErrorKind::InternalServerError - .with_message("Message processing failed") - .with_context("Error processing JetStream message"), - - nvisy_nats::Error::StreamError { .. } => ErrorKind::InternalServerError - .with_message("Stream operation failed") - .with_context("Error accessing or manipulating stream"), - - nvisy_nats::Error::ConsumerError { .. } => ErrorKind::InternalServerError - .with_message("Consumer operation failed") - .with_context("Error with message consumer"), - - nvisy_nats::Error::JobQueueError { .. } => ErrorKind::InternalServerError - .with_message("Job processing failed") - .with_context("Error processing job from queue"), - - // Legacy streaming errors -> Internal Server Error - nvisy_nats::Error::Consumer(_) => ErrorKind::InternalServerError - .with_message("Consumer error") - .with_context("Message consumer encountered an error"), - - nvisy_nats::Error::Stream(_) => ErrorKind::InternalServerError - .with_message("Stream error") - .with_context("Stream operation encountered an error"), - - nvisy_nats::Error::Ack(_) => ErrorKind::InternalServerError - .with_message("Message acknowledgment failed") - .with_context("Unable to acknowledge message receipt"), - - // Generic operation error -> Internal Server Error - nvisy_nats::Error::Operation { ref operation, .. } => ErrorKind::InternalServerError - .with_message(format!("Operation '{operation}' failed")) - .with_context("The requested operation could not be completed"), - } + fn from(error: nvisy_nats::Error) -> Self { + let kind = match &error { + // The messaging backend is momentarily unreachable or slow: + // transient, so a retryable 503. + nvisy_nats::Error::Connection(_) | nvisy_nats::Error::Timeout { .. } => { + ErrorKind::ServiceUnavailable + } + // A payload we framed ourselves, or a server-side messaging + // operation: never something the caller's request can fix. + nvisy_nats::Error::Serialization(_) | nvisy_nats::Error::Operation { .. } => { + ErrorKind::InternalServerError + } + }; + let message = match kind { + ErrorKind::ServiceUnavailable => "Messaging is temporarily unavailable", + _ => "Messaging operation failed", + }; + kind.with_message(message).with_context(error.to_string()) } } @@ -108,69 +45,21 @@ mod tests { use super::*; #[test] - fn test_connection_error_conversion() { - let nats_err = nvisy_nats::Error::timeout(Duration::from_secs(30)); - let http_err: HttpError = nats_err.into(); - - assert_eq!(http_err.kind(), ErrorKind::InternalServerError); - assert!(http_err.message.as_deref().unwrap().contains("timed out")); - } - - #[test] - fn test_serialization_error_conversion() { - let json_err = serde_json::from_str::("invalid").unwrap_err(); - let nats_err = nvisy_nats::Error::Serialization(json_err); - let http_err: HttpError = nats_err.into(); - - assert_eq!(http_err.kind(), ErrorKind::InternalServerError); - assert!( - http_err - .message - .as_deref() - .unwrap() - .contains("Invalid request") + fn transient_failures_are_retryable() { + let timeout = nvisy_nats::Error::Timeout { + operation: "ping", + timeout: Duration::from_secs(10), + }; + assert_eq!( + HttpError::from(timeout).kind(), + ErrorKind::ServiceUnavailable ); } #[test] - fn test_not_found_error_conversion() { - let nats_err = nvisy_nats::Error::kv_key_not_found("test_bucket", "missing_key"); - let http_err: HttpError = nats_err.into(); - - assert_eq!(http_err.kind(), ErrorKind::NotFound); - assert!(http_err.context.as_deref().unwrap().contains("test_bucket")); - } - - #[test] - fn test_revision_mismatch_conversion() { - let nats_err = nvisy_nats::Error::kv_revision_mismatch("test_key", 5, 7); - let http_err: HttpError = nats_err.into(); - - assert_eq!(http_err.kind(), ErrorKind::Conflict); - assert!(http_err.context.as_deref().unwrap().contains("modified")); - } - - #[test] - fn test_stream_error_conversion() { - let nats_err = nvisy_nats::Error::stream_error("test_stream", "stream not available"); - let http_err: HttpError = nats_err.into(); - - assert_eq!(http_err.kind(), ErrorKind::InternalServerError); - assert!(http_err.context.as_deref().unwrap().contains("stream")); - } - - #[test] - fn test_invalid_config_conversion() { - let nats_err = nvisy_nats::Error::invalid_config("missing server URL"); - let http_err: HttpError = nats_err.into(); - - assert_eq!(http_err.kind(), ErrorKind::InternalServerError); - assert!( - http_err - .context - .as_deref() - .unwrap() - .contains("configuration") - ); + fn payload_failures_are_server_faults() { + let json = serde_json::from_str::("invalid").unwrap_err(); + let error = HttpError::from(nvisy_nats::Error::Serialization(json)); + assert_eq!(error.kind(), ErrorKind::InternalServerError); } } diff --git a/crates/nvisy-server/src/service/auth/auth_flow.rs b/crates/nvisy-server/src/service/auth/auth_flow.rs index b56d96df..64f51381 100644 --- a/crates/nvisy-server/src/service/auth/auth_flow.rs +++ b/crates/nvisy-server/src/service/auth/auth_flow.rs @@ -17,7 +17,7 @@ use nvisy_postgres::model::{NewAccount, NewAccountIdentity}; use nvisy_postgres::query::{ AccountApiTokenRepository, AccountIdentityRepository, AccountRepository, }; -use nvisy_postgres::types::IdentityProvider; +use nvisy_postgres::types::{ApiTokenType, IdentityProvider}; use nvisy_postgres::{AsyncConnection, Error as PgError, PgClient}; use crate::extract::SecurityContext; @@ -202,6 +202,46 @@ impl SignInService { Ok(jwt) } + /// Mints a long-lived desktop (`app`) session token for the account behind + /// a browser session, to hand to the desktop app. + /// + /// Only a `web` session may mint one: the desktop login completes in the + /// browser first, and refusing `app`/`api` tokens stops a leaked `app` token + /// from renewing itself indefinitely. The account must still be allowed to + /// sign in. + /// + /// # Errors + /// + /// - `Unauthorized` if the session no longer exists. + /// - `Forbidden` if the session is not a browser session, or the account may + /// not sign in. + /// - A database or signing error if minting fails. + pub async fn issue_desktop_token( + &self, + account_id: uuid::Uuid, + session_id: uuid::Uuid, + security: SecurityContext, + ) -> Result { + let mut conn = self.postgres.get_connection().await?; + + let session = conn + .find_account_api_token_by_id(session_id) + .await? + .ok_or_else(|| ErrorKind::Unauthorized.with_message("Session not found"))?; + if session.session_type != ApiTokenType::Web { + return Err(ErrorKind::Forbidden + .with_message("Desktop tokens can only be minted from a browser session")); + } + + let account = AccountProvisioner + .load_active(&mut conn, account_id) + .await?; + AccountProvisioner::ensure_can_sign_in(&account)?; + self.issuer + .issue_app_token(&mut conn, &account, security) + .await + } + /// Revokes the session token `token_id` (logout), returning whether a live /// token was found and deleted. /// diff --git a/crates/nvisy-server/src/service/auth/mod.rs b/crates/nvisy-server/src/service/auth/mod.rs index 36a12fe2..168749c7 100644 --- a/crates/nvisy-server/src/service/auth/mod.rs +++ b/crates/nvisy-server/src/service/auth/mod.rs @@ -16,4 +16,5 @@ pub use oidc::{ CallbackOutcome, ConsumedFlow, OidcAuthorization, OidcConfig, OidcConfigured, OidcError, OidcIdentity, OidcPurpose, OidcService, RedirectKind, }; +pub(crate) use oidc::{OidcStateBucket, ReauthProofBucket}; pub use password::PasswordService; diff --git a/crates/nvisy-server/src/service/auth/oidc/mod.rs b/crates/nvisy-server/src/service/auth/oidc/mod.rs index 05328cc2..2588fa04 100644 --- a/crates/nvisy-server/src/service/auth/oidc/mod.rs +++ b/crates/nvisy-server/src/service/auth/oidc/mod.rs @@ -31,11 +31,9 @@ use std::str::FromStr; use std::sync::Arc; use std::time::Duration; +use nvisy_core::http::OAuthHttpClient; use nvisy_nats::NatsClient; -use nvisy_nats::kv::{ - OidcStateBucket as OidcStateKvBucket, OidcStateKey, ReauthProofBucket as ReauthProofKvBucket, - ReauthProofKey, -}; +use nvisy_nats::kv::TokenKey; use nvisy_postgres::PgClient; use nvisy_postgres::query::AccountIdentityRepository; use nvisy_postgres::types::IdentityProvider; @@ -43,7 +41,7 @@ use openidconnect::core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetada use openidconnect::{ AuthorizationCode, ClientId, ClientSecret, CsrfToken, EndpointMaybeSet, EndpointNotSet, EndpointSet, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, Scope, - TokenResponse, reqwest, + TokenResponse, }; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -143,7 +141,7 @@ const OIDC_HTTP_REQUEST_TIMEOUT: Duration = Duration::from_secs(15); /// application state, so the per-request [`OidcService`] is assembled by cloning /// this handle and composing the (also `Arc`-backed) collaborators around it. struct OidcCore { - http: reqwest::Client, + http: OAuthHttpClient, providers: Vec, /// Frontend origins (`scheme://host[:port]`) the sign-in callback may redirect /// to. A caller-supplied redirect must match one of these, or it is refused — @@ -202,7 +200,7 @@ pub enum OidcPurpose { /// The stashed state of an in-flight OIDC flow, held between `begin_flow` and the /// callback in the [`OidcStateBucket`]. Keyed by the CSRF state token. #[derive(Debug, Clone, Serialize, Deserialize)] -struct OidcFlowState { +pub(crate) struct OidcFlowState { /// The provider the flow is against. provider: IdentityProvider, /// The PKCE verifier to present when exchanging the code. @@ -215,8 +213,17 @@ struct OidcFlowState { purpose: OidcPurpose, } -/// The OIDC-state bucket pinned to this server's flow-state value. -type OidcStateBucket = OidcStateKvBucket; +nvisy_nats::kv_bucket! { + /// In-flight OIDC sign-in state (CSRF token, PKCE verifier, and nonce), held + /// between starting a sign-in and its callback, keyed by the state token. + /// Separate from the connection-OAuth bucket: a sign-in carries a nonce and + /// serves a different flow. + pub(crate) OidcStateBucket: OidcFlowState { + name: "oidc_state", + description: "In-flight OIDC sign-in state", + ttl: Duration::from_mins(10), + } +} /// What a step-up re-authentication proof attests: the account it authorizes a /// credential-adding action for. @@ -229,12 +236,20 @@ type OidcStateBucket = OidcStateKvBucket; /// credential-add needs. Single-use + TTL + account-binding keep that from being /// a standing capability; consuming it atomically keeps it from being used twice. #[derive(Debug, Clone, Serialize, Deserialize)] -struct ReauthProof { +pub(crate) struct ReauthProof { account_id: Uuid, } -/// The reauth-proof bucket pinned to this server's proof value. -type ReauthProofBucket = ReauthProofKvBucket; +nvisy_nats::kv_bucket! { + /// Step-up re-authentication proofs, keyed by the proof id. Short-lived: a + /// step-up action follows its re-auth within minutes, and an unused proof + /// should not linger as a standing capability. + pub(crate) ReauthProofBucket: ReauthProof { + name: "reauth_proof", + description: "Step-up re-authentication proofs", + ttl: Duration::from_mins(5), + } +} /// The result of a completed callback flow, by purpose. The handler turns this /// into the browser response (a cookie, a deep-link, or a fragment redirect). @@ -322,7 +337,7 @@ impl OidcConfigured { Ok(Self { core: Arc::new(OidcCore { - http, + http: OAuthHttpClient::new(http), providers, allowed_redirect_origins: config.allowed_redirect_origins(), allowed_redirect_schemes: config.desktop_allowed_redirect_schemes(), @@ -567,9 +582,7 @@ impl OidcService { purpose, }; let store = self.nats.kv_store::().await?; - store - .put(&csrf_state.parse::()?, &flow) - .await?; + store.put(&csrf_state.parse::()?, &flow).await?; Ok(authorize_url) } @@ -587,7 +600,7 @@ impl OidcService { pub async fn consume_flow(&self, query: &OidcCallbackQuery) -> Result { // Validate the state before touching the store so a malformed value maps to // a clean BadRequest rather than a KV error. - let key = OidcStateKey::from_str(&query.state) + let key = TokenKey::from_str(&query.state) .map_err(|_| ErrorKind::BadRequest.with_message("Invalid authorization state"))?; // `take` consumes single-use and atomically, so two concurrent callbacks @@ -726,10 +739,7 @@ impl OidcService { let proof = generate_proof_token(); let store = self.nats.kv_store::().await?; store - .put( - &proof.parse::()?, - &ReauthProof { account_id }, - ) + .put(&proof.parse::()?, &ReauthProof { account_id }) .await?; Ok(proof) } @@ -748,7 +758,7 @@ impl OidcService { /// or belongs to a different account. /// - A messaging error if opening the KV store or the atomic take fails. pub async fn consume_reauth_proof(&self, account_id: Uuid, proof: &str) -> Result<()> { - let key = ReauthProofKey::from_str(proof) + let key = TokenKey::from_str(proof) .map_err(|_| ErrorKind::Unauthorized.with_message("Invalid re-authentication proof"))?; let store = self.nats.kv_store::().await?; // Consume single-use and atomically (`take`), so the same proof cannot be @@ -788,7 +798,7 @@ mod tests { fn service_with(origins: &[&str], schemes: &[&str]) -> OidcCore { OidcCore { - http: reqwest::Client::new(), + http: OAuthHttpClient::new(reqwest::Client::new()), providers: Vec::new(), allowed_redirect_origins: origins.iter().map(ToString::to_string).collect(), allowed_redirect_schemes: schemes.iter().map(ToString::to_string).collect(), diff --git a/crates/nvisy-server/src/service/di.rs b/crates/nvisy-server/src/service/di.rs index 9c4318d1..9b401cd2 100644 --- a/crates/nvisy-server/src/service/di.rs +++ b/crates/nvisy-server/src/service/di.rs @@ -123,6 +123,7 @@ impl_di_unit!(AccountProvisioner); // Per-resource domain services built over the Postgres client alone: impl_di_domain!( crate::domain::AccountService, + crate::domain::WorkspaceAnalyticsService, crate::domain::WorkspaceInviteService, crate::domain::WorkspaceMemberService, crate::domain::WorkspacePolicyService, @@ -157,8 +158,11 @@ impl_di_new! { // Crypto (encrypt/decrypt config) and the endpoint policy (validate endpoints). crate::domain::WorkspaceProviderService => |state| state.infra.postgres.clone(), state.crypto.clone(), state.endpoint_policy; + // Crypto, the endpoint policy, and the cloud file service (reach, refresh, + // and verify a connection's backing store). crate::domain::WorkspaceConnectionService => - |state| state.infra.postgres.clone(), state.crypto.clone(), state.endpoint_policy; + |state| state.infra.postgres.clone(), state.crypto.clone(), state.endpoint_policy, + state.file_service.clone(); // Crypto (decrypt the connection config) and the sync service (create the // run, spawn and cancel its transfer). crate::domain::WorkspaceConnectionSyncService => diff --git a/crates/nvisy-server/src/service/infra.rs b/crates/nvisy-server/src/service/infra.rs index afff0b8b..1b67ad9a 100644 --- a/crates/nvisy-server/src/service/infra.rs +++ b/crates/nvisy-server/src/service/infra.rs @@ -80,14 +80,13 @@ async fn connect_nats(config: NatsConfig) -> Result { /// Connects to the S3-compatible blob store and verifies it is reachable. /// -/// The AWS SDK builds its client lazily, so [`BlobStore::connect`] alone never -/// touches the network. A follow-up [`ping`](BlobStore::ping) makes a bad -/// endpoint, wrong credentials, or missing bucket fail at startup — matching the -/// fail-fast contract of the Postgres and NATS connectors — rather than at the -/// first upload. +/// [`BlobStore::connect`] only builds the client and never touches the network. +/// A follow-up [`ping`](BlobStore::ping) makes a bad endpoint, wrong +/// credentials, or missing bucket fail at startup, matching the fail-fast +/// contract of the Postgres and NATS connectors, rather than at the first +/// upload. async fn connect_blobs(config: S3Config) -> Result { let blobs = BlobStore::connect(&config) - .await .map_err(|e| Error::external("S3", "Failed to connect to the blob store").with_source(e))?; blobs.ping().await.map_err(|e| { diff --git a/crates/nvisy-server/src/service/mod.rs b/crates/nvisy-server/src/service/mod.rs index def4162c..2b27ba08 100644 --- a/crates/nvisy-server/src/service/mod.rs +++ b/crates/nvisy-server/src/service/mod.rs @@ -34,6 +34,7 @@ pub use crate::service::auth::{ OidcAuthorization, OidcConfig, OidcConfigured, OidcError, OidcIdentity, OidcPurpose, OidcService, PasswordService, RedirectKind, SignInService, }; +pub(crate) use crate::service::auth::{OidcStateBucket, ReauthProofBucket}; pub use crate::service::avatar::{ AVATAR_CONTENT_TYPE, AvatarOwner, AvatarService, MAX_AVATAR_UPLOAD_BYTES, }; @@ -62,7 +63,7 @@ use crate::worker::integration::ConnectionSyncWorker; use crate::worker::purge::{PurgeConfig, WorkspacePurgeWorker}; use crate::worker::reaper::BlobReaper; use crate::worker::webhook::WebhookDeliveryWorker; -use crate::worker::{Coordinator, WorkerSet, ensure_streams}; +use crate::worker::{Coordinator, WorkerSet, ensure_kv_buckets, ensure_streams}; /// Tracing target for service-state initialization. const TRACING_TARGET: &str = "nvisy_server::service"; @@ -191,10 +192,11 @@ impl ServiceState { ) -> Result { let infra = Infra::from_config(args.postgres, args.nats, args.s3).await?; - // Reconcile every JetStream stream once, up front, so the publishers and - // subscribers built per use later are cheap handles that assume their - // stream already exists. + // Reconcile every JetStream stream and KV bucket once, up front, so the + // publishers, subscribers, and stores built per use later are cheap + // handles that assume theirs already exists. ensure_streams(&infra.nats).await?; + ensure_kv_buckets(&infra.nats).await?; let engine = EngineService::from_config(args.engine).await?; let oidc = OidcConfigured::from_config(&args.oidc)?; diff --git a/crates/nvisy-server/src/worker/assistant/worker.rs b/crates/nvisy-server/src/worker/assistant/worker.rs index be135af5..c16f364d 100644 --- a/crates/nvisy-server/src/worker/assistant/worker.rs +++ b/crates/nvisy-server/src/worker/assistant/worker.rs @@ -257,11 +257,7 @@ impl AssistantWorker { ProviderConfig::Inference(AssistantConfig::Llm(llm)) => llm, }; - llm.connect(None).map_err(|err| { - ErrorKind::InternalServerError - .with_message("Failed to build the language model client") - .with_context(err.to_string()) - }) + Ok(llm.connect(None)) } /// Posts the assistant's reply as a comment answering `trigger_comment_id`, diff --git a/crates/nvisy-server/src/worker/integration/file_source.rs b/crates/nvisy-server/src/worker/integration/file_source.rs index 49195f94..ead1607f 100644 --- a/crates/nvisy-server/src/worker/integration/file_source.rs +++ b/crates/nvisy-server/src/worker/integration/file_source.rs @@ -71,19 +71,19 @@ impl ObjectStoreSource { #[async_trait::async_trait] impl FileSource for ObjectStoreSource { async fn get_stream(&self, key: &str) -> Result { - Ok(self.0.get_stream(key).await?) + Ok(self.0.get_stream(key).await?.body) } async fn put_stream(&self, upload: FileUpload<'_>) -> Result<()> { - // Object stores stream via multipart, which frames its own parts, so the - // known length is unused here. + // An object store frames its own upload (a single put, or multipart for + // large content), so the known length is unused here. let FileUpload { key, content_type, body, .. } = upload; - self.0.put_multipart(key, Some(content_type), body).await?; + self.0.put_stream(key, Some(content_type), body).await?; Ok(()) } } diff --git a/crates/nvisy-server/src/worker/integration/mod.rs b/crates/nvisy-server/src/worker/integration/mod.rs index 018eae6e..2344d9f9 100644 --- a/crates/nvisy-server/src/worker/integration/mod.rs +++ b/crates/nvisy-server/src/worker/integration/mod.rs @@ -24,6 +24,7 @@ use std::future::Future; pub use engine::TransferEngine; pub use file_source::SourceEntry; use futures::stream::{self, StreamExt}; +pub(crate) use worker::SchedulerLocksBucket; pub use worker::{ConnectionSyncJob, ConnectionSyncWorker, SyncStream}; /// Runs `transfer` over `items`, at most `concurrency` at once, and counts the diff --git a/crates/nvisy-server/src/worker/integration/worker.rs b/crates/nvisy-server/src/worker/integration/worker.rs index 8ef2d2c5..d794b983 100644 --- a/crates/nvisy-server/src/worker/integration/worker.rs +++ b/crates/nvisy-server/src/worker/integration/worker.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use std::time::Duration; use jiff::{Span, Timestamp}; -use nvisy_nats::kv::{SchedulerLockKey, SchedulerLocksBucket}; +use nvisy_nats::kv::TokenKey; use nvisy_nats::stream::{ConnectionSyncStream, Delivery, EventPublisher, Settle}; use nvisy_postgres::model::{ NewWorkspaceConnectionSync, WorkspaceConnection, WorkspaceConnectionSync, @@ -51,6 +51,18 @@ const STALE_RUN_AGE_HOURS: i64 = 6; /// Fixed KV key for the per-tick scheduler leader-election lock. const SCHEDULER_LOCK_KEY: &str = "connection-sync-scheduler"; +nvisy_nats::kv_bucket! { + /// Short-lived scheduler leader-election locks, one key per tick period. The + /// value is a nonce; only the key's presence matters. The TTL is comfortably + /// above the tick interval, so a period's lock outlives its period despite + /// clock skew, and a crashed holder never blocks later ticks. + pub(crate) SchedulerLocksBucket: u64 { + name: "scheduler_locks", + description: "Short-lived scheduler leader-election locks", + ttl: Duration::from_mins(5), + } +} + /// Base backoff before a failed scheduled sync is redelivered. Each attempt /// waits this multiplied by the attempt number (linear backoff); the stream's /// `MAX_DELIVER` bounds the attempts. @@ -145,7 +157,7 @@ impl ConnectionSyncWorker { // instance's tick phase. The bucket TTL reclaims old period keys. Segments // are joined with `.`, which NATS KV keys allow (`[-/_=.a-zA-Z0-9]`). let period = now.as_second() / i64::try_from(TICK_INTERVAL.as_secs()).unwrap_or(i64::MAX); - let lock_key: SchedulerLockKey = format!("{SCHEDULER_LOCK_KEY}.{period}").parse()?; + let lock_key: TokenKey = format!("{SCHEDULER_LOCK_KEY}.{period}").parse()?; let locks = self.infra.nats.kv_store::().await?; let acquired = locks.create(&lock_key, &1).await?; if !acquired { diff --git a/crates/nvisy-server/src/worker/mod.rs b/crates/nvisy-server/src/worker/mod.rs index 10cf90d0..f4c37e2c 100644 --- a/crates/nvisy-server/src/worker/mod.rs +++ b/crates/nvisy-server/src/worker/mod.rs @@ -27,6 +27,8 @@ pub(crate) use set::every; pub use set::{Worker, WorkerSet}; use crate::Result; +use crate::handler::OAuthStateBucket; +use crate::service::{OidcStateBucket, ReauthProofBucket}; /// Reconciles every `JetStream` stream the workers use, creating each if absent and /// updating its config to match. @@ -46,3 +48,20 @@ pub async fn ensure_streams(nats: &NatsClient) -> Result<()> { nats.ensure_stream::().await?; Ok(()) } + +/// Creates every KV bucket the server uses, if absent. +/// +/// Called once at startup beside [`ensure_streams`], so a store opened per use +/// later is a lookup, never a create. +/// +/// # Errors +/// +/// A NATS error if looking up or creating any bucket fails. +pub async fn ensure_kv_buckets(nats: &NatsClient) -> Result<()> { + nats.ensure_kv_bucket::().await?; + nats.ensure_kv_bucket::().await?; + nats.ensure_kv_bucket::().await?; + nats.ensure_kv_bucket::() + .await?; + Ok(()) +} diff --git a/crates/nvisy-webhook/Cargo.toml b/crates/nvisy-webhook/Cargo.toml index a96bf309..384f56f6 100644 --- a/crates/nvisy-webhook/Cargo.toml +++ b/crates/nvisy-webhook/Cargo.toml @@ -25,7 +25,7 @@ rustdoc-args = ["--cfg", "docsrs"] default = [] # Reqwest-based HTTP client for webhook delivery -reqwest = ["dep:reqwest", "dep:reqwest-middleware", "dep:reqwest-retry", "dep:reqwest-tracing", "dep:hmac", "dep:sha2", "dep:hex", "nvisy-core/reqwest"] +reqwest = ["dep:reqwest", "dep:reqwest-middleware", "dep:hmac", "dep:sha2", "dep:hex", "nvisy-core/reqwest"] # JSON Schema support: enables JsonSchema derives on webhook types # This allows webhook types to be used directly in API documentation without @@ -38,16 +38,20 @@ cli = ["dep:clap", "nvisy-core/cli"] [dependencies] # Internal crates -nvisy-core = { workspace = true } +nvisy-core = { workspace = true, features = [] } + +# CLI +clap = { workspace = true, features = ["derive", "env"], optional = true } # Async runtime -async-trait = { workspace = true } +async-trait = { workspace = true, features = [] } # HTTP client & middleware reqwest = { workspace = true, features = ["json"], optional = true } -reqwest-middleware = { workspace = true, optional = true } -reqwest-retry = { workspace = true, optional = true } -reqwest-tracing = { workspace = true, optional = true } +reqwest-middleware = { workspace = true, optional = true, features = [] } + +# OpenAPI/Documentation +schemars = { workspace = true, optional = true, features = [] } # Encryption & Cryptography hmac = { workspace = true, optional = true, features = [] } @@ -56,16 +60,12 @@ sha2 = { workspace = true, optional = true, features = [] } # Encoding hex = { workspace = true, optional = true, features = [] } -# CLI -clap = { workspace = true, features = ["derive", "env"], optional = true } - # Observability -tracing = { workspace = true } +tracing = { workspace = true, features = [] } # (De)serialization serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = [] } -schemars = { workspace = true, optional = true } # Primitive datatypes uuid = { workspace = true, features = ["serde", "v4", "v7"] } @@ -75,6 +75,7 @@ jiff = { workspace = true, features = ["serde"] } url = { workspace = true, features = ["serde"] } [dev-dependencies] +# Async runtime tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] } [lints] diff --git a/crates/nvisy-webhook/src/reqwest/client.rs b/crates/nvisy-webhook/src/reqwest/client.rs index cfe2ee7d..de16f222 100644 --- a/crates/nvisy-webhook/src/reqwest/client.rs +++ b/crates/nvisy-webhook/src/reqwest/client.rs @@ -6,12 +6,10 @@ use std::sync::Arc; use hmac::{Hmac, KeyInit, Mac}; use jiff::Timestamp; use nvisy_core::health::{ComponentHealth, HealthCheck}; +use nvisy_core::http::{ExponentialBackoff, middleware_client}; use nvisy_core::net::check_outbound; use reqwest::Client; -use reqwest_middleware::{ClientBuilder, ClientWithMiddleware}; -use reqwest_retry::RetryTransientMiddleware; -use reqwest_retry::policies::ExponentialBackoff; -use reqwest_tracing::TracingMiddleware; +use reqwest_middleware::ClientWithMiddleware; use sha2::Sha256; use super::{ReqwestConfig, TRACING_TARGET}; @@ -86,10 +84,7 @@ impl ReqwestClient { .retry_bounds(config.min_retry_interval, config.max_retry_interval) .build_with_max_retries(config.max_retries); - let http = ClientBuilder::new(base_client) - .with(TracingMiddleware::default()) - .with(RetryTransientMiddleware::new_with_policy(retry_policy)) - .build(); + let http = middleware_client(base_client, retry_policy); tracing::info!( target: TRACING_TARGET,