diff --git a/.env.example b/.env.example index f926a3e7..3ba8bc3c 100644 --- a/.env.example +++ b/.env.example @@ -240,6 +240,16 @@ MAX_FILE_BODY_BYTES=524288000 # Whether session cookies carry the Secure attribute (HTTPS-only) COOKIE_SECURE=true +# The domain the signed-in hint cookie is set for (e.g. nvisy.com), so every site under it +# can read it. Unset or empty, the hint is not set +# SIGNED_IN_COOKIE_DOMAIN= + +# ─── Sign-up ─── + +# Whether new accounts can be created, by password sign-up or by a first OIDC sign-in. +# Existing accounts can sign in either way +SIGNUP_ENABLED=true + # ─── Webhook HTTP client ─── # HTTP request timeout (e.g. 30s); falls back to the default when unset diff --git a/Cargo.lock b/Cargo.lock index 117a32fd..1606ebb6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,6 +60,7 @@ checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38" dependencies = [ "cfg-if", "const-random", + "getrandom 0.3.4", "getrandom 0.4.3", "once_cell", "serde", @@ -210,7 +211,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -221,7 +222,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1936,9 +1937,9 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -2987,7 +2988,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3112,7 +3113,7 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ - "curve25519-dalek 5.0.0", + "curve25519-dalek 5.1.0", "ed25519 3.0.0", "serde", "sha2 0.11.1", @@ -3142,7 +3143,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "elide" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-audio", @@ -3167,7 +3168,7 @@ dependencies = [ [[package]] name = "elide-audio" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3184,7 +3185,7 @@ dependencies = [ [[package]] name = "elide-backend" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3197,7 +3198,7 @@ dependencies = [ [[package]] name = "elide-bentoml" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "async-trait", "base64 0.23.1", @@ -3215,7 +3216,7 @@ dependencies = [ [[package]] name = "elide-codec" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3226,7 +3227,7 @@ dependencies = [ [[package]] name = "elide-core" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "blake3", @@ -3245,7 +3246,7 @@ dependencies = [ [[package]] name = "elide-deployment" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "hipstr", @@ -3257,7 +3258,7 @@ dependencies = [ [[package]] name = "elide-detection" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3271,7 +3272,7 @@ dependencies = [ [[package]] name = "elide-engine" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "bytes", "elide-audio", @@ -3293,7 +3294,7 @@ dependencies = [ [[package]] name = "elide-export" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "csv", "elide", @@ -3305,7 +3306,7 @@ dependencies = [ [[package]] name = "elide-fake" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3317,7 +3318,7 @@ dependencies = [ [[package]] name = "elide-format" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "elide-audio", "elide-codec", @@ -3332,7 +3333,7 @@ dependencies = [ [[package]] name = "elide-image" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3350,7 +3351,7 @@ dependencies = [ [[package]] name = "elide-lingua" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3361,7 +3362,7 @@ dependencies = [ [[package]] name = "elide-llm" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "base64 0.23.1", @@ -3385,7 +3386,7 @@ dependencies = [ [[package]] name = "elide-macros" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -3396,7 +3397,7 @@ dependencies = [ [[package]] name = "elide-markup" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-codec", @@ -3407,7 +3408,7 @@ dependencies = [ [[package]] name = "elide-ner" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "elide-core", @@ -3419,7 +3420,7 @@ dependencies = [ [[package]] name = "elide-office" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3434,7 +3435,7 @@ dependencies = [ [[package]] name = "elide-pattern" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "aho-corasick", "async-trait", @@ -3455,7 +3456,7 @@ dependencies = [ [[package]] name = "elide-pdf" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "async-trait", "bytes", @@ -3474,7 +3475,7 @@ dependencies = [ [[package]] name = "elide-pipeline" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "bytes", "elide", @@ -3495,7 +3496,7 @@ dependencies = [ [[package]] name = "elide-plain" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "anstream", "async-trait", @@ -3508,7 +3509,7 @@ dependencies = [ [[package]] name = "elide-provider" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "elide-bentoml", @@ -3525,7 +3526,7 @@ dependencies = [ [[package]] name = "elide-redaction" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide?branch=main#112193850169b68578f8bb814f63c7b483f95246" +source = "git+https://github.com/nvisycom/elide?branch=main#850253e69ddb3b5119caee1c5f5ee098c467b7ca" dependencies = [ "aes-gcm", "async-trait", @@ -3551,7 +3552,7 @@ dependencies = [ [[package]] name = "elide-review" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "elide-schema", @@ -3563,7 +3564,7 @@ dependencies = [ [[package]] name = "elide-schema" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "hipstr", @@ -3576,7 +3577,7 @@ dependencies = [ [[package]] name = "elide-template" version = "0.1.0" -source = "git+https://github.com/nvisycom/elide-runtime?rev=6712316061b4497098ba5a7b61f7c0a7e70ca5b0#6712316061b4497098ba5a7b61f7c0a7e70ca5b0" +source = "git+https://github.com/nvisycom/elide-runtime?rev=296f2db896f750393da47bb849156bfc83bcf4f4#296f2db896f750393da47bb849156bfc83bcf4f4" dependencies = [ "elide", "elide-schema", @@ -3723,7 +3724,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6616,7 +6617,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6940,6 +6941,7 @@ dependencies = [ "csv", "derive_more", "dotenvy", + "elide", "elide-pipeline", "futures", "garde", @@ -7552,7 +7554,7 @@ dependencies = [ "regex-cache", "serde", "serde_derive", - "strum 0.27.2", + "strum 0.26.3", "thiserror 2.0.21", ] @@ -8003,7 +8005,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -9068,7 +9070,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -9127,7 +9129,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -9747,7 +9749,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -9913,9 +9915,6 @@ name = "strum" version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" -dependencies = [ - "strum_macros 0.27.2", -] [[package]] name = "strum" @@ -10142,10 +10141,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -11310,7 +11309,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -11825,7 +11824,7 @@ dependencies = [ "memchr", "nix", "typed-path", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index d9aaa80a..89458603 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,8 @@ 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, features = [] } +elide-pipeline = { git = "https://github.com/nvisycom/elide-runtime", rev = "296f2db896f750393da47bb849156bfc83bcf4f4", default-features = false, features = [] } +elide = { git = "https://github.com/nvisycom/elide", branch = "main", default-features = false, features = [] } # Internal crates nvisy-core = { path = "./crates/nvisy-core", version = "0.1.0" } diff --git a/crates/nvisy-core/src/health.rs b/crates/nvisy-core/src/health.rs index 7c81ece9..8b393a96 100644 --- a/crates/nvisy-core/src/health.rs +++ b/crates/nvisy-core/src/health.rs @@ -12,8 +12,9 @@ use serde::Serialize; use crate::TRACING_TARGET; -/// Operational status of a service component. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +/// Operational status of a service component, ordered from best to worst, so the +/// worst of several is their `max`. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "snake_case")] @@ -34,28 +35,19 @@ impl HealthStatus { matches!(self, Self::Healthy) } - /// Aggregates per-component results into an overall status: [`Unhealthy`] - /// when there are no components or none are healthy, [`Healthy`] when all - /// are, and [`Degraded`] otherwise. + /// Aggregates per-component results into an overall status: the worst + /// component status, or [`Unhealthy`] when there are no components. Every + /// component is a dependency the server needs, so one being down makes the + /// whole server unhealthy. /// /// [`Unhealthy`]: Self::Unhealthy - /// [`Healthy`]: Self::Healthy - /// [`Degraded`]: Self::Degraded #[must_use] pub fn from_components(components: &[ComponentHealth]) -> Self { - if components.is_empty() { - return Self::Unhealthy; - } - - let healthy = components.iter().filter(|c| c.status.is_healthy()).count(); - - if healthy == 0 { - Self::Unhealthy - } else if healthy == components.len() { - Self::Healthy - } else { - Self::Degraded - } + components + .iter() + .map(|component| component.status) + .max() + .unwrap_or(Self::Unhealthy) } } @@ -168,11 +160,26 @@ mod tests { } #[test] - fn some_healthy_is_degraded() { + fn one_unhealthy_component_is_unhealthy() { let components = [ ComponentHealth::healthy("a"), ComponentHealth::unhealthy("b"), ]; + assert_eq!( + HealthStatus::from_components(&components), + HealthStatus::Unhealthy + ); + } + + #[test] + fn one_degraded_component_is_degraded() { + let components = [ + ComponentHealth::healthy("a"), + ComponentHealth { + name: "b".into(), + status: HealthStatus::Degraded, + }, + ]; assert_eq!( HealthStatus::from_components(&components), HealthStatus::Degraded diff --git a/crates/nvisy-nats/src/stream/consume.rs b/crates/nvisy-nats/src/stream/consume.rs index c974aeab..f8d164ca 100644 --- a/crates/nvisy-nats/src/stream/consume.rs +++ b/crates/nvisy-nats/src/stream/consume.rs @@ -101,7 +101,10 @@ impl EventSubscriber { let mut tasks: JoinSet<()> = JoinSet::new(); loop { + // Biased so a fired cancellation wins over a free permit: unbiased, the + // loop would start another pull about half the time it should stop. let permit = tokio::select! { + biased; () = cancel.cancelled() => break, // Reap finished tasks so the set stays bounded by what is in flight. Some(_) = tasks.join_next() => continue, diff --git a/crates/nvisy-object-store/src/provider/mod.rs b/crates/nvisy-object-store/src/provider/mod.rs index 1f35001f..937bdb24 100644 --- a/crates/nvisy-object-store/src/provider/mod.rs +++ b/crates/nvisy-object-store/src/provider/mod.rs @@ -22,7 +22,7 @@ use crate::client::ObjectStoreClient; /// an S3 connection cannot carry Azure credentials. Each variant carries a /// shared optional `root_path` and a nested `credentials` object, giving a wire /// shape like -/// `{ "provider": "s3", "rootPath": "in/", "credentials": { "bucket": "b", "accessKeyId": "..." } }`. +/// `{ "provider": "s3", "rootPath": "in/", "credentials": { "bucket": "b", "accessKeyId": "...", "secretAccessKey": "..." } }`. /// /// Secrets are masked in [`Debug`]; serialization exists only to persist the /// config encrypted at rest, never to return it in API responses. diff --git a/crates/nvisy-postgres/src/model/mod.rs b/crates/nvisy-postgres/src/model/mod.rs index d306c0a1..9b6c2351 100644 --- a/crates/nvisy-postgres/src/model/mod.rs +++ b/crates/nvisy-postgres/src/model/mod.rs @@ -13,6 +13,7 @@ mod workspace_blobs; mod workspace_connection_schedule; mod workspace_connection_syncs; mod workspace_connections; +mod workspace_detection_edits; mod workspace_detection_jobs; mod workspace_detection_policy_versions; mod workspace_detections; @@ -49,6 +50,7 @@ pub use workspace_connection_syncs::{NewWorkspaceConnectionSync, WorkspaceConnec pub use workspace_connections::{ NewWorkspaceConnection, UpdateWorkspaceConnection, WorkspaceConnection, }; +pub use workspace_detection_edits::{NewDetectionDecision, WorkspaceDetectionEdit}; pub use workspace_detection_jobs::{NewWorkspaceDetectionJob, WorkspaceDetectionJob}; pub use workspace_detection_policy_versions::DetectionPolicyVersion; pub use workspace_detections::{ @@ -68,7 +70,7 @@ pub use workspace_review_comments::{ NewWorkspaceReviewComment, UpdateWorkspaceReviewComment, WorkspaceReviewComment, }; pub use workspace_review_events::{NewWorkspaceReviewEvent, WorkspaceReviewEvent}; -pub use workspace_review_links::NewReviewAssignee; +pub use workspace_review_links::{NewReviewAssignee, WorkspaceReviewApproval}; pub use workspace_reviews::{NewWorkspaceReview, UpdateWorkspaceReview, WorkspaceReview}; pub use workspace_webhooks::{NewWorkspaceWebhook, UpdateWorkspaceWebhook, WorkspaceWebhook}; pub use workspaces::{NewWorkspace, UpdateWorkspace, Workspace}; diff --git a/crates/nvisy-postgres/src/model/workspace_detection_edits.rs b/crates/nvisy-postgres/src/model/workspace_detection_edits.rs new file mode 100644 index 00000000..488d6d65 --- /dev/null +++ b/crates/nvisy-postgres/src/model/workspace_detection_edits.rs @@ -0,0 +1,41 @@ +//! Workspace detection edit model: one reviewer decision about a detection. +//! +//! A detection's edits are its rows here, each holding one decision and the +//! reviewer who last set it. Redaction applies each reviewer's decisions under +//! their own account, so every audit event names the person who decided it. + +use diesel::prelude::*; +use jiff_diesel::Timestamp; +use uuid::Uuid; + +use crate::schema::workspace_detection_edits; +use crate::types::Json; + +/// One reviewer decision about a detection. +#[derive(Debug, Clone, PartialEq, Queryable, Selectable)] +#[diesel(table_name = workspace_detection_edits)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct WorkspaceDetectionEdit { + /// Detection the decision is about. + pub detection_id: Uuid, + /// What the decision is about, derived by the server from the edit. + pub decision_key: String, + /// Reviewer who last set the decision. + pub account_id: Uuid, + /// The decision, as an engine `EditSet` holding exactly one edit. Stored + /// opaquely here; the engine type lives in the server layer. + pub edit: Json, + /// When the decision was first set. + pub created_at: Timestamp, + /// When the decision was last set. + pub updated_at: Timestamp, +} + +/// A decision to store for a detection, keyed by what it is about. +#[derive(Debug, Clone, PartialEq)] +pub struct NewDetectionDecision { + /// What the decision is about. + pub decision_key: String, + /// The decision, as an engine `EditSet` holding exactly one edit. + pub edit: Json, +} diff --git a/crates/nvisy-postgres/src/model/workspace_detections.rs b/crates/nvisy-postgres/src/model/workspace_detections.rs index 51df235a..135d1d17 100644 --- a/crates/nvisy-postgres/src/model/workspace_detections.rs +++ b/crates/nvisy-postgres/src/model/workspace_detections.rs @@ -49,13 +49,11 @@ pub struct WorkspaceDetection { pub retention_override: Option>, /// Non-encrypted metadata for filtering/display. pub metadata: Json, - /// Accumulated reviewer edits (the engine's `EditSet`) layered over the base - /// analysis at redact time, so manual corrections persist between redactions. - /// Stored opaquely as JSON here (the engine type lives in the server layer); - /// `None` means no edits yet. - pub edit_set: Option>, - /// Optimistic-concurrency version for `edit_set`, bumped on every edit write; an - /// edit names the revision it read and the write proceeds only if it still matches. + /// Optimistic-concurrency version of the detection's reviewer edits (held as + /// [`WorkspaceDetectionEdit`] rows), bumped on every edit write; an edit names + /// the revision it read and the write proceeds only if it still matches. + /// + /// [`WorkspaceDetectionEdit`]: crate::model::WorkspaceDetectionEdit pub edit_set_rev: i32, /// When a worker last claimed this detection. Acts as a lease: a redelivered /// job whose claim is still fresh is skipped, while a stale claim (a worker @@ -128,8 +126,6 @@ pub struct UpdateWorkspaceDetection { pub audit_expires_at: Option>, /// Non-encrypted metadata for filtering/display. pub metadata: Option>, - /// Accumulated reviewer edits; outer `None` leaves it, inner `None` clears it. - pub edit_set: Option>>, /// When a worker last claimed this detection (lease timestamp). pub claimed_at: Option>, /// When the detection completed analysis. diff --git a/crates/nvisy-postgres/src/model/workspace_review_links.rs b/crates/nvisy-postgres/src/model/workspace_review_links.rs index 795b9bb6..49940415 100644 --- a/crates/nvisy-postgres/src/model/workspace_review_links.rs +++ b/crates/nvisy-postgres/src/model/workspace_review_links.rs @@ -1,13 +1,13 @@ -//! Review assignee model: the many-to-many rows tying a review to its reviewers, -//! each carrying that reviewer's approval (`approved_at`). +//! Review link models: the many-to-many rows tying a review to its reviewers, and +//! each reviewer's approval of one specific redaction. use diesel::prelude::*; +use jiff_diesel::Timestamp; use uuid::Uuid; -use crate::schema::workspace_review_assignees; +use crate::schema::{workspace_review_approvals, workspace_review_assignees}; -/// A link assigning an account as a reviewer of a review. A new assignee starts -/// unapproved (`approved_at` defaults to NULL). +/// A link assigning an account as a reviewer of a review. #[derive(Debug, Clone, Insertable)] #[diesel(table_name = workspace_review_assignees)] #[diesel(check_for_backend(diesel::pg::Pg))] @@ -18,3 +18,19 @@ pub struct NewReviewAssignee { /// The assigned reviewer. pub account_id: Uuid, } + +/// An assignee's approval of one redaction of the review's document. At most one +/// per assignee; approving another redaction replaces it. +#[derive(Debug, Clone, PartialEq, Queryable, Selectable, Insertable)] +#[diesel(table_name = workspace_review_approvals)] +#[diesel(check_for_backend(diesel::pg::Pg))] +pub struct WorkspaceReviewApproval { + /// The review. + pub review_id: Uuid, + /// The approving assignee. + pub account_id: Uuid, + /// The redaction this approval endorses. + pub redaction_id: Uuid, + /// When the assignee approved it. + pub approved_at: Timestamp, +} diff --git a/crates/nvisy-postgres/src/model/workspace_reviews.rs b/crates/nvisy-postgres/src/model/workspace_reviews.rs index 2ead4f42..29a7254b 100644 --- a/crates/nvisy-postgres/src/model/workspace_reviews.rs +++ b/crates/nvisy-postgres/src/model/workspace_reviews.rs @@ -1,13 +1,13 @@ //! Workspace review model: a named discussion on a document with an explicit //! approval lifecycle. A document has 0..N reviews, which may run concurrently (one -//! per audience). A review carries its [`ReviewStatus`], the detection it is -//! currently reviewing and the redaction it has approved (direct columns), owns a -//! stream of [`WorkspaceReviewComment`] messages and [`WorkspaceReviewEvent`] -//! timeline entries, and references its assignees — whose stamped `approved_at` -//! drive sign-off — via [`NewReviewAssignee`](super::NewReviewAssignee). +//! per audience). A review carries its [`ReviewStatus`] and the redaction its quorum +//! approved, owns a stream of [`WorkspaceReviewComment`] messages and +//! [`WorkspaceReviewEvent`] timeline entries, and references its assignees, whose +//! [`WorkspaceReviewApproval`]s of specific redactions drive sign-off. //! //! [`WorkspaceReviewComment`]: super::WorkspaceReviewComment //! [`WorkspaceReviewEvent`]: super::WorkspaceReviewEvent +//! [`WorkspaceReviewApproval`]: super::WorkspaceReviewApproval use diesel::prelude::*; use jiff_diesel::Timestamp; @@ -16,9 +16,9 @@ use uuid::Uuid; use crate::schema::workspace_reviews; use crate::types::ReviewStatus; -/// A review: a named discussion on a document, carrying its [`ReviewStatus`], the -/// detection it is currently reviewing, and the redaction it approved. Its assignees -/// and approvals live in link tables; its comments and timeline events belong to it. +/// A review: a named discussion on a document, carrying its [`ReviewStatus`] and the +/// redaction its quorum approved. Its assignees and approvals live in link tables; +/// its comments and timeline events belong to it. #[derive(Debug, Clone, PartialEq, Queryable, Selectable)] #[diesel(table_name = workspace_reviews)] #[diesel(check_for_backend(diesel::pg::Pg))] @@ -29,9 +29,8 @@ pub struct WorkspaceReview { pub workspace_id: Uuid, /// Document under review (a document may have many concurrent reviews). pub document_id: Uuid, - /// The detection currently under review; `None` before one is linked. - pub detection_id: Option, - /// The redaction bound by an approval; `None` until an approver names one. + /// The redaction the quorum approved (the output); set exactly while the + /// review is `approved`. pub redaction_id: Option, /// Account that opened the review. pub author_account_id: Uuid, @@ -57,8 +56,6 @@ pub struct NewWorkspaceReview { pub workspace_id: Uuid, /// Document under review (required). pub document_id: Uuid, - /// The detection the review opens against; `None` for a draft without one yet. - pub detection_id: Option, /// Opening author account ID (required). pub author_account_id: Uuid, /// Title (required). @@ -72,7 +69,6 @@ impl NewWorkspaceReview { Self { workspace_id, document_id, - detection_id: None, author_account_id, display_name: "A test review.".to_owned(), } @@ -81,9 +77,9 @@ impl NewWorkspaceReview { /// Data for updating a review's mutable fields. /// -/// The two id fields are doubly optional: the outer `None` leaves the column +/// `redaction_id` is doubly optional: the outer `None` leaves the column /// unchanged, an inner `Some` sets it, and an inner `None` clears it to `NULL` (so a -/// reopen can clear `redaction_id`). +/// reopen can clear it). #[derive(Debug, Clone, Default, AsChangeset)] #[diesel(table_name = workspace_reviews)] #[diesel(check_for_backend(diesel::pg::Pg))] @@ -93,8 +89,6 @@ pub struct UpdateWorkspaceReview { pub display_name: Option, /// The new review status; `None` leaves it unchanged. pub review_status: Option, - /// The detection under review; outer `None` leaves it, inner `None` clears it. - pub detection_id: Option>, - /// The bound redaction; outer `None` leaves it, inner `None` clears it. + /// The approved output; outer `None` leaves it, inner `None` clears it. pub redaction_id: Option>, } diff --git a/crates/nvisy-postgres/src/query/accounts.rs b/crates/nvisy-postgres/src/query/accounts.rs index 0e19db5c..ab6110c0 100644 --- a/crates/nvisy-postgres/src/query/accounts.rs +++ b/crates/nvisy-postgres/src/query/accounts.rs @@ -32,6 +32,14 @@ pub trait AccountRepository { account_id: Uuid, ) -> impl Future>> + Send; + /// Finds the public references of `account_ids`, in the order given. As with + /// [`Self::find_account_ref`], a soft-deleted account still resolves; an id + /// matching no account is skipped. + fn find_account_refs( + &mut self, + account_ids: &[Uuid], + ) -> impl Future>> + Send; + /// Finds an account by its unique identifier. /// /// Retrieves a specific account using its UUID, automatically excluding @@ -157,6 +165,21 @@ impl AccountRepository for PgConnection { .optional()?) } + async fn find_account_refs(&mut self, account_ids: &[Uuid]) -> Result> { + use schema::accounts::{self, dsl}; + + if account_ids.is_empty() { + return Ok(Vec::new()); + } + let mut refs: Vec = accounts::table + .filter(dsl::id.eq_any(account_ids)) + .select(AccountRefRow::as_select()) + .load(self) + .await?; + refs.sort_by_key(|account| account_ids.iter().position(|id| *id == account.id)); + Ok(refs) + } + async fn find_account_by_id(&mut self, account_id: Uuid) -> Result> { use schema::accounts::{self, dsl}; diff --git a/crates/nvisy-postgres/src/query/analytics.rs b/crates/nvisy-postgres/src/query/analytics.rs index d2f83730..c939cb9d 100644 --- a/crates/nvisy-postgres/src/query/analytics.rs +++ b/crates/nvisy-postgres/src/query/analytics.rs @@ -12,7 +12,9 @@ use std::future::Future; use bigdecimal::BigDecimal; +use diesel::pg::Pg; use diesel::prelude::*; +use diesel::query_builder::{BoxedSelectStatement, FromClause}; use diesel::sql_types::Timestamptz; use diesel_async::RunQueryDsl; use uuid::Uuid; @@ -110,14 +112,18 @@ pub struct AnalyticsSnapshot { /// Read-only aggregate queries backing the workspace analytics endpoint. pub trait WorkspaceAnalyticsRepository { - /// A workspace's point-in-time analytics — storage by kind, detection counts - /// by status, and completed-detection durations — read in one read-only, - /// repeatable-read transaction so the parts reflect a single snapshot. Each - /// breakdown lists only the groups that have data; the caller zero-fills the - /// rest. + /// A workspace's analytics — storage by kind, detection counts by status, and + /// completed-detection durations — read in one read-only, repeatable-read + /// transaction so the parts reflect a single snapshot. Each breakdown lists + /// only the groups that have data; the caller zero-fills the rest. + /// + /// The detection parts cover detections started in `[from, to)`, each bound + /// applied only when given; storage is always the workspace's live files now. fn snapshot( &mut self, workspace_id: Uuid, + from: Option, + to: Option, ) -> impl Future> + Send; /// Daily detection activity for a workspace over `[from, to)` (UTC day @@ -135,7 +141,16 @@ pub trait WorkspaceAnalyticsRepository { } impl WorkspaceAnalyticsRepository for PgConnection { - async fn snapshot(&mut self, workspace_id: Uuid) -> Result { + async fn snapshot( + &mut self, + workspace_id: Uuid, + from: Option, + to: Option, + ) -> Result { + let window = StartedWindow { + from: from.map(jiff_diesel::Timestamp::from), + to: to.map(jiff_diesel::Timestamp::from), + }; // The three reads run in one read-only, repeatable-read transaction so the // snapshot is internally consistent: a write landing between two of the // reads cannot make the detection counts and durations disagree. @@ -145,8 +160,8 @@ impl WorkspaceAnalyticsRepository for PgConnection { .run(async |conn| { Ok(AnalyticsSnapshot { storage: load_storage_by_kind(conn, workspace_id).await?, - detections: load_detections_by_status(conn, workspace_id).await?, - durations: load_detection_durations(conn, workspace_id).await?, + detections: load_detections_by_status(conn, workspace_id, window).await?, + durations: load_detection_durations(conn, workspace_id, window).await?, }) }) .await @@ -217,29 +232,64 @@ async fn load_storage_by_kind( .collect()) } -/// Detection count per `status`, Only statuses -/// with a detection appear. +/// Optional bounds on when a detection started: `from` inclusive, `to` +/// exclusive, each applied only when given. +#[derive(Debug, Clone, Copy)] +struct StartedWindow { + from: Option, + to: Option, +} + +/// A boxed aggregate over the detections table. +type DetectionAggregate<'a, ST, GB> = + BoxedSelectStatement<'a, ST, FromClause, Pg, GB>; + +impl StartedWindow { + /// Narrows a boxed detection aggregate to the detections that started + /// within this window. Boxing after the select keeps `group_by` available, + /// which a boxed source table would not. + fn narrow( + self, + query: DetectionAggregate<'_, ST, GB>, + ) -> DetectionAggregate<'_, ST, GB> { + use schema::workspace_detections::dsl as detections; + + let mut query = query; + if let Some(from) = self.from { + query = query.filter(detections::started_at.ge(from)); + } + if let Some(to) = self.to { + query = query.filter(detections::started_at.lt(to)); + } + query + } +} + +/// Detection count per `status` within `window`. Only statuses with a detection +/// appear. async fn load_detections_by_status( conn: &mut PgConnection, workspace_id: Uuid, + window: StartedWindow, ) -> Result> { use diesel::dsl::count_star; use schema::workspace_detections; use schema::workspace_detections::dsl as detections; - Ok(workspace_detections::table + let query = workspace_detections::table .filter(detections::workspace_id.eq(workspace_id)) .group_by(detections::status) .select((detections::status, count_star())) - .load(conn) - .await?) + .into_boxed(); + Ok(window.narrow(query).load(conn).await?) } /// Mean and 95th-percentile duration (milliseconds) of the workspace's completed -/// detections. Both `None` when no detection has completed. +/// detections within `window`. Both `None` when none has completed. async fn load_detection_durations( conn: &mut PgConnection, workspace_id: Uuid, + window: StartedWindow, ) -> Result { use diesel::dsl::sql; use diesel::sql_types::{BigInt, Nullable}; @@ -261,15 +311,15 @@ async fn load_detection_durations( - workspace_detections.started_at))) * 1000)::bigint", ); - let (avg_ms, p95_ms): (Option, Option) = workspace_detections::table + let query = workspace_detections::table .filter(detections::workspace_id.eq(workspace_id)) // Durations describe successful analysis only. `completed_at` is stamped // on failure too, so filter on the terminal `Complete` status, not merely // on the timestamp being present. .filter(detections::status.eq(DetectionStatus::Complete)) .select((avg_ms, p95_ms)) - .first(conn) - .await?; + .into_boxed(); + let (avg_ms, p95_ms): (Option, Option) = window.narrow(query).first(conn).await?; Ok(DetectionDurations { avg_ms, p95_ms }) } @@ -411,7 +461,7 @@ mod tests { )) .await?; - let snapshot = conn.snapshot(seeded.workspace_id).await?; + let snapshot = conn.snapshot(seeded.workspace_id, None, None).await?; // Storage: 2 original documents + 1 redacted, grouped by kind. let original = snapshot @@ -445,6 +495,63 @@ mod tests { assert_eq!(snapshot.durations.avg_ms, Some(10_000)); Ok(()) } + #[tokio::test] + async fn snapshot_window_scopes_detections_but_not_storage() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let mut conn = db.client.get_connection().await?; + + // One detection ten days ago (10s), one two hours ago (20s). + let _old = completed_detection( + &mut conn, + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + Span::new().hours(240), + Span::new().seconds(10), + ) + .await?; + let _recent = completed_detection( + &mut conn, + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + Span::new().hours(2), + Span::new().seconds(20), + ) + .await?; + + // A window over the last day sees only the recent detection. + let from = Timestamp::now() - Span::new().hours(24); + let windowed = conn.snapshot(seeded.workspace_id, Some(from), None).await?; + let complete = |snapshot: &AnalyticsSnapshot| { + snapshot + .detections + .iter() + .find(|d| d.status == DetectionStatus::Complete) + .map(|d| d.count) + }; + assert_eq!(complete(&windowed), Some(1)); + assert_eq!(windowed.durations.avg_ms, Some(20_000)); + assert_eq!(windowed.durations.p95_ms, Some(20_000)); + + // A window ending before both sees no detections at all. + let to = Timestamp::now() - Span::new().hours(480); + let before = conn.snapshot(seeded.workspace_id, None, Some(to)).await?; + assert!(before.detections.is_empty()); + assert_eq!(before.durations.avg_ms, None); + + // Storage is the live files now, whatever the window. + assert_eq!(before.storage.len(), windowed.storage.len()); + assert!(!before.storage.is_empty()); + + // No window is all time. + let all = conn.snapshot(seeded.workspace_id, None, None).await?; + assert_eq!(complete(&all), Some(2)); + assert_eq!(all.durations.avg_ms, Some(15_000)); + Ok(()) + } + #[tokio::test] async fn snapshot_is_scoped_to_the_workspace() -> anyhow::Result<()> { let db = TestDatabase::start().await; @@ -462,14 +569,14 @@ mod tests { .await?; // The unrelated workspace sees none of it. - let snapshot = conn.snapshot(seeded.workspace_id).await?; + let snapshot = conn.snapshot(seeded.workspace_id, None, None).await?; assert!(snapshot.detections.is_empty()); assert!(snapshot.storage.is_empty()); // The owning workspace does. assert!( !conn - .snapshot(other.workspace_id) + .snapshot(other.workspace_id, None, None) .await? .detections .is_empty() diff --git a/crates/nvisy-postgres/src/query/mod.rs b/crates/nvisy-postgres/src/query/mod.rs index 2c672b84..e06f5e24 100644 --- a/crates/nvisy-postgres/src/query/mod.rs +++ b/crates/nvisy-postgres/src/query/mod.rs @@ -21,6 +21,7 @@ mod workspace_blobs; mod workspace_connection_schedule; mod workspace_connection_syncs; mod workspace_connections; +mod workspace_detection_edits; mod workspace_detection_policy_versions; mod workspace_detections; mod workspace_documents; @@ -56,9 +57,10 @@ pub use workspace_blobs::{ReclaimableBlob, WorkspaceBlobRepository}; pub use workspace_connection_schedule::WorkspaceConnectionScheduleRepository; pub use workspace_connection_syncs::WorkspaceConnectionSyncRepository; pub use workspace_connections::{ScheduledConnection, WorkspaceConnectionRepository}; +pub use workspace_detection_edits::{DetectionEditRepository, EditWriteOutcome}; pub use workspace_detection_policy_versions::DetectionPolicyVersionRepository; pub use workspace_detections::{ - DetectionDocuments, DetectionListRow, DetectionSummary, DetectionTreeRow, EditWriteOutcome, + DetectionDocuments, DetectionListRow, DetectionSummary, DetectionTreeRow, WorkspaceDetectionRepository, }; pub use workspace_documents::{DocumentWithBlob, ImportedDocumentRef, WorkspaceDocumentRepository}; diff --git a/crates/nvisy-postgres/src/query/workspace_detection_edits.rs b/crates/nvisy-postgres/src/query/workspace_detection_edits.rs new file mode 100644 index 00000000..240300d5 --- /dev/null +++ b/crates/nvisy-postgres/src/query/workspace_detection_edits.rs @@ -0,0 +1,346 @@ +//! Repository for a detection's reviewer decisions. +//! +//! A detection's edits are stored one decision per row, keyed by what the +//! decision is about and attributed to the reviewer who last set it. A write +//! replaces the whole set under the detection's `edit_set_rev` guard: a decision +//! the write leaves unchanged keeps its author, a new or changed one is +//! attributed to the writer, and one the write omits is deleted. + +use std::collections::{HashMap, HashSet}; +use std::future::Future; + +use diesel::dsl::now; +use diesel::prelude::*; +use diesel_async::{AsyncConnection, RunQueryDsl}; +use uuid::Uuid; + +use crate::model::{NewDetectionDecision, WorkspaceDetection, WorkspaceDetectionEdit}; +use crate::types::{AccountRefRow, Json, WithAccountRef}; +use crate::{PgConnection, Result, schema}; + +/// The outcome of a guarded write of a detection's edits. +#[derive(Debug, Clone)] +pub enum EditWriteOutcome { + /// The write landed; carries the updated detection (with the bumped revision). + Updated(Box), + /// The detection exists but its `edit_set_rev` no longer matches the expected + /// one: a concurrent edit won, so this write was not applied. + Stale, + /// No live detection matches in the workspace. + Absent, +} + +/// Repository for the detection edit table. +pub trait DetectionEditRepository { + /// Replaces a live detection's decisions, scoped to its workspace, under an + /// optimistic-concurrency guard. `expected_rev` is the `edit_set_rev` the + /// caller read; the write proceeds and bumps the revision only if it still + /// matches. An empty `decisions` clears the detection's edits. + /// + /// A decision whose key and content are unchanged keeps its author and + /// timestamps. A new or changed one is attributed to `account_id`. A stored + /// decision whose key is absent from `decisions` is deleted. Keys in + /// `decisions` must be distinct. + /// + /// Returns [`EditWriteOutcome::Updated`] with the detection, [`Stale`] when the + /// detection exists but its revision has moved on, or [`Absent`] when no live + /// detection matches. + /// + /// [`Stale`]: EditWriteOutcome::Stale + /// [`Absent`]: EditWriteOutcome::Absent + fn replace_detection_edits( + &mut self, + workspace_id: Uuid, + detection_id: Uuid, + account_id: Uuid, + expected_rev: i32, + decisions: Vec, + ) -> impl Future> + Send; + + /// Lists a detection's decisions with their authors, oldest-set first. + fn list_detection_edits( + &mut self, + detection_id: Uuid, + ) -> impl Future>>> + Send; +} + +impl DetectionEditRepository for PgConnection { + async fn replace_detection_edits( + &mut self, + workspace_id: Uuid, + detection_id: Uuid, + account_id: Uuid, + expected_rev: i32, + decisions: Vec, + ) -> Result { + use schema::workspace_detection_edits::{self as edits, dsl as edit}; + use schema::workspace_detections::{self, dsl}; + + self.transaction(async |conn| { + // Bump the revision only while it still matches, so the next writer's + // stale guard trips. The bump also locks the detection row, so the + // decision rewrite below cannot interleave with a concurrent writer. + let updated: Option = diesel::update( + workspace_detections::table + .filter(dsl::id.eq(detection_id)) + .filter(dsl::workspace_id.eq(workspace_id)) + .filter(dsl::deleted_at.is_null()) + .filter(dsl::edit_set_rev.eq(expected_rev)), + ) + .set(dsl::edit_set_rev.eq(dsl::edit_set_rev + 1)) + .returning(WorkspaceDetection::as_returning()) + .get_result(conn) + .await + .optional()?; + + let Some(detection) = updated else { + // No row updated: either the detection is gone (Absent) or its + // revision moved on (Stale). A scoped existence check separates them. + let exists: bool = diesel::select(diesel::dsl::exists( + workspace_detections::table + .filter(dsl::id.eq(detection_id)) + .filter(dsl::workspace_id.eq(workspace_id)) + .filter(dsl::deleted_at.is_null()), + )) + .get_result(conn) + .await?; + return Ok(if exists { + EditWriteOutcome::Stale + } else { + EditWriteOutcome::Absent + }); + }; + + let stored: HashMap = edits::table + .filter(edit::detection_id.eq(detection_id)) + .select((edit::decision_key, edit::edit)) + .load::<(String, Json)>(conn) + .await? + .into_iter() + .map(|(key, value)| (key, value.as_value().clone())) + .collect(); + + // Delete the decisions the write omits. + let keys: HashSet<&str> = decisions.iter().map(|d| d.decision_key.as_str()).collect(); + let omitted: Vec<&str> = stored + .keys() + .map(String::as_str) + .filter(|key| !keys.contains(key)) + .collect(); + if !omitted.is_empty() { + diesel::delete( + edits::table + .filter(edit::detection_id.eq(detection_id)) + .filter(edit::decision_key.eq_any(&omitted)), + ) + .execute(conn) + .await?; + } + + // Write the new and changed decisions as the caller; an unchanged one + // is left alone, keeping its author. + for decision in decisions { + if stored.get(&decision.decision_key) == Some(decision.edit.as_value()) { + continue; + } + diesel::insert_into(edits::table) + .values(( + edit::detection_id.eq(detection_id), + edit::decision_key.eq(&decision.decision_key), + edit::account_id.eq(account_id), + edit::edit.eq(&decision.edit), + )) + .on_conflict((edit::detection_id, edit::decision_key)) + .do_update() + .set(( + edit::account_id.eq(account_id), + edit::edit.eq(&decision.edit), + edit::updated_at.eq(now), + )) + .execute(conn) + .await?; + } + + Ok(EditWriteOutcome::Updated(Box::new(detection))) + }) + .await + } + + async fn list_detection_edits( + &mut self, + detection_id: Uuid, + ) -> Result>> { + use schema::accounts; + use schema::workspace_detection_edits::{self as edits, dsl as edit}; + + let rows: Vec<(WorkspaceDetectionEdit, AccountRefRow)> = edits::table + .inner_join(accounts::table.on(edit::account_id.eq(accounts::id))) + .filter(edit::detection_id.eq(detection_id)) + .order((edit::updated_at.asc(), edit::decision_key.asc())) + .select(( + WorkspaceDetectionEdit::as_select(), + AccountRefRow::as_select(), + )) + .load(self) + .await?; + Ok(rows.into_iter().map(WithAccountRef::from).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PgConn; + use crate::model::{NewAccount, NewWorkspaceDetection}; + use crate::query::{AccountRepository, WorkspaceDetectionRepository}; + use crate::test_util::TestDatabase; + + fn decision(key: &str, value: serde_json::Value) -> NewDetectionDecision { + NewDetectionDecision { + decision_key: key.to_owned(), + edit: Json::from_raw(value), + } + } + + /// The stored decisions as `(key, author)`, in key order. + async fn authors(conn: &mut PgConn, detection_id: Uuid) -> anyhow::Result> { + let mut rows: Vec<_> = conn + .list_detection_edits(detection_id) + .await? + .into_iter() + .map(|row| (row.item.decision_key, row.account.id)) + .collect(); + rows.sort(); + Ok(rows) + } + + #[tokio::test] + async fn a_rewrite_keeps_unchanged_authors_and_attributes_the_rest() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let alice = seeded.account_id; + let mut conn = db.client.get_connection().await?; + let bob = conn.create_account(NewAccount::test()).await?.id; + let detection = conn + .create_workspace_detection(NewWorkspaceDetection::test( + seeded.workspace_id, + alice, + seeded.document_id, + )) + .await?; + + // Alice sets two decisions. + let outcome = conn + .replace_detection_edits( + seeded.workspace_id, + detection.id, + alice, + 0, + vec![ + decision("a", serde_json::json!({ "v": 1 })), + decision("b", serde_json::json!({ "v": 1 })), + ], + ) + .await?; + let EditWriteOutcome::Updated(updated) = outcome else { + panic!("the first write lands"); + }; + assert_eq!(updated.edit_set_rev, 1); + + // Bob keeps `a`, changes `b`, and adds `c`. + conn.replace_detection_edits( + seeded.workspace_id, + detection.id, + bob, + 1, + vec![ + decision("a", serde_json::json!({ "v": 1 })), + decision("b", serde_json::json!({ "v": 2 })), + decision("c", serde_json::json!({ "v": 1 })), + ], + ) + .await?; + assert_eq!( + authors(&mut conn, detection.id).await?, + vec![ + ("a".to_owned(), alice), + ("b".to_owned(), bob), + ("c".to_owned(), bob), + ] + ); + + // Alice drops `c`; the others are unchanged and keep their authors. + conn.replace_detection_edits( + seeded.workspace_id, + detection.id, + alice, + 2, + vec![ + decision("a", serde_json::json!({ "v": 1 })), + decision("b", serde_json::json!({ "v": 2 })), + ], + ) + .await?; + assert_eq!( + authors(&mut conn, detection.id).await?, + vec![("a".to_owned(), alice), ("b".to_owned(), bob),] + ); + + // An empty write clears them. + conn.replace_detection_edits(seeded.workspace_id, detection.id, bob, 3, Vec::new()) + .await?; + assert_eq!(authors(&mut conn, detection.id).await?, Vec::new()); + Ok(()) + } + + #[tokio::test] + async fn a_write_is_guarded_by_revision() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let mut conn = db.client.get_connection().await?; + let detection = conn + .create_workspace_detection(NewWorkspaceDetection::test( + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + )) + .await?; + assert_eq!(detection.edit_set_rev, 0, "a new detection starts at rev 0"); + let write = || vec![decision("a", serde_json::json!({ "v": 1 }))]; + + conn.replace_detection_edits( + seeded.workspace_id, + detection.id, + seeded.account_id, + 0, + write(), + ) + .await?; + + // Reusing the old revision is stale, and changes nothing. + let stale = conn + .replace_detection_edits( + seeded.workspace_id, + detection.id, + seeded.account_id, + 0, + Vec::new(), + ) + .await?; + assert!(matches!(stale, EditWriteOutcome::Stale)); + assert_eq!(authors(&mut conn, detection.id).await?.len(), 1); + + // A detection that does not exist is absent. + let absent = conn + .replace_detection_edits( + seeded.workspace_id, + Uuid::now_v7(), + seeded.account_id, + 0, + write(), + ) + .await?; + assert!(matches!(absent, EditWriteOutcome::Absent)); + Ok(()) + } +} diff --git a/crates/nvisy-postgres/src/query/workspace_detections.rs b/crates/nvisy-postgres/src/query/workspace_detections.rs index 8d617731..16f69987 100644 --- a/crates/nvisy-postgres/src/query/workspace_detections.rs +++ b/crates/nvisy-postgres/src/query/workspace_detections.rs @@ -20,18 +20,6 @@ use crate::types::{ }; use crate::{Error, PgConnection, Result, schema}; -/// The outcome of a guarded `edit_set` write. -#[derive(Debug, Clone)] -pub enum EditWriteOutcome { - /// The write landed; carries the updated detection (with the bumped revision). - Updated(Box), - /// The detection exists but its `edit_set_rev` no longer matches the expected - /// one — a concurrent edit won, so this write was not applied. - Stale, - /// No live detection matches in the workspace. - Absent, -} - /// Resolved display name of a detection's input document. /// /// `None` when the document has been removed (e.g. by retention). Redacted @@ -54,6 +42,13 @@ fn detection_error() -> _ { .nullable() } +#[diesel::dsl::auto_type] +fn detection_tags() -> _ { + schema::workspace_detections::metadata + .retrieve_as_object("tags") + .nullable() +} + #[diesel::dsl::auto_type] fn retained_intermediate() -> _ { diesel::dsl::exists( @@ -111,6 +106,10 @@ pub struct DetectionSummary { #[diesel(select_expression = detection_error())] #[diesel(select_expression_type = detection_error)] pub error: Option, + /// Free-form tags, without loading the rest of the metadata. + #[diesel(select_expression = detection_tags())] + #[diesel(select_expression_type = detection_tags)] + pub tags: Option>>, /// Whether an intermediate artifact is retained. #[diesel(select_expression = retained_intermediate())] #[diesel(select_expression_type = retained_intermediate)] @@ -273,25 +272,6 @@ pub trait WorkspaceDetectionRepository { detection_id: Uuid, updates: UpdateWorkspaceDetection, ) -> impl Future> + Send; - - /// Sets a live detection's accumulated reviewer edits (`edit_set`), scoped to its - /// workspace, under an optimistic-concurrency guard. `expected_rev` is the - /// `edit_set_rev` the caller read; the write proceeds and bumps the revision only - /// if it still matches. Pass `Some` to store the edits, `None` to clear them. - /// - /// Returns [`EditWriteOutcome::Updated`] with the new row, [`Stale`] when the - /// detection exists but its revision has moved on (a concurrent edit won), or - /// [`Absent`] when no live detection matches. - /// - /// [`Stale`]: EditWriteOutcome::Stale - /// [`Absent`]: EditWriteOutcome::Absent - fn set_detection_edits( - &mut self, - workspace_id: Uuid, - detection_id: Uuid, - expected_rev: i32, - edit_set: Option>, - ) -> impl Future> + Send; } impl WorkspaceDetectionRepository for PgConnection { @@ -335,56 +315,6 @@ impl WorkspaceDetectionRepository for PgConnection { .await?) } - async fn set_detection_edits( - &mut self, - workspace_id: Uuid, - detection_id: Uuid, - expected_rev: i32, - edit_set: Option>, - ) -> Result { - use schema::workspace_detections::{self, dsl}; - - // Update only when the revision still matches, bumping it so the next writer's - // stale guard trips. The whole read-decide-write is one statement, so it is - // atomic against a concurrent edit without a separate lock. - let updated: Option = diesel::update( - workspace_detections::table - .filter(dsl::id.eq(detection_id)) - .filter(dsl::workspace_id.eq(workspace_id)) - .filter(dsl::deleted_at.is_null()) - .filter(dsl::edit_set_rev.eq(expected_rev)), - ) - .set(( - dsl::edit_set.eq(edit_set), - dsl::edit_set_rev.eq(dsl::edit_set_rev + 1), - )) - .returning(WorkspaceDetection::as_returning()) - .get_result(self) - .await - .optional()?; - - if let Some(detection) = updated { - return Ok(EditWriteOutcome::Updated(Box::new(detection))); - } - - // No row updated: either the detection is gone (Absent) or its revision moved - // on (Stale). A scoped existence check separates the two. - let exists: bool = diesel::select(diesel::dsl::exists( - workspace_detections::table - .filter(dsl::id.eq(detection_id)) - .filter(dsl::workspace_id.eq(workspace_id)) - .filter(dsl::deleted_at.is_null()), - )) - .get_result(self) - .await?; - - Ok(if exists { - EditWriteOutcome::Stale - } else { - EditWriteOutcome::Absent - }) - } - async fn find_workspace_detection_by_id( &mut self, workspace_id: Uuid, @@ -703,7 +633,7 @@ mod tests { use crate::model::{NewWorkspaceDetection, UpdateWorkspaceDetection}; use crate::query::WorkspaceDetectionRepository; use crate::test_util::TestDatabase; - use crate::types::DetectionStatus; + use crate::types::{DetectionMetadata, DetectionStatus}; #[tokio::test] async fn claim_transitions_pending_and_honors_a_fresh_lease() -> anyhow::Result<()> { @@ -938,6 +868,48 @@ mod tests { Ok(()) } + #[tokio::test] + async fn cursor_list_projects_detection_tags() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let seeded = db.seed_document().await; + let mut conn = db.client.get_connection().await?; + + let mut tagged = + NewWorkspaceDetection::test(seeded.workspace_id, seeded.account_id, seeded.document_id); + tagged.metadata = Some(Json::encode(&DetectionMetadata { + tags: Some(vec!["finance".into(), "q3".into()]), + ..Default::default() + })); + let tagged = conn.create_workspace_detection(tagged).await?; + let untagged = conn + .create_workspace_detection(NewWorkspaceDetection::test( + seeded.workspace_id, + seeded.account_id, + seeded.document_id, + )) + .await?; + + let page = conn + .cursor_list_workspace_detections( + seeded.workspace_id, + CursorPagination::new(50), + &DetectionFilter::default(), + ) + .await?; + let tags_of = |id| { + page.items + .iter() + .find(|row| row.detection.id == id) + .and_then(|row| row.detection.tags.as_ref().map(Json::or_default)) + }; + assert_eq!( + tags_of(tagged.id), + Some(vec!["finance".to_owned(), "q3".to_owned()]) + ); + assert_eq!(tags_of(untagged.id), None); + Ok(()) + } + #[tokio::test] async fn cursor_list_filters_by_status_and_names_the_input_document() -> anyhow::Result<()> { let db = TestDatabase::start().await; @@ -1380,57 +1352,4 @@ mod tests { ); Ok(()) } - - #[tokio::test] - async fn set_detection_edits_is_guarded_by_revision() -> anyhow::Result<()> { - use crate::query::EditWriteOutcome; - use crate::types::Json; - - let db = TestDatabase::start().await; - let seeded = db.seed_document().await; - let mut conn = db.client.get_connection().await?; - - let detection = conn - .create_workspace_detection(NewWorkspaceDetection::test( - seeded.workspace_id, - seeded.account_id, - seeded.document_id, - )) - .await?; - assert_eq!(detection.edit_set_rev, 0, "a new detection starts at rev 0"); - - let edits = || Some(Json::from_raw(serde_json::json!({ "v": 1 }))); - - // A write at the current revision lands and bumps the revision. - let first = conn - .set_detection_edits(seeded.workspace_id, detection.id, 0, edits()) - .await?; - let EditWriteOutcome::Updated(updated) = first else { - panic!("expected the write to land"); - }; - assert_eq!(updated.edit_set_rev, 1); - - // A second write at the now-stale revision 0 is rejected, nothing changes. - let stale = conn - .set_detection_edits(seeded.workspace_id, detection.id, 0, edits()) - .await?; - assert!(matches!(stale, EditWriteOutcome::Stale)); - - // A write at the current revision 1 lands again. - let next = conn - .set_detection_edits(seeded.workspace_id, detection.id, 1, None) - .await?; - let EditWriteOutcome::Updated(cleared) = next else { - panic!("expected the write to land"); - }; - assert_eq!(cleared.edit_set_rev, 2); - assert!(cleared.edit_set.is_none(), "None clears the edits"); - - // A write against a detection that does not exist reports Absent. - let absent = conn - .set_detection_edits(seeded.workspace_id, uuid::Uuid::now_v7(), 0, edits()) - .await?; - assert!(matches!(absent, EditWriteOutcome::Absent)); - Ok(()) - } } diff --git a/crates/nvisy-postgres/src/query/workspace_reviews.rs b/crates/nvisy-postgres/src/query/workspace_reviews.rs index e8ac03c8..77ff07f6 100644 --- a/crates/nvisy-postgres/src/query/workspace_reviews.rs +++ b/crates/nvisy-postgres/src/query/workspace_reviews.rs @@ -2,11 +2,11 @@ //! an explicit approval lifecycle (0..N per document, concurrent per audience): an author, //! a title, a stream of comments and timeline events, and a status (`draft` → //! `in_review` → `changes_requested`/`partially_approved` → `approved`, reopen). It -//! is anchored to its document and points at the detection it is currently reviewing -//! and the redaction it approves (direct columns, not link tables). A review is +//! is anchored to its document; each assignee's approval names the redaction it +//! endorses, and the redaction a quorum approved is the review's output. A review is //! created explicitly (not auto-created by detection/redaction). Opening a review -//! records the `review.opened` event; renaming, repointing, assignment, and each -//! lifecycle decision (`submitted`, `changes_requested`, `approved`, `reopened`) +//! records the `review.opened` event; renaming, assignment, and each lifecycle +//! decision (`submitted`, `changes_requested`, `approved`, `reopened`) //! record their own event on the review's one timeline ([`WorkspaceReviewEvent`]), //! which the reader interleaves with the comments. //! @@ -22,7 +22,7 @@ use uuid::Uuid; use super::workspace_review_events::record_event; use crate::model::{ NewReviewAssignee, NewWorkspaceReview, UpdateWorkspaceReview, WorkspaceReview, - WorkspaceReviewEvent, + WorkspaceReviewApproval, WorkspaceReviewEvent, }; use crate::types::{ AccountRefRow, CursorPage, CursorPagination, DocumentReviewFilter, ReviewEventKind, @@ -30,7 +30,8 @@ use crate::types::{ }; use crate::{AsyncConnection, Error, PgConnection, Result, schema}; -/// A review with the people on it: its author and its assigned reviewers. +/// A review with the people on it: its author, its assigned reviewers, and their +/// approvals. #[derive(Debug, Clone)] pub struct ReviewDetails { /// The review. @@ -39,13 +40,15 @@ pub struct ReviewDetails { pub author: AccountRefRow, /// The assigned reviewers' account references (empty when unassigned). pub assignees: Vec, + /// The assignees' approvals, each naming the redaction it endorses, oldest + /// first. + pub approvals: Vec, } /// Read and write operations on document reviews. pub trait WorkspaceReviewRepository { /// Opens a new review on a document at [`ReviewStatus::Draft`], recording the - /// `review.opened` timeline event (whose target carries the detection id when it - /// opens against one), in one transaction, and returns the review. + /// `review.opened` timeline event in one transaction, and returns the review. /// `display_name` is the review's title. A document may have many concurrent /// reviews (one per audience). fn create_review( @@ -102,19 +105,6 @@ pub trait WorkspaceReviewRepository { /// hidden with the review). fn delete_review(&mut self, review_id: Uuid) -> impl Future> + Send; - /// Points a review at a detection (its current subject), recording a - /// `review.redetected` event when the target changes. Idempotent when the review - /// already points at `detection_id`. Moving an `approved` or - /// `partially_approved` review to a different detection clears its approvals - /// and approved redaction and returns it to `in_review`, since those approvals - /// endorsed the previous detection's output. Returns the review. - fn point_detection( - &mut self, - review_id: Uuid, - detection_id: Uuid, - actor: Uuid, - ) -> impl Future> + Send; - /// Assigns a reviewer to a review (idempotent). Records an `assigned` event on /// first assignment. Assignment is metadata only (who is responsible); it does /// not change the review's status. The [`AssignmentOutcome`] reports the review @@ -126,16 +116,14 @@ pub trait WorkspaceReviewRepository { actor: Uuid, ) -> impl Future> + Send; - /// Removes a reviewer from a review. Records an `unassigned` event when a link - /// existed. Does not change the review's status. The [`AssignmentOutcome`] reports - /// the review and whether a link was actually removed (`false` when the reviewer - /// was not assigned). /// Removes `account_id` from the review's assignees, recording an `unassigned` - /// event when a row was removed. If the removed reviewer had approved, their - /// approval is removed with the row, so the review's status is reconciled under - /// the same lock: should the remaining approvals fall below `required_approvals`, - /// an `approved` review is demoted (clearing its approved output) and a - /// `partially_approved` review with no approvals left returns to `in_review`. + /// event when a row was removed. The [`AssignmentOutcome`] reports whether a + /// link was removed (`false` when the reviewer was not assigned). If the removed + /// reviewer had approved, their approval goes with the row, so the review's + /// status is reconciled under the same lock, only ever downward: an `approved` + /// review whose output falls below `required_approvals` is demoted (clearing + /// its output), and a `partially_approved` review with no approvals left + /// returns to `in_review`. fn remove_assignee( &mut self, review_id: Uuid, @@ -150,7 +138,8 @@ pub trait WorkspaceReviewRepository { review_id: Uuid, ) -> impl Future>> + Send; - /// Loads the people on a review: its author and its assignees. + /// Loads the people on a review: its author, its assignees, and their + /// approvals. fn review_details( &mut self, review: WorkspaceReview, @@ -177,25 +166,25 @@ pub trait WorkspaceReviewRepository { actor: Uuid, ) -> impl Future> + Send; - /// Stamps `actor`'s approval on their assignee row (idempotent per reviewer) and - /// advances the status: once the count of approved assignees reaches - /// `required_approvals` the review becomes `approved`, otherwise - /// `partially_approved`. A given `output` binds `redaction_id` on either - /// outcome, and once bound a later approval naming a different redaction is - /// rejected (`rebind_rejected`). Records an `approved` - /// event on a new approval. Locks the review first. The caller must already be an - /// assignee (the domain layer enforces this); an un-assigned actor stamps nothing - /// and the [`ApprovalOutcome`] reports `recorded = false` with the unchanged count. + /// Records `actor`'s approval of `redaction_id` and advances the status: once + /// `required_approvals` assignees approve that same redaction the review becomes + /// `approved` with it as the output, otherwise `partially_approved`. An + /// assignee holds one approval, so approving a different redaction moves it; + /// re-approving the same one is a no-op. Records an `approved` event on a new + /// approval. Locks the review first and re-checks under the lock that it is + /// awaiting a decision. The caller must be an assignee (the domain layer + /// enforces this); an un-assigned actor records nothing, and the + /// [`ApprovalOutcome`] reports `recorded = false`. fn approve_review( &mut self, review_id: Uuid, actor: Uuid, required_approvals: u32, - output: Option, + redaction_id: Uuid, ) -> impl Future> + Send; - /// Reopens an approved review back to `in_review`, clearing its approvals and its - /// approved `redaction_id`, and recording a `reopened` event. Locks the review + /// Reopens an approved review back to `in_review`, deleting its approvals and + /// clearing its output `redaction_id`, and recording a `reopened` event. Locks the review /// first and re-checks the status under the lock: a review that is not approved is /// returned unchanged (`changed = false`), so a concurrent /// reopen that lost the race does not re-fire the event. @@ -244,19 +233,17 @@ pub struct StatusOutcome { } /// The result of an approval: the (possibly status-advanced) review, whether this -/// approval was newly recorded (`false` when the reviewer had already approved), and -/// how many distinct approvals the review now holds. +/// approval was newly recorded (`false` when the reviewer had already approved the +/// same redaction, or is not assigned), and how many approvals the named redaction +/// now holds. #[derive(Debug, Clone)] pub struct ApprovalOutcome { /// The review after the approval. pub review: WorkspaceReview, - /// Whether a new approval row was inserted (vs an idempotent re-approval). + /// Whether an approval was recorded or moved (vs an idempotent no-op). pub recorded: bool, - /// The count of distinct approvals on the review after the operation. + /// The count of approvals of the named redaction after the operation. pub approvals: u32, - /// `true` when the approval named a different output than the one already bound - /// to the review, so nothing was stamped. The domain layer maps this to a 409. - pub rebind_rejected: bool, } impl WorkspaceReviewRepository for PgConnection { @@ -269,18 +256,13 @@ impl WorkspaceReviewRepository for PgConnection { .await?; // Record the review's opening as the first timeline event, so the stream - // begins with an explicit `review.opened` entry. When the review opens - // against a detection, its target carries that detection id — the - // timeline shows the review's initial subject without a separate event. - let opened_target = review - .detection_id - .map(|detection_id| serde_json::json!({ "detectionId": detection_id })); + // begins with an explicit `review.opened` entry. record_event( conn, &review, ReviewEventKind::Opened, review.author_account_id, - opened_target, + None, ) .await?; @@ -351,8 +333,8 @@ impl WorkspaceReviewRepository for PgConnection { ) -> Result> { use schema::workspace_reviews::{self, dsl}; - // The assignee filter is a membership test against the link table, so it - // is applied as an EXISTS subquery rather than a join. + // The assignee and awaiting-approval filters are membership tests against + // the link tables, so they are applied as EXISTS subqueries, not joins. let scoped = || { let mut query = workspace_reviews::table .filter(dsl::workspace_id.eq(workspace_id)) @@ -375,6 +357,26 @@ impl WorkspaceReviewRepository for PgConnection { if let Some(review_status) = filter.review_status { query = query.filter(dsl::review_status.eq(review_status)); } + if let Some(reviewer) = filter.awaiting_approval_by { + use schema::{ + workspace_review_approvals as wrp, workspace_review_assignees as wra, + }; + query = query + .filter( + dsl::review_status + .eq_any([ReviewStatus::InReview, ReviewStatus::PartiallyApproved]), + ) + .filter(diesel::dsl::exists( + wra::table + .filter(wra::review_id.eq(dsl::id)) + .filter(wra::account_id.eq(reviewer)), + )) + .filter(diesel::dsl::not(diesel::dsl::exists( + wrp::table + .filter(wrp::review_id.eq(dsl::id)) + .filter(wrp::account_id.eq(reviewer)), + ))); + } query }; @@ -469,58 +471,6 @@ impl WorkspaceReviewRepository for PgConnection { .await } - async fn point_detection( - &mut self, - review_id: Uuid, - detection_id: Uuid, - actor: Uuid, - ) -> Result { - self.transaction(async |conn| { - let review = lock_review(conn, review_id).await?; - - // Idempotent: already pointing at this detection records nothing. - if review.detection_id == Some(detection_id) { - return Ok(review); - } - - // Approvals endorse the previous detection's output, so moving to a - // different detection drops them (and the approved redaction) and - // returns the review to in_review, as a reopen does. - let drops_approvals = matches!( - review.review_status, - ReviewStatus::Approved | ReviewStatus::PartiallyApproved - ); - if drops_approvals { - clear_approvals(conn, review_id).await?; - } - let review = apply_update( - conn, - review_id, - UpdateWorkspaceReview { - detection_id: Some(Some(detection_id)), - review_status: drops_approvals.then_some(ReviewStatus::InReview), - redaction_id: drops_approvals.then_some(None), - ..Default::default() - }, - ) - .await?; - - record_event( - conn, - &review, - ReviewEventKind::Redetected, - actor, - Some(serde_json::json!({ - "detectionId": detection_id, - "approvalsCleared": drops_approvals, - })), - ) - .await?; - Ok(review) - }) - .await - } - async fn add_assignee( &mut self, review_id: Uuid, @@ -580,16 +530,15 @@ impl WorkspaceReviewRepository for PgConnection { let review = lock_review(conn, review_id).await?; - // Capture whether this assignee had approved before deleting the row: an - // approved reviewer's removal drops one approval, so the review's status may - // need to be recomputed below. - let had_approved: Option> = wra::table - .filter(wra::review_id.eq(review_id)) - .filter(wra::account_id.eq(account_id)) - .select(wra::approved_at) - .first(conn) - .await - .optional()?; + // Whether the reviewer held an approval: deleting the assignee row + // cascades it away, which may drop the review below quorum. + let had_approval = diesel::select(diesel::dsl::exists( + schema::workspace_review_approvals::table + .filter(schema::workspace_review_approvals::review_id.eq(review_id)) + .filter(schema::workspace_review_approvals::account_id.eq(account_id)), + )) + .get_result::(conn) + .await?; let deleted = diesel::delete( wra::table @@ -616,36 +565,38 @@ impl WorkspaceReviewRepository for PgConnection { ) .await?; - // Removing an assignee who had not approved cannot change the decision, so - // the status stands. Removing one who had approved drops an approval: if the - // remaining count no longer meets quorum, demote the review under the same - // lock so it never sits `approved` (or keeps an approved output) on fewer - // approvals than the policy requires. - let removed_an_approval = matches!(had_approved, Some(Some(_))); + // Losing an approval can only demote: an approved review whose output + // falls below quorum returns to partially_approved (or in_review when no + // approvals are left) and drops its output, and a partially approved + // review with none left returns to in_review. Reconciled under the same + // lock, and never a promotion, since no one approved anything here. let mut review = review; - if removed_an_approval - && matches!( - review.review_status, - ReviewStatus::Approved | ReviewStatus::PartiallyApproved - ) - { - let approvals = count_approvals(conn, review_id).await?; - if approvals < required_approvals.max(1) { - // Below quorum: an approved review returns to in_review and drops its - // approved output; a partially-approved review with approvals left - // stays partial, and one with none left returns to in_review. - let status = if approvals == 0 { - ReviewStatus::InReview - } else { - ReviewStatus::PartiallyApproved - }; - let clear_output = review.review_status == ReviewStatus::Approved; + if had_approval { + let demoted = match (review.review_status, review.redaction_id) { + (ReviewStatus::Approved, Some(output)) + if count_approvals(conn, review_id, output).await? + < required_approvals.max(1) => + { + Some(if has_approvals(conn, review_id).await? { + ReviewStatus::PartiallyApproved + } else { + ReviewStatus::InReview + }) + } + (ReviewStatus::PartiallyApproved, _) + if !has_approvals(conn, review_id).await? => + { + Some(ReviewStatus::InReview) + } + _ => None, + }; + if let Some(status) = demoted { review = apply_update( conn, review_id, UpdateWorkspaceReview { review_status: Some(status), - redaction_id: clear_output.then_some(None), + redaction_id: Some(None), ..Default::default() }, ) @@ -757,10 +708,10 @@ impl WorkspaceReviewRepository for PgConnection { review_id: Uuid, actor: Uuid, required_approvals: u32, - output: Option, + redaction_id: Uuid, ) -> Result { self.transaction(async |conn| { - use schema::workspace_review_assignees as wra; + use schema::{workspace_review_approvals as wrap, workspace_review_assignees as wra}; let review = lock_review(conn, review_id).await?; @@ -773,91 +724,82 @@ impl WorkspaceReviewRepository for PgConnection { review.review_status, ReviewStatus::InReview | ReviewStatus::PartiallyApproved ) { - let approvals = count_approvals(conn, review_id).await?; - return Ok(ApprovalOutcome { - review, - recorded: false, - approvals, - rebind_rejected: false, - }); - } - - // Once an earlier approval has bound an output, every later approval must - // name that same redaction (or name none and inherit it). A quorum is only - // meaningful if all its approvals endorse the same output; allowing a later - // approver to rebind would mark the review approved for a redaction an - // earlier approver never saw. Checked under the lock so the binding cannot - // change between this read and the stamp below; the domain layer maps the - // rejection to a 409. - if let (Some(bound), Some(named)) = (review.redaction_id, output) - && bound != named - { - let approvals = count_approvals(conn, review_id).await?; + let approvals = count_approvals(conn, review_id, redaction_id).await?; return Ok(ApprovalOutcome { review, recorded: false, approvals, - rebind_rejected: true, }); } - // Stamp the caller's own assignee row, but only if they are assigned and - // have not already approved (approved_at IS NULL). The row count tells us - // whether this was a new approval; an un-assigned or already-approved - // caller stamps nothing. - let stamped = diesel::update( + // Only an assignee approves. The review lock serializes this check with + // the write below, so an assignee removed concurrently cannot slip in. + let assigned = diesel::select(diesel::dsl::exists( wra::table .filter(wra::review_id.eq(review_id)) - .filter(wra::account_id.eq(actor)) - .filter(wra::approved_at.is_null()), - ) - .set(wra::approved_at.eq(now)) - .execute(conn) + .filter(wra::account_id.eq(actor)), + )) + .get_result::(conn) .await?; - // Count approved assignees now on the review (including any just stamped). - let approvals = count_approvals(conn, review_id).await?; + // The caller's current approval, if any. Approving the redaction they + // already approved is a no-op; approving another moves their approval. + let current: Option = wrap::table + .filter(wrap::review_id.eq(review_id)) + .filter(wrap::account_id.eq(actor)) + .select(wrap::redaction_id) + .first(conn) + .await + .optional()?; - // Nothing stamped: the caller was not an assignee, or had already - // approved. Idempotent, no event, no status move. - if stamped == 0 { + if !assigned || current == Some(redaction_id) { + let approvals = count_approvals(conn, review_id, redaction_id).await?; return Ok(ApprovalOutcome { review, recorded: false, approvals, - rebind_rejected: false, }); } - // The approval event carries the output redaction the approver named (if - // any), so the timeline shows which redaction was approved without a - // separate event. Binding the output on each approval (partial or quorum) - // means a later approver passing no output cannot drop an earlier binding. - let approved_target = - output.map(|redaction_id| serde_json::json!({ "redactionId": redaction_id })); + diesel::insert_into(wrap::table) + .values(( + wrap::review_id.eq(review_id), + wrap::account_id.eq(actor), + wrap::redaction_id.eq(redaction_id), + )) + .on_conflict((wrap::review_id, wrap::account_id)) + .do_update() + .set(( + wrap::redaction_id.eq(redaction_id), + wrap::approved_at.eq(now), + )) + .execute(conn) + .await?; + record_event( conn, &review, ReviewEventKind::Approved, actor, - approved_target, + Some(serde_json::json!({ "redactionId": redaction_id })), ) .await?; - // Quorum met → approved; otherwise it rests at partially_approved. The - // output binding (if any) is applied either way; an absent output leaves - // the current `redaction_id` untouched. - let status = if approvals >= required_approvals.max(1) { - ReviewStatus::Approved + // Quorum on the redaction just approved → approved with it as the output; + // otherwise it rests at partially_approved with no output. Only this + // redaction is judged, so an approval never promotes a different one. + let approvals = count_approvals(conn, review_id, redaction_id).await?; + let (status, output) = if approvals >= required_approvals.max(1) { + (ReviewStatus::Approved, Some(redaction_id)) } else { - ReviewStatus::PartiallyApproved + (ReviewStatus::PartiallyApproved, None) }; let review = apply_update( conn, review_id, UpdateWorkspaceReview { review_status: Some(status), - redaction_id: output.map(Some), + redaction_id: Some(output), ..Default::default() }, ) @@ -867,7 +809,6 @@ impl WorkspaceReviewRepository for PgConnection { review, recorded: true, approvals, - rebind_rejected: false, }) }) .await @@ -1003,33 +944,47 @@ async fn apply_update( ) } -/// Counts the review's assignees that have approved (a stamped `approved_at`). -async fn count_approvals(conn: &mut PgConnection, review_id: Uuid) -> Result { - use schema::workspace_review_assignees as wra; +/// Counts the approvals of `redaction_id` on a review. +async fn count_approvals( + conn: &mut PgConnection, + review_id: Uuid, + redaction_id: Uuid, +) -> Result { + use schema::workspace_review_approvals as wrap; - let count: i64 = wra::table - .filter(wra::review_id.eq(review_id)) - .filter(wra::approved_at.is_not_null()) + let count: i64 = wrap::table + .filter(wrap::review_id.eq(review_id)) + .filter(wrap::redaction_id.eq(redaction_id)) .count() .get_result(conn) .await?; Ok(u32::try_from(count).unwrap_or(u32::MAX)) } -/// Clears every approval on a review (a pushback or reopen invalidates them), +/// Whether a review holds any approval. +async fn has_approvals(conn: &mut PgConnection, review_id: Uuid) -> Result { + use schema::workspace_review_approvals as wrap; + + Ok(diesel::select(diesel::dsl::exists( + wrap::table.filter(wrap::review_id.eq(review_id)), + )) + .get_result::(conn) + .await?) +} + +/// Deletes every approval on a review (a pushback or reopen invalidates them), /// leaving the assignments themselves in place. async fn clear_approvals(conn: &mut PgConnection, review_id: Uuid) -> Result<()> { - use schema::workspace_review_assignees as wra; + use schema::workspace_review_approvals as wrap; - diesel::update(wra::table.filter(wra::review_id.eq(review_id))) - .set(wra::approved_at.eq(None::)) + diesel::delete(wrap::table.filter(wrap::review_id.eq(review_id))) .execute(conn) .await?; Ok(()) } -/// Pairs each review with its author and its assignees, in one grouped query -/// each (no N+1), preserving the input order. A review whose author no longer +/// Pairs each review with its author, its assignees, and their approvals, in one +/// grouped query each (no N+1), preserving the input order. A review whose author no longer /// resolves is a broken invariant (the author is a live account). async fn attach_people( conn: &mut PgConnection, @@ -1063,6 +1018,20 @@ async fn attach_people( by_review.entry(review_id).or_default().push(account); } + let approval_rows: Vec = schema::workspace_review_approvals::table + .filter(schema::workspace_review_approvals::review_id.eq_any(&review_ids)) + .order(schema::workspace_review_approvals::approved_at.asc()) + .select(WorkspaceReviewApproval::as_select()) + .load(conn) + .await?; + let mut approvals_by_review: HashMap> = HashMap::new(); + for approval in approval_rows { + approvals_by_review + .entry(approval.review_id) + .or_default() + .push(approval); + } + reviews .into_iter() .map(|item| { @@ -1073,10 +1042,12 @@ async fn attach_people( Error::unexpected(format!("review {} has no author account", item.id)) })?; let assignees = by_review.remove(&item.id).unwrap_or_default(); + let approvals = approvals_by_review.remove(&item.id).unwrap_or_default(); Ok(ReviewDetails { item, author, assignees, + approvals, }) }) .collect() @@ -1087,13 +1058,13 @@ mod tests { use super::count_approvals; use crate::PgConn; use crate::model::{ - NewAccount, NewWorkspaceDetection, NewWorkspaceRedaction, NewWorkspaceReview, - NewWorkspaceReviewComment, UpdateWorkspaceReviewComment, + NewAccount, NewWorkspaceRedaction, NewWorkspaceReview, NewWorkspaceReviewComment, + UpdateWorkspaceReviewComment, }; use crate::query::{ - AccountRepository, TimelineCursor, TimelineSource, WorkspaceDetectionRepository, - WorkspaceRedactionRepository, WorkspaceReviewCommentRepository, - WorkspaceReviewEventRepository, WorkspaceReviewRepository, + AccountRepository, TimelineCursor, TimelineSource, WorkspaceRedactionRepository, + WorkspaceReviewCommentRepository, WorkspaceReviewEventRepository, + WorkspaceReviewRepository, }; use crate::test_util::TestDatabase; use crate::types::{ @@ -1111,7 +1082,6 @@ mod tests { .create_review(NewWorkspaceReview { workspace_id: seeded.workspace_id, document_id: seeded.document_id, - detection_id: None, author_account_id: seeded.account_id, display_name: "Public release".to_owned(), }) @@ -1123,7 +1093,6 @@ mod tests { .create_review(NewWorkspaceReview { workspace_id: seeded.workspace_id, document_id: seeded.document_id, - detection_id: None, author_account_id: seeded.account_id, display_name: "Court filing".to_owned(), }) @@ -1507,13 +1476,13 @@ mod tests { assert!(resubmitted.changed); assert_eq!(resubmitted.review.review_status, ReviewStatus::InReview); - // approve with a single required approval: -> approved, output recorded. A - // reviewer approves by stamping their own assignee row, so assign first. + // approve with a single required approval: -> approved, output recorded. Only + // an assignee approves, so assign first. conn.add_assignee(review.id, seeded.account_id, seeded.account_id) .await?; let redaction_id = fixture.redaction_id; let outcome = conn - .approve_review(review.id, seeded.account_id, 1, Some(redaction_id)) + .approve_review(review.id, seeded.account_id, 1, redaction_id) .await?; assert!(outcome.recorded); assert_eq!(outcome.approvals, 1); @@ -1572,44 +1541,39 @@ mod tests { .await?; conn.submit_review(review.id, seeded.account_id).await?; - // Both reviewers must be assigned to approve (approval stamps the assignee - // row). + // Both reviewers must be assigned to approve. conn.add_assignee(review.id, seeded.account_id, seeded.account_id) .await?; conn.add_assignee(review.id, bob, seeded.account_id).await?; - // First of two required approvals: partially_approved, and the named output - // is bound immediately (so a later approver passing none cannot drop it). + // First of two required approvals: partially_approved, with no output until + // quorum. let first = conn - .approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + .approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; assert!(first.recorded); assert_eq!(first.approvals, 1); assert_eq!(first.review.review_status, ReviewStatus::PartiallyApproved); - assert_eq!(first.review.redaction_id, Some(redaction_id)); + assert_eq!(first.review.redaction_id, None); // The same reviewer approving again is an idempotent no-op. let again = conn - .approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + .approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; assert!(!again.recorded); assert_eq!(again.approvals, 1); assert_eq!(again.review.review_status, ReviewStatus::PartiallyApproved); - // Requesting changes while partially approved clears the accumulated approval - // (and its bound output), so quorum must be met afresh. + // Requesting changes while partially approved deletes the accumulated + // approval, so quorum must be met afresh. let pushed_back = conn.request_changes(review.id, seeded.account_id).await?; assert_eq!( pushed_back.review.review_status, ReviewStatus::ChangesRequested ); - assert_eq!( - pushed_back.review.redaction_id, None, - "the invalidated approval's output is cleared" - ); conn.submit_review(review.id, seeded.account_id).await?; let after = conn - .approve_review(review.id, seeded.account_id, 2, None) + .approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; assert_eq!( after.approvals, 1, @@ -1617,16 +1581,18 @@ mod tests { ); assert_eq!(after.review.review_status, ReviewStatus::PartiallyApproved); - // The second distinct approval now meets quorum again: approved. - let second = conn.approve_review(review.id, bob, 2, None).await?; + // The second approval of the same redaction meets quorum: approved, with it + // as the output. + let second = conn.approve_review(review.id, bob, 2, redaction_id).await?; assert!(second.recorded); assert_eq!(second.approvals, 2); assert_eq!(second.review.review_status, ReviewStatus::Approved); + assert_eq!(second.review.redaction_id, Some(redaction_id)); Ok(()) } #[tokio::test] - async fn a_quorum_approval_without_output_keeps_an_earlier_one() -> anyhow::Result<()> { + async fn approvals_of_different_redactions_do_not_combine() -> anyhow::Result<()> { let db = TestDatabase::start().await; let fixture = db.seed_detection_and_redaction().await; let seeded = fixture.seeded; @@ -1637,6 +1603,15 @@ mod tests { }; let mut conn = db.client.get_connection().await?; + // A second redaction of the same detection: a different, equally valid output. + let other_redaction = conn + .create_redaction(NewWorkspaceRedaction::test( + fixture.detection_id, + seeded.account_id, + )) + .await? + .id; + let review = conn .create_review(NewWorkspaceReview::test( seeded.workspace_id, @@ -1649,32 +1624,47 @@ mod tests { .await?; conn.add_assignee(review.id, bob, seeded.account_id).await?; - // The first approver names the output; the quorum-meeting approver names none. - conn.approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + // Two approvals of two different redactions are not a quorum of two: each + // redaction has one, so the review stays partially approved with no output. + conn.approve_review(review.id, seeded.account_id, 2, redaction_id) + .await?; + let split = conn + .approve_review(review.id, bob, 2, other_redaction) .await?; - let approved = conn.approve_review(review.id, bob, 2, None).await?; + assert!(split.recorded); + assert_eq!(split.approvals, 1); + assert_eq!(split.review.review_status, ReviewStatus::PartiallyApproved); + assert_eq!(split.review.redaction_id, None); - // The review is approved and keeps the output the first approver bound; the - // absent output on the final approval does not clear it. - assert_eq!(approved.review.review_status, ReviewStatus::Approved); - assert_eq!(approved.review.redaction_id, Some(redaction_id)); + // Bob approving the first redaction moves his approval to it: quorum. + let agreed = conn.approve_review(review.id, bob, 2, redaction_id).await?; + assert!(agreed.recorded); + assert_eq!(agreed.approvals, 2); + assert_eq!(agreed.review.review_status, ReviewStatus::Approved); + assert_eq!(agreed.review.redaction_id, Some(redaction_id)); + assert_eq!( + count_approvals(&mut conn, review.id, other_redaction).await?, + 0, + "the moved approval no longer counts for the other redaction" + ); Ok(()) } #[tokio::test] - async fn a_later_approval_cannot_rebind_the_output() -> anyhow::Result<()> { + async fn a_lowered_quorum_promotes_only_the_redaction_approved() -> anyhow::Result<()> { let db = TestDatabase::start().await; let fixture = db.seed_detection_and_redaction().await; let seeded = fixture.seeded; - let redaction_id = fixture.redaction_id; - let bob = { + let leading = fixture.redaction_id; + let mut reviewers = Vec::new(); + for _ in 0..3 { let mut conn = db.client.get_connection().await?; - conn.create_account(NewAccount::test()).await?.id - }; + reviewers.push(conn.create_account(NewAccount::test()).await?.id); + } + let (alice, bob, carol) = (reviewers[0], reviewers[1], reviewers[2]); let mut conn = db.client.get_connection().await?; - // A second redaction of the same detection: a valid, different output. - let other_redaction = conn + let other = conn .create_redaction(NewWorkspaceRedaction::test( fixture.detection_id, seeded.account_id, @@ -1690,32 +1680,38 @@ mod tests { )) .await?; conn.submit_review(review.id, seeded.account_id).await?; - conn.add_assignee(review.id, seeded.account_id, seeded.account_id) - .await?; - conn.add_assignee(review.id, bob, seeded.account_id).await?; + for reviewer in [alice, bob, carol] { + conn.add_assignee(review.id, reviewer, seeded.account_id) + .await?; + } - // The first approver binds one output. - conn.approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) - .await?; + // Under a quorum of three, two approvals of one redaction leave it partial. + conn.approve_review(review.id, alice, 3, leading).await?; + conn.approve_review(review.id, bob, 3, leading).await?; - // A second approver naming a different output is rejected under the lock: - // nothing is stamped, the binding stands, and the status does not advance. - let rebind = conn - .approve_review(review.id, bob, 2, Some(other_redaction)) - .await?; - assert!(rebind.rebind_rejected); - assert!(!rebind.recorded); - assert_eq!(rebind.approvals, 1); - assert_eq!(rebind.review.review_status, ReviewStatus::PartiallyApproved); - assert_eq!(rebind.review.redaction_id, Some(redaction_id)); + // The quorum is lowered to two, and Carol approves a different redaction. + // Only Carol's redaction is judged: one approval is not a quorum, so the + // review stays partial rather than approving the other redaction. + let outcome = conn.approve_review(review.id, carol, 2, other).await?; + assert!(outcome.recorded); + assert_eq!(outcome.approvals, 1); + assert_eq!( + outcome.review.review_status, + ReviewStatus::PartiallyApproved + ); + assert_eq!(outcome.review.redaction_id, None); - // The second approver endorsing the already-bound output meets quorum. - let agreed = conn - .approve_review(review.id, bob, 2, Some(redaction_id)) + // Unassigning a reviewer never promotes: Carol held the only approval of + // the other redaction, and the leading one stays short of an approval. + let removed = conn + .remove_assignee(review.id, carol, seeded.account_id, 2) .await?; - assert!(agreed.recorded); - assert_eq!(agreed.review.review_status, ReviewStatus::Approved); - assert_eq!(agreed.review.redaction_id, Some(redaction_id)); + assert!(removed.changed); + assert_eq!( + removed.review.review_status, + ReviewStatus::PartiallyApproved + ); + assert_eq!(removed.review.redaction_id, None); Ok(()) } @@ -1737,7 +1733,7 @@ mod tests { conn.submit_review(review.id, seeded.account_id).await?; conn.add_assignee(review.id, seeded.account_id, seeded.account_id) .await?; - conn.approve_review(review.id, seeded.account_id, 1, Some(redaction_id)) + conn.approve_review(review.id, seeded.account_id, 1, redaction_id) .await?; // A submit racing in after the review is approved finds it in a non-submittable @@ -1747,9 +1743,9 @@ mod tests { assert_eq!(outcome.review.review_status, ReviewStatus::Approved); assert_eq!(outcome.review.redaction_id, Some(redaction_id)); assert_eq!( - count_approvals(&mut conn, review.id).await?, + count_approvals(&mut conn, review.id, redaction_id).await?, 1, - "the approval stamp survives the no-op submit" + "the approval survives the no-op submit" ); Ok(()) } @@ -1779,9 +1775,9 @@ mod tests { conn.add_assignee(review.id, bob, seeded.account_id).await?; // Two approvals meet a quorum of two: approved, output bound. - conn.approve_review(review.id, seeded.account_id, 2, Some(redaction_id)) + conn.approve_review(review.id, seeded.account_id, 2, redaction_id) .await?; - let approved = conn.approve_review(review.id, bob, 2, None).await?; + let approved = conn.approve_review(review.id, bob, 2, redaction_id).await?; assert_eq!(approved.review.review_status, ReviewStatus::Approved); // Removing one approver drops to one approval, below the quorum of two: the @@ -1842,6 +1838,65 @@ mod tests { Ok(()) } + #[tokio::test] + async fn queue_filters_to_reviews_awaiting_an_approval() -> anyhow::Result<()> { + let db = TestDatabase::start().await; + let fixture = db.seed_detection_and_redaction().await; + let seeded = fixture.seeded; + let me = seeded.account_id; + let bob = { + let mut conn = db.client.get_connection().await?; + conn.create_account(NewAccount::test()).await?.id + }; + let mut conn = db.client.get_connection().await?; + let open = async |conn: &mut PgConn| { + conn.create_review(NewWorkspaceReview::test( + seeded.workspace_id, + seeded.document_id, + me, + )) + .await + }; + + // Awaiting me: assigned, submitted, and only bob has approved. + let waiting = open(&mut conn).await?; + conn.add_assignee(waiting.id, me, me).await?; + conn.add_assignee(waiting.id, bob, me).await?; + conn.submit_review(waiting.id, me).await?; + conn.approve_review(waiting.id, bob, 2, fixture.redaction_id) + .await?; + + // Not awaiting me: I already approved it. + let approved = open(&mut conn).await?; + conn.add_assignee(approved.id, me, me).await?; + conn.submit_review(approved.id, me).await?; + conn.approve_review(approved.id, me, 2, fixture.redaction_id) + .await?; + + // Not awaiting me: still a draft. + let draft = open(&mut conn).await?; + conn.add_assignee(draft.id, me, me).await?; + + // Not awaiting me: submitted, but assigned to bob only. + let elsewhere = open(&mut conn).await?; + conn.add_assignee(elsewhere.id, bob, me).await?; + conn.submit_review(elsewhere.id, me).await?; + + let queue = conn + .cursor_list_reviews( + seeded.workspace_id, + CursorPagination::new(50), + &DocumentReviewFilter { + awaiting_approval_by: Some(me), + ..Default::default() + }, + ) + .await?; + let ids: Vec<_> = queue.items.iter().map(|row| row.item.id).collect(); + assert_eq!(ids, vec![waiting.id]); + Ok(()) + } + /// A timeline entry's sort key: `(created_at, source, id)`. type Entry = (jiff::Timestamp, TimelineSource, uuid::Uuid); @@ -1971,74 +2026,4 @@ mod tests { assert_eq!(paged, all); Ok(()) } - - #[tokio::test] - async fn pointing_at_another_detection_drops_approvals() -> anyhow::Result<()> { - let db = TestDatabase::start().await; - let fixture = db.seed_detection_and_redaction().await; - let seeded = fixture.seeded; - let mut conn = db.client.get_connection().await?; - - let review = conn - .create_review(NewWorkspaceReview::test( - seeded.workspace_id, - seeded.document_id, - seeded.account_id, - )) - .await?; - conn.point_detection(review.id, fixture.detection_id, seeded.account_id) - .await?; - conn.submit_review(review.id, seeded.account_id).await?; - conn.add_assignee(review.id, seeded.account_id, seeded.account_id) - .await?; - let approved = conn - .approve_review(review.id, seeded.account_id, 1, Some(fixture.redaction_id)) - .await?; - assert_eq!(approved.review.review_status, ReviewStatus::Approved); - - // Re-pointing at the same detection is a no-op: the approval stands. - let same = conn - .point_detection(review.id, fixture.detection_id, seeded.account_id) - .await?; - assert_eq!(same.review_status, ReviewStatus::Approved); - assert_eq!(same.redaction_id, Some(fixture.redaction_id)); - - // A different detection drops the approvals and the approved output. - let redetected = conn - .create_workspace_detection(NewWorkspaceDetection::test( - seeded.workspace_id, - seeded.account_id, - seeded.document_id, - )) - .await?; - let moved = conn - .point_detection(review.id, redetected.id, seeded.account_id) - .await?; - assert_eq!(moved.detection_id, Some(redetected.id)); - assert_eq!(moved.review_status, ReviewStatus::InReview); - assert_eq!(moved.redaction_id, None); - assert_eq!(count_approvals(&mut conn, review.id).await?, 0); - Ok(()) - } - - #[tokio::test] - async fn pointing_an_unapproved_review_keeps_its_status() -> anyhow::Result<()> { - let db = TestDatabase::start().await; - let fixture = db.seed_detection_and_redaction().await; - let seeded = fixture.seeded; - let mut conn = db.client.get_connection().await?; - - let review = conn - .create_review(NewWorkspaceReview::test( - seeded.workspace_id, - seeded.document_id, - seeded.account_id, - )) - .await?; - let moved = conn - .point_detection(review.id, fixture.detection_id, seeded.account_id) - .await?; - assert_eq!(moved.review_status, ReviewStatus::Draft); - Ok(()) - } } diff --git a/crates/nvisy-postgres/src/schema.rs b/crates/nvisy-postgres/src/schema.rs index 04523284..f082143b 100644 --- a/crates/nvisy-postgres/src/schema.rs +++ b/crates/nvisy-postgres/src/schema.rs @@ -255,6 +255,19 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + + workspace_detection_edits (detection_id, decision_key) { + detection_id -> Uuid, + decision_key -> Text, + account_id -> Uuid, + edit -> Jsonb, + created_at -> Timestamptz, + updated_at -> Timestamptz, + } +} + diesel::table! { use diesel::sql_types::*; use super::sql_types::OutboxStatus; @@ -297,7 +310,6 @@ diesel::table! { idempotency_key -> Nullable, retention_override -> Nullable, metadata -> Jsonb, - edit_set -> Nullable, edit_set_rev -> Int4, claimed_at -> Nullable, started_at -> Timestamptz, @@ -478,6 +490,17 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + + workspace_review_approvals (review_id, account_id) { + review_id -> Uuid, + account_id -> Uuid, + redaction_id -> Uuid, + approved_at -> Timestamptz, + } +} + diesel::table! { use diesel::sql_types::*; @@ -485,7 +508,6 @@ diesel::table! { review_id -> Uuid, account_id -> Uuid, created_at -> Timestamptz, - approved_at -> Nullable, } } @@ -526,7 +548,6 @@ diesel::table! { id -> Uuid, workspace_id -> Uuid, document_id -> Uuid, - detection_id -> Nullable, redaction_id -> Nullable, author_account_id -> Uuid, display_name -> Text, @@ -592,6 +613,8 @@ diesel::joinable!(workspace_connection_syncs -> accounts (account_id)); diesel::joinable!(workspace_connection_syncs -> workspace_connections (connection_id)); diesel::joinable!(workspace_connections -> accounts (account_id)); diesel::joinable!(workspace_connections -> workspaces (workspace_id)); +diesel::joinable!(workspace_detection_edits -> accounts (account_id)); +diesel::joinable!(workspace_detection_edits -> workspace_detections (detection_id)); diesel::joinable!(workspace_detection_jobs -> workspace_detections (detection_id)); diesel::joinable!(workspace_detection_policy_versions -> workspace_detections (detection_id)); diesel::joinable!(workspace_detection_policy_versions -> workspace_policy_versions (policy_version_id)); @@ -619,6 +642,7 @@ diesel::joinable!(workspace_redactions -> accounts (account_id)); diesel::joinable!(workspace_redactions -> workspace_blobs (review_audit_blob_id)); diesel::joinable!(workspace_redactions -> workspace_detections (detection_id)); diesel::joinable!(workspace_redactions -> workspace_documents (output_document_id)); +diesel::joinable!(workspace_review_approvals -> workspace_redactions (redaction_id)); diesel::joinable!(workspace_review_assignees -> accounts (account_id)); diesel::joinable!(workspace_review_assignees -> workspace_reviews (review_id)); diesel::joinable!(workspace_review_comments -> accounts (author_account_id)); @@ -626,7 +650,6 @@ diesel::joinable!(workspace_review_comments -> workspace_reviews (review_id)); diesel::joinable!(workspace_review_events -> accounts (actor_account_id)); diesel::joinable!(workspace_review_events -> workspace_reviews (review_id)); diesel::joinable!(workspace_reviews -> accounts (author_account_id)); -diesel::joinable!(workspace_reviews -> workspace_detections (detection_id)); diesel::joinable!(workspace_reviews -> workspace_redactions (redaction_id)); diesel::joinable!(workspace_reviews -> workspaces (workspace_id)); diesel::joinable!(workspace_webhooks -> accounts (created_by)); @@ -644,6 +667,7 @@ diesel::allow_tables_to_appear_in_same_query!( workspace_connection_schedule, workspace_connection_syncs, workspace_connections, + workspace_detection_edits, workspace_detection_jobs, workspace_detection_policy_versions, workspace_detections, @@ -657,6 +681,7 @@ diesel::allow_tables_to_appear_in_same_query!( workspace_policy_versions, workspace_providers, workspace_redactions, + workspace_review_approvals, workspace_review_assignees, workspace_review_comments, workspace_review_events, diff --git a/crates/nvisy-postgres/src/types/enums/review_event_kind.rs b/crates/nvisy-postgres/src/types/enums/review_event_kind.rs index 43cf4bc2..d93fdc33 100644 --- a/crates/nvisy-postgres/src/types/enums/review_event_kind.rs +++ b/crates/nvisy-postgres/src/types/enums/review_event_kind.rs @@ -7,17 +7,13 @@ db_enum! { /// /// Corresponds to the `REVIEW_EVENT_KIND` `PostgreSQL` enum. A review's stream /// interleaves comments (messages) with these events: the lifecycle (opened, - /// renamed, submitted, changes requested, approved, reopened), re-detection, and - /// assignment changes. + /// renamed, submitted, changes requested, approved, reopened) and assignment + /// changes. pub enum ReviewEventKind = "crate::schema::sql_types::ReviewEventKind" { - /// The review was opened. Its target carries the initial detection id, when - /// the review was opened against one. + /// The review was opened. Opened = "review.opened", /// The review's display name was changed. Renamed = "review.renamed", - /// The review was repointed at a newer detection (the document was - /// re-detected). Its target carries the new detection id. - Redetected = "review.redetected", /// The review was assigned to a reviewer. Assigned = "review.assigned", /// A reviewer was unassigned. @@ -26,8 +22,8 @@ db_enum! { Submitted = "review.submitted", /// A reviewer requested changes. ChangesRequested = "review.changes_requested", - /// A reviewer approved the review (quorum may require more approvals). Its - /// target carries the approved output redaction id, when one was named. + /// A reviewer approved one redaction of the review's document (quorum may + /// require more approvals of it). Its target carries that redaction id. Approved = "review.approved", /// An approved review was reopened (back to `in_review`). Reopened = "review.reopened", diff --git a/crates/nvisy-postgres/src/types/enums/review_status.rs b/crates/nvisy-postgres/src/types/enums/review_status.rs index 06ffe8f5..9a7455b9 100644 --- a/crates/nvisy-postgres/src/types/enums/review_status.rs +++ b/crates/nvisy-postgres/src/types/enums/review_status.rs @@ -10,11 +10,10 @@ db_enum! { /// explicit reviewer decisions, not by assignment: a review opens at `Draft`; /// `submit` moves it to `InReview`; a reviewer can `request-changes` /// (`ChangesRequested`, from which `submit` returns it to `InReview`) or - /// `approve`. An approval reaches `Approved` once the workspace's required number - /// of distinct approvals is met, and rests at `PartiallyApproved` in between - /// (only reachable when two or more approvals are required). Reopening an - /// `Approved` review returns it to `InReview`, as does pointing a review that - /// has approvals at a different detection. + /// `approve`. Each approval names one redaction of the document, and only + /// approvals of the same redaction count toward the workspace's required + /// number. Requesting changes and reopening clear every approval. Unassigning + /// an approver deletes their approval, which can only demote the review. pub enum ReviewStatus: Default = Draft, "crate::schema::sql_types::ReviewStatus" { /// Opened, edits being assembled; `submit` sends it for review. Draft = "draft", @@ -22,13 +21,13 @@ db_enum! { InReview = "in_review", /// A reviewer requested changes; `submit` returns it to `InReview`. ChangesRequested = "changes_requested", - /// Some, but not all, required approvals are in. Only reachable when the - /// workspace requires two or more approvals. An approver may already have - /// bound the redaction the remaining approvals must endorse. + /// At least one approval is in, but no redaction has the required number + /// of approvals yet. Only reachable when the workspace requires two or + /// more. Approvals of different redactions do not combine. PartiallyApproved = "partially_approved", - /// Signed off: the required approvals are in. When an approver named a - /// redaction, that redaction is the review's output; otherwise the review - /// has none. + /// Signed off: one redaction has the required number of approvals, and + /// it is the review's output (`redactionId`). Reopening returns the review + /// to `InReview`. Approved = "approved", } } diff --git a/crates/nvisy-postgres/src/types/filtering/reviews.rs b/crates/nvisy-postgres/src/types/filtering/reviews.rs index 41621525..2ceba987 100644 --- a/crates/nvisy-postgres/src/types/filtering/reviews.rs +++ b/crates/nvisy-postgres/src/types/filtering/reviews.rs @@ -25,4 +25,8 @@ pub struct DocumentReviewFilter { /// Filter by review status. #[serde(skip_serializing_if = "Option::is_none")] pub review_status: Option, + /// Filter to the reviews awaiting this account's approval: it is assigned, + /// the review is `InReview` or `PartiallyApproved`, and it has not approved. + #[serde(skip_serializing_if = "Option::is_none")] + pub awaiting_approval_by: Option, } diff --git a/crates/nvisy-server/Cargo.toml b/crates/nvisy-server/Cargo.toml index 35bcd9e5..e827e320 100644 --- a/crates/nvisy-server/Cargo.toml +++ b/crates/nvisy-server/Cargo.toml @@ -153,6 +153,9 @@ ipnet = { workspace = true, features = [] } url = { workspace = true, features = [] } [dev-dependencies] +# Elide crates +elide = { workspace = true, features = ["engine"] } + # Internal crates nvisy-nats = { workspace = true, features = [] } nvisy-postgres = { workspace = true, features = ["schema", "test_util"] } diff --git a/crates/nvisy-server/src/args.rs b/crates/nvisy-server/src/args.rs index e12400f6..17272919 100644 --- a/crates/nvisy-server/src/args.rs +++ b/crates/nvisy-server/src/args.rs @@ -21,7 +21,7 @@ use crate::middleware::UploadConfig; use crate::response::CookieConfig; use crate::service::{ AuthKeysConfig, CryptoConfig, EngineConfig, FileConnectorsConfig, HealthConfig, - IntegrationConfig, OidcConfig, S3Config, + IntegrationConfig, OidcConfig, S3Config, SignupConfig, }; use crate::worker::purge::PurgeConfig; @@ -30,7 +30,7 @@ pub(crate) const TRACING_TARGET_CONFIG: &str = "nvisy_server::args"; /// Every external-service and resource config [`ServiceState`] is built from. /// -/// Grouped so a binary flattens one struct rather than the ten configs it wraps; +/// Grouped so a binary flattens one struct rather than every config it wraps; /// [`ServiceState::from_config`] consumes it. The `clap::Args` derive is gated on /// the `cli` feature. /// @@ -100,6 +100,10 @@ pub struct ServiceArgs { /// Session-cookie policy (the `Secure` attribute) for browser clients. #[cfg_attr(feature = "cli", clap(flatten, next_help_heading = "Session cookies"))] pub cookie: CookieConfig, + + /// Sign-up policy (whether new accounts can be created). + #[cfg_attr(feature = "cli", clap(flatten, next_help_heading = "Sign-up"))] + pub signup: SignupConfig, } impl ServiceArgs { diff --git a/crates/nvisy-server/src/domain/detection_decisions.rs b/crates/nvisy-server/src/domain/detection_decisions.rs new file mode 100644 index 00000000..3c569eb0 --- /dev/null +++ b/crates/nvisy-server/src/domain/detection_decisions.rs @@ -0,0 +1,507 @@ +//! A detection's reviewer edits as attributed decisions. +//! +//! An [`EditSet`] is stored one decision per row, each keyed by what it is about, +//! so a rewrite can tell which decisions changed and credit only those to the +//! writer. [`split`] turns a set into keyed decisions, [`merge`] joins decisions +//! back into one set, and [`apply`] lands them on a report under each decision's +//! author, so every audit event names the reviewer who made that decision. +//! +//! Keys follow elide's own channels: a retag is split into its relabel and its +//! relocation, so two reviewers correcting one entity's label and span are each +//! credited with their own correction. An added entity has no id until it is +//! applied, so it is keyed by its content: identical adds redact the same span, +//! so they are one decision. + +use elide_pipeline::Report; +use elide_pipeline::entity::{ + AuditKind, Edit, EditBucket, EditSet, HiddenChoices, HiddenContentEdits, Retag, +}; +use elide_pipeline::modality::{Audio, Image, Modality, Tabular, Text}; +use nvisy_postgres::model::WorkspaceDetectionEdit; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +use crate::response::{ErrorKind, Result}; + +/// One reviewer decision: an [`EditSet`] holding exactly one edit, and the key +/// naming what it is about. +#[derive(Debug, Clone)] +pub(crate) struct Decision { + /// What the decision is about: its modality, channel, and target. + pub key: String, + /// The decision itself. + pub edits: EditSet, +} + +/// Splits `edits` into one [`Decision`] per question it answers. +/// +/// A retag setting both a label and a location becomes two decisions. A +/// decision repeated within the set collapses into one, the last one kept; for +/// an added entity, a repeat is an identical add, which redacts the same span. +/// +/// # Errors +/// +/// - `InternalServerError` if an edit cannot be encoded for its key. +pub(crate) fn split(edits: &EditSet) -> Result> { + let mut decisions = Decisions::default(); + split_bucket::(edits, &mut decisions)?; + split_bucket::(edits, &mut decisions)?; + split_bucket::(edits, &mut decisions)?; + split_bucket::