diff --git a/AGENTS.md b/AGENTS.md index b0a068c8..872811cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,7 +52,7 @@ Seven terms have exactly one meaning each, everywhere in this repository: code c - If Cargo rejects a dependency cycle, the design is wrong, not the graph. - Pseudo-random test input comes only from a fixed seed that the failure prints. Temporary directory names come from the test's name, the process id, and a counter. -- A file holds one concept and has no length limit. Split a file only when it holds a second unrelated concept. Size limits sit on functions and types, and clippy and `cargo test -p build-xtask` enforce them. Split an oversized type by responsibility; a new entry in the allowlist in `crates/build-xtask/src/type_size.rs` is a plan decision with a reason, never a way to make a change pass. +- 1 file holds 1 domain concept with no length limit. Split a file only when it holds a second unrelated concept. - Production code uses the standard module layout: `foo.rs`, with `foo/bar.rs` for its children. No `#[path]`, and no inline `mod` blocks. A module never has exactly one child file (tests aside): merge it, or make it a peer module `foo_bar.rs` declared beside `foo.rs`. - Test code goes at the bottom of the file under test in a `#[cfg(test)] mod tests { }` block when practical (if in doubt, beside), and otherwise in `foo-tests.rs` beside it, wired with `#[path = "foo-tests.rs"] mod tests;`. A big test file may split by topic into siblings named after it, `-.rs` (so `foo-tests-topic.rs`). These are the only files wired with `#[path]`, so a hyphen in a file name means test code. Top-level `tests/` and `benches/` trees follow Cargo's conventions. - The crates in this repository keep their older layout until their own pass. diff --git a/Cargo.toml b/Cargo.toml index 201bb70f..ff82404c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -197,3 +197,5 @@ doc_markdown = "allow" # `assert_eq!(x, [] as [T; 0])`, which has to spell out the element type and # needs `T: PartialEq + Debug`, so it cannot be applied to most call sites. assert_is_empty = "allow" +too_many_lines = "allow" +too_many_arguments = "allow" diff --git a/clippy.toml b/clippy.toml index 00803dd2..36460a2e 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,11 +1,6 @@ allow-unwrap-in-tests = true allow-expect-in-tests = true -# Size limits sit on functions (here) and on types (build-xtask's -# type-size check). A file has no length limit. -too-many-lines-threshold = 100 -too-many-arguments-threshold = 7 - # Process-global installers. Only a binary entry point may call one, under # `#[expect(clippy::disallowed_methods, reason = ...)]`. No entry names a # `replacement`, because no alternative takes the same arguments and returns diff --git a/crates/build-xtask/src/main.rs b/crates/build-xtask/src/main.rs index 59e3fd8e..2668c4ac 100644 --- a/crates/build-xtask/src/main.rs +++ b/crates/build-xtask/src/main.rs @@ -13,7 +13,6 @@ mod new_crate; mod no_doctests; mod product; mod tidy; -mod type_size; mod unsafe_allowlist; use std::path::Path; diff --git a/crates/build-xtask/src/tidy.rs b/crates/build-xtask/src/tidy.rs index 8fb79a03..e95130c7 100644 --- a/crates/build-xtask/src/tidy.rs +++ b/crates/build-xtask/src/tidy.rs @@ -2,9 +2,8 @@ //! the product boundary (run from `product`), the pin on the crates that //! come from runvil-harness (run from `harness_pin`), the doctest ban over //! every workspace crate (run from `no_doctests`), the `Debug` trait's one -//! spelling over every workspace crate (run from `debug_spelling`), the -//! unsafe allowlist (run from `unsafe_allowlist`), and the type-size -//! limits over every workspace crate (run from `type_size`). +//! spelling over every workspace crate (run from `debug_spelling`), and the +//! unsafe allowlist (run from `unsafe_allowlist`). //! //! Each check returns a list of human-readable violations. The `#[test]` //! wrappers assert the lists are empty, so `cargo test -p build-xtask` @@ -68,7 +67,6 @@ pub(crate) fn all_violations(root: &Path) -> Vec { violations.extend(crate::harness_pin::harness_pin_violations(root)); violations.extend(crate::no_doctests::no_doctests_violations(root)); violations.extend(crate::debug_spelling::debug_spelling_violations(root)); - violations.extend(crate::type_size::type_size_violations(root)); violations } diff --git a/crates/build-xtask/src/type_size.rs b/crates/build-xtask/src/type_size.rs deleted file mode 100644 index 6b2c2322..00000000 --- a/crates/build-xtask/src/type_size.rs +++ /dev/null @@ -1,712 +0,0 @@ -//! The type-size limits: a type's inherent methods, summed across every -//! `impl` block in its crate, stay at or under [`MAX_METHODS`], and a -//! struct's named fields stay at or under [`MAX_FIELDS`], unless -//! [`ALLOWED`] records the type with a reason. Runs as part of -//! `cargo test -p build-xtask` and `cargo xtask tidy`. -//! -//! The limits sit on types because a file has no length limit: a type's -//! methods may live in any number of files, so the count sums every -//! inherent `impl` block in the crate. Trait impls are not counted, -//! because the trait fixes their methods. -//! -//! The check reads syntax, so it keys a type by its crate and the last -//! segment of the name an `impl` gives it: two types of one name in one -//! crate are summed, and an `impl` that a macro expands to is not seen. -//! It reads each crate's `src/` tree, skipping test files by name and -//! every item behind a `cfg` that names `test`; a test-support file that -//! only a gated `mod` line reaches is still read. - -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; - -use proc_macro2::{TokenStream, TokenTree}; -use syn::{Attribute, Fields, Ident, ImplItem, Item, Meta, Type}; - -/// The most inherent methods one type may have, summed across every -/// `impl` block in its crate. -const MAX_METHODS: usize = 25; - -/// The most named fields one struct may have. -const MAX_FIELDS: usize = 12; - -/// The types over a limit today. A new entry is a plan decision with a -/// reason, never a way to make a change pass. -const ALLOWED: &[Allowed] = &[ - Allowed { - krate: "crates/workshop/gateway-discovery", - name: "ProcBsdInfo", - limit: Limit::Fields, - recorded: 22, - reason: "A `#[repr(C)]` mirror of the stable prefix of Darwin's `proc_bsdinfo`, \ - whose fields the OS fixes.", - }, - Allowed { - krate: "crates/workshop/workspace", - name: "Workspace", - limit: Limit::Methods, - recorded: 39, - reason: "The workspace every route shares: the grant set and confinement plus the \ - backing file's open, save-as, duplicate, and persistence, on one cloneable \ - state so a new grant reaches every handler at once.", - }, -]; - -/// The limit an [`Allowed`] entry lifts. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum Limit { - /// [`MAX_METHODS`]. - Methods, - /// [`MAX_FIELDS`]. - Fields, -} - -impl Limit { - /// The count every type without an entry is held to. - fn bound(self) -> usize { - match self { - Limit::Methods => MAX_METHODS, - Limit::Fields => MAX_FIELDS, - } - } - - /// What the limit counts, as a violation names it. - fn noun(self) -> &'static str { - match self { - Limit::Methods => "inherent methods across its `impl` blocks", - Limit::Fields => "named fields", - } - } - - /// The rule a type without an entry breaks by passing the limit. - fn rule(self) -> &'static str { - match self { - Limit::Methods => "type over the inherent method limit", - Limit::Fields => "struct over the named field limit", - } - } -} - -/// A type that may pass one limit, up to the count recorded when the -/// entry was written. The type may shrink without the entry changing; it -/// fails when it grows past `recorded`, and the entry fails as stale once -/// the type is gone or back within the limit. -struct Allowed { - /// The crate directory, relative to the workspace root, with `/` - /// separators. - krate: &'static str, - /// The type's name. - name: &'static str, - /// The limit the entry lifts. - limit: Limit, - /// The most the type may count; one more fails. - recorded: usize, - /// What the type is and why its size holds, in one sentence. - reason: &'static str, -} - -/// Each counted type's count, keyed by crate directory, type name, and -/// limit, for the stale-entry pass. -type Counts = BTreeMap<(String, String, Limit), usize>; - -/// A definition or `impl` block: its file, relative to the workspace root -/// with `/` separators, and its line. -#[derive(Clone)] -struct Site { - path: String, - line: usize, -} - -/// One type's inherent methods: its first `impl` block, and how many -/// methods each file, relative to the crate, gives it. -struct Tally { - first: Site, - files: BTreeMap, -} - -impl Tally { - /// Each file's share, as `src/a.rs 8, src/b.rs 3`. - fn breakdown(&self) -> String { - self.files - .iter() - .map(|(file, count)| format!("{file} {count}")) - .collect::>() - .join(", ") - } -} - -/// What one crate's sources hold. -#[derive(Default)] -struct Census { - /// Each type's inherent methods, by type name. - methods: BTreeMap, - /// Each struct with named fields: its name, its definition, and its - /// field count. - structs: Vec<(String, Site, usize)>, - /// The first struct, enum, or union definition of each name. - defined: BTreeMap, -} - -/// Runs the limits over every workspace crate's `src/` tree, the crates -/// whose manifest the shared walk could not read included, against -/// [`ALLOWED`]. An unreadable or unparseable file is reported, not -/// skipped, and a scan that read no source at all fails: a file that was -/// never read cannot be shown within the limits. -#[must_use] -pub(crate) fn type_size_violations(root: &Path) -> Vec { - violations_against(root, ALLOWED) -} - -/// [`type_size_violations`] against any allowlist, so a fixture can pass -/// its own. -fn violations_against(root: &Path, allowed: &[Allowed]) -> Vec { - let walk = crate::product::workspace_crates(root); - let mut dirs: Vec<&PathBuf> = walk - .crates - .iter() - .map(|krate| &krate.dir) - .chain(&walk.unread) - .collect(); - dirs.sort(); - let mut violations = Vec::new(); - let mut counts = Counts::new(); - let mut read = 0; - for dir in dirs { - let crate_dir = root.join(dir); - let src = crate_dir.join("src"); - let mut files: Vec = crate::tidy::rust_files(&src) - .into_iter() - .filter(|file| !is_test_file(&crate::tidy::slash_path(&src, file))) - .collect(); - files.sort(); - read += files.len(); - let mut census = Census::default(); - for file in &files { - census.read(root, &crate_dir, file, &mut violations); - } - let krate = crate::tidy::slash_path(root, &crate_dir); - census.judge(&krate, allowed, &mut counts, &mut violations); - } - if read == 0 { - return vec![format!( - "{}: the type-size check read nothing: no workspace crate holds a `.rs` file under \ - `src/`, so none can be shown within the limits", - root.join("crates").display() - )]; - } - violations.extend(entry_violations(allowed, &counts)); - violations -} - -impl Census { - /// Parses `file` and records its types, or reports why it could not. - fn read(&mut self, root: &Path, crate_dir: &Path, file: &Path, violations: &mut Vec) { - let path = crate::tidy::slash_path(root, file); - let text = match fs::read_to_string(file) { - Ok(text) => text, - Err(error) => { - violations.push(format!("{path}: unreadable source: {error}")); - return; - } - }; - match syn::parse_file(&text) { - Ok(parsed) if gated_on_test(&parsed.attrs) => {} - Ok(parsed) => { - let local = crate::tidy::slash_path(crate_dir, file); - self.items(&parsed.items, &path, &local); - } - Err(error) => violations.push(format!( - "{path}:{}: unparseable source: required a file that parses as Rust, found {error}", - error.span().start().line - )), - } - } - - /// Records the inherent methods, structs, and definitions in `items`, - /// inline modules included, from the file at `path` (`local` within - /// its crate). - fn items(&mut self, items: &[Item], path: &str, local: &str) { - for item in items { - match item { - Item::Impl(item) if item.trait_.is_none() && !gated_on_test(&item.attrs) => { - let Some(name) = self_type_name(&item.self_ty) else { - continue; - }; - let count = item - .items - .iter() - .filter(|member| { - matches!(member, ImplItem::Fn(function) if !gated_on_test(&function.attrs)) - }) - .count(); - let tally = self.methods.entry(name).or_insert_with(|| Tally { - first: Site { - path: path.to_owned(), - line: item.impl_token.span.start().line, - }, - files: BTreeMap::new(), - }); - *tally.files.entry(local.to_owned()).or_default() += count; - } - Item::Struct(item) if !gated_on_test(&item.attrs) => { - if let Fields::Named(fields) = &item.fields { - self.structs.push(( - item.ident.to_string(), - site(&item.ident, path), - fields.named.len(), - )); - } - self.define(&item.ident, path); - } - Item::Enum(item) if !gated_on_test(&item.attrs) => self.define(&item.ident, path), - Item::Union(item) if !gated_on_test(&item.attrs) => self.define(&item.ident, path), - Item::Mod(item) if !gated_on_test(&item.attrs) => { - if let Some((_, items)) = &item.content { - self.items(items, path, local); - } - } - _ => {} - } - } - } - - /// Records `ident`'s definition in `path`, unless the name has one. - fn define(&mut self, ident: &Ident, path: &str) { - self.defined - .entry(ident.to_string()) - .or_insert_with(|| site(ident, path)); - } - - /// Judges this crate's counts against the limits and `allowed`, and - /// records each count in `counts` for [`entry_violations`]. - fn judge( - &self, - krate: &str, - allowed: &[Allowed], - counts: &mut Counts, - violations: &mut Vec, - ) { - for (name, tally) in &self.methods { - let total: usize = tally.files.values().sum(); - counts.insert((krate.to_owned(), name.clone(), Limit::Methods), total); - let site = self.defined.get(name).unwrap_or(&tally.first); - let found = format!("`{name}` with {total} ({})", tally.breakdown()); - let entry = entry(allowed, krate, name, Limit::Methods); - violations.extend(judge_one(site, entry, Limit::Methods, total, &found)); - } - for (name, site, fields) in &self.structs { - let count = counts - .entry((krate.to_owned(), name.clone(), Limit::Fields)) - .or_default(); - *count = (*count).max(*fields); - let found = format!("`{name}` with {fields}"); - let entry = entry(allowed, krate, name, Limit::Fields); - violations.extend(judge_one(site, entry, Limit::Fields, *fields, &found)); - } - } -} - -/// The site of the item `ident` names, in `path`. -fn site(ident: &Ident, path: &str) -> Site { - Site { - path: path.to_owned(), - line: ident.span().start().line, - } -} - -/// The entry in `allowed` for `name` in the crate at `krate` under `limit`. -fn entry<'a>(allowed: &'a [Allowed], krate: &str, name: &str, limit: Limit) -> Option<&'a Allowed> { - allowed - .iter() - .find(|entry| entry.krate == krate && entry.name == name && entry.limit == limit) -} - -/// The violation `count` makes against `limit` at `site`, where `entry` is -/// the allowlist's entry for the type, if it has one. -fn judge_one( - site: &Site, - entry: Option<&Allowed>, - limit: Limit, - count: usize, - found: &str, -) -> Option { - let Site { path, line } = site; - match entry { - None if count > limit.bound() => Some(format!( - "{path}:{line}: {}: required at most {} {}, or an allowlist entry with a reason, \ - found {found}", - limit.rule(), - limit.bound(), - limit.noun() - )), - Some(entry) if count > entry.recorded => Some(format!( - "{path}:{line}: allowlisted type past its recorded count: required at most {} {}, \ - the count its entry records, found {found}", - entry.recorded, - limit.noun() - )), - _ => None, - } -} - -/// The entries in `allowed` with a blank reason, and the stale ones: a type -/// the scan never counted, or one back within its limit. -fn entry_violations(allowed: &[Allowed], counts: &Counts) -> Vec { - const ALLOWLIST: &str = "crates/build-xtask/src/type_size.rs"; - let mut violations = Vec::new(); - for entry in allowed { - let Allowed { - krate, - name, - limit, - reason, - .. - } = *entry; - if reason.trim().is_empty() { - violations.push(format!( - "{ALLOWLIST}: allowlist entry without a reason: required one sentence saying what \ - `{name}` in `{krate}` is and why its size holds, found a blank reason" - )); - } - let required = format!( - "`{name}` in `{krate}` over {} {}", - limit.bound(), - limit.noun() - ); - match counts.get(&(krate.to_owned(), name.to_owned(), limit)) { - None => violations.push(format!( - "{ALLOWLIST}: stale allowlist entry: required {required}, found no such type" - )), - Some(count) if *count <= limit.bound() => violations.push(format!( - "{ALLOWLIST}: stale allowlist entry: required {required}, found {count}" - )), - Some(_) => {} - } - } - violations -} - -/// Whether `path`, relative to a crate's `src/` with `/` separators, is a -/// test file: one under a `tests/` directory, or one whose name marks it as -/// tests (`tests.rs`, `foo-tests.rs`, `foo-tests-bar.rs`, `tests-foo.rs`, -/// or `foo_tests.rs`). -fn is_test_file(path: &str) -> bool { - let mut parts: Vec<&str> = path.split('/').collect(); - let stem = parts - .pop() - .map_or("", |file| file.strip_suffix(".rs").unwrap_or(file)); - parts.contains(&"tests") - || stem == "tests" - || stem.ends_with("-tests") - || stem.contains("-tests-") - || stem.starts_with("tests-") - || stem.ends_with("_tests") -} - -/// Whether `attrs` hold a `cfg` that names `test` outside a `not`, as -/// `cfg(test)` and `cfg(any(test, feature = "..."))` do. -fn gated_on_test(attrs: &[Attribute]) -> bool { - attrs.iter().any(|attr| { - attr.path().is_ident("cfg") - && matches!(&attr.meta, Meta::List(list) if names_test(list.tokens.clone())) - }) -} - -/// Whether `tokens` name `test` at any depth outside a `not(...)`. -fn names_test(tokens: TokenStream) -> bool { - let mut tokens = tokens.into_iter(); - while let Some(token) = tokens.next() { - match token { - TokenTree::Ident(ident) if ident == "not" => { - tokens.next(); - } - TokenTree::Ident(ident) if ident == "test" => return true, - TokenTree::Group(group) if names_test(group.stream()) => return true, - _ => {} - } - } - false -} - -/// The last path segment of an `impl`'s self type, through any grouping, -/// or `None` for a self type that is not a plain path. -fn self_type_name(ty: &Type) -> Option { - match ty { - Type::Path(path) if path.qself.is_none() => path - .path - .segments - .last() - .map(|segment| segment.ident.to_string()), - Type::Group(group) => self_type_name(&group.elem), - Type::Paren(paren) => self_type_name(&paren.elem), - _ => None, - } -} - -#[cfg(test)] -mod tests { - use std::fmt::Write as _; - use std::path::Path; - - use super::*; - use crate::product::test_support::workspace_root; - - /// Writes a crate at `crates/fixture/` holding each `(path, text)` - /// under its `src/`. - fn write_fixture(root: &Path, files: &[(&str, &str)]) { - crate::product::test_support::write_crate(root, "fixture", "fixture", ""); - let src = root.join("crates").join("fixture").join("src"); - for (path, text) in files { - let file = src.join(path); - let dir = file.parent().expect("a fixture file sits in a directory"); - fs::create_dir_all(dir).expect("the fixture directory creates"); - fs::write(&file, text).expect("the fixture file writes"); - } - } - - /// An inherent `impl` of `name` holding `count` methods named after `tag`. - fn methods(name: &str, tag: &str, count: usize) -> String { - let mut text = format!("impl {name} {{\n"); - for index in 0..count { - writeln!(text, " fn {tag}_{index}(&self) {{}}").expect("a String takes every write"); - } - text + "}\n" - } - - /// A struct `name` with `count` named fields. - fn fields(name: &str, count: usize) -> String { - let mut text = format!("struct {name} {{\n"); - for index in 0..count { - writeln!(text, " f{index}: u8,").expect("a String takes every write"); - } - text + "}\n" - } - - /// An entry lifting `limit` for `name` in the fixture crate. - fn fixture_entry( - name: &'static str, - limit: Limit, - recorded: usize, - reason: &'static str, - ) -> Allowed { - Allowed { - krate: "crates/fixture", - name, - limit, - recorded, - reason, - } - } - - #[test] - fn the_workspace_keeps_every_type_within_its_size_limits() { - let violations = type_size_violations(&workspace_root()); - assert!( - violations.is_empty(), - "type-size violations:\n{}", - violations.join("\n") - ); - } - - #[test] - fn methods_are_summed_across_every_inherent_impl_block_in_the_crate() { - let root = tempfile::TempDir::new().expect("tempdir"); - let lib = format!("mod more;\npub struct Wide;\n{}", methods("Wide", "a", 13)); - let more = format!("use super::Wide;\n{}", methods("Wide", "b", 13)); - write_fixture(root.path(), &[("lib.rs", &lib), ("more.rs", &more)]); - let violations = violations_against(root.path(), &[]); - assert_eq!(violations.len(), 1, "{violations:?}"); - assert!( - violations[0].starts_with( - "crates/fixture/src/lib.rs:2: type over the inherent method limit: required at \ - most 25 inherent methods" - ) && violations[0].ends_with("found `Wide` with 26 (src/lib.rs 13, src/more.rs 13)"), - "the type is named at its definition with each file's share: {violations:?}" - ); - } - - #[test] - fn trait_impl_methods_are_not_counted() { - let root = tempfile::TempDir::new().expect("tempdir"); - let lib = format!( - "struct Wide;\n{}impl Clone for Wide {{\n fn clone(&self) -> Self {{\n \ - Wide\n }}\n}}\n", - methods("Wide", "a", 25) - ); - write_fixture(root.path(), &[("lib.rs", &lib)]); - let violations = violations_against(root.path(), &[]); - assert!(violations.is_empty(), "{violations:?}"); - } - - #[test] - fn a_struct_over_the_field_limit_is_reported_at_its_definition() { - let root = tempfile::TempDir::new().expect("tempdir"); - let lib = format!( - "//! Fixture.\n{}{}", - fields("Narrow", 12), - fields("Broad", 13) - ); - write_fixture(root.path(), &[("lib.rs", &lib)]); - let violations = violations_against(root.path(), &[]); - assert_eq!(violations.len(), 1, "{violations:?}"); - assert!( - violations[0].starts_with( - "crates/fixture/src/lib.rs:16: struct over the named field limit: required at \ - most 12 named fields" - ) && violations[0].ends_with("found `Broad` with 13"), - "{violations:?}" - ); - } - - #[test] - fn an_allowlisted_type_passes_at_its_recorded_count_and_fails_one_past_it() { - let root = tempfile::TempDir::new().expect("tempdir"); - let allowed = [fixture_entry("Wide", Limit::Methods, 27, "a fixture type")]; - let at = format!("struct Wide;\n{}", methods("Wide", "a", 27)); - write_fixture(root.path(), &[("lib.rs", &at)]); - let violations = violations_against(root.path(), &allowed); - assert!(violations.is_empty(), "{violations:?}"); - - let past = format!("struct Wide;\n{}", methods("Wide", "a", 28)); - write_fixture(root.path(), &[("lib.rs", &past)]); - let violations = violations_against(root.path(), &allowed); - assert_eq!(violations.len(), 1, "{violations:?}"); - assert!( - violations[0].contains("allowlisted type past its recorded count: required at most 27") - && violations[0].ends_with("found `Wide` with 28 (src/lib.rs 28)"), - "{violations:?}" - ); - } - - #[test] - fn stale_entries_and_a_blank_reason_are_reported() { - let root = tempfile::TempDir::new().expect("tempdir"); - let allowed = [ - fixture_entry("Gone", Limit::Methods, 30, "a type that no longer exists"), - fixture_entry("Small", Limit::Fields, 20, "a struct back within the limit"), - fixture_entry("Wide", Limit::Methods, 26, " "), - ]; - let lib = format!( - "{}struct Wide;\n{}", - fields("Small", 12), - methods("Wide", "a", 26) - ); - write_fixture(root.path(), &[("lib.rs", &lib)]); - let violations = violations_against(root.path(), &allowed); - assert_eq!(violations.len(), 3, "{violations:?}"); - assert!( - violations[0].contains("stale allowlist entry: required `Gone` in `crates/fixture`") - && violations[0].ends_with("found no such type"), - "a type the scan never counted is stale: {violations:?}" - ); - assert!( - violations[1].contains("stale allowlist entry: required `Small` in `crates/fixture`") - && violations[1].ends_with("found 12"), - "a type back within its limit is stale: {violations:?}" - ); - assert!( - violations[2].contains("allowlist entry without a reason") - && violations[2].contains("`Wide`"), - "an entry needs a reason: {violations:?}" - ); - } - - #[test] - fn test_files_and_items_gated_on_test_are_not_counted() { - let root = tempfile::TempDir::new().expect("tempdir"); - let wide = methods("Wide", "a", 30); - let lib = format!( - "pub struct Wide;\n#[cfg(test)]\nmod tests {{\n{wide}}}\n\ - #[cfg(any(test, feature = \"fixture\"))]\n{wide}" - ); - let gated = format!("#![cfg(test)]\n{wide}"); - write_fixture( - root.path(), - &[ - ("lib.rs", &lib), - ("support.rs", &gated), - ("tests.rs", &wide), - ("wide-tests.rs", &wide), - ("wide-tests-more.rs", &wide), - ("tests-wide.rs", &wide), - ("wide_tests.rs", &wide), - ("inner/tests/deep.rs", &wide), - ], - ); - let violations = violations_against(root.path(), &[]); - assert!(violations.is_empty(), "{violations:?}"); - - let ungated = format!("pub struct Wide;\n#[cfg(not(test))]\n{wide}"); - write_fixture(root.path(), &[("lib.rs", &ungated)]); - let violations = violations_against(root.path(), &[]); - assert_eq!( - violations.len(), - 1, - "a `not(test)` item is counted: {violations:?}" - ); - } - - #[test] - fn methods_in_inline_modules_count_and_test_gated_methods_do_not() { - let root = tempfile::TempDir::new().expect("tempdir"); - let lib = format!( - "pub struct Wide;\nmod inner {{\n{}}}\nimpl Wide {{\n #[cfg(test)]\n fn \ - helper(&self) {{}}\n}}\n", - methods("Wide", "a", 26) - ); - write_fixture(root.path(), &[("lib.rs", &lib)]); - let violations = violations_against(root.path(), &[]); - assert_eq!(violations.len(), 1, "{violations:?}"); - assert!( - violations[0].ends_with("found `Wide` with 26 (src/lib.rs 26)"), - "{violations:?}" - ); - } - - #[test] - fn a_crate_whose_manifest_does_not_parse_is_still_scanned() { - let root = tempfile::TempDir::new().expect("tempdir"); - let lib = format!("struct Wide;\n{}", methods("Wide", "a", 26)); - write_fixture(root.path(), &[("lib.rs", &lib)]); - fs::write( - root.path() - .join("crates") - .join("fixture") - .join("Cargo.toml"), - "not [valid toml", - ) - .expect("the manifest rewrites"); - let violations = violations_against(root.path(), &[]); - assert_eq!(violations.len(), 1, "{violations:?}"); - assert!( - violations[0].contains("type over the inherent method limit"), - "a crate whose manifest was never read cannot be shown within the limits: \ - {violations:?}" - ); - } - - #[test] - fn a_source_file_that_does_not_parse_is_reported() { - let root = tempfile::TempDir::new().expect("tempdir"); - write_fixture(root.path(), &[("lib.rs", "fn broken( {\n")]); - let violations = violations_against(root.path(), &[]); - assert_eq!(violations.len(), 1, "{violations:?}"); - assert!( - violations[0].starts_with("crates/fixture/src/lib.rs:") - && violations[0].contains("unparseable source"), - "a file that was never read cannot be shown within the limits: {violations:?}" - ); - } - - #[test] - fn a_type_size_scan_that_reads_no_source_fails() { - let root = tempfile::TempDir::new().expect("tempdir"); - fs::create_dir_all(root.path().join("crates")).expect("the crates directory creates"); - let violations = violations_against(root.path(), &[]); - assert_eq!(violations.len(), 1, "{violations:?}"); - assert!( - violations[0].contains("read nothing"), - "a check that read no source cannot show it within the limits: {violations:?}" - ); - } -} diff --git a/crates/workshop/agents/src/conversation-run.rs b/crates/workshop/agents/src/conversation-run.rs deleted file mode 100644 index 6c64c796..00000000 --- a/crates/workshop/agents/src/conversation-run.rs +++ /dev/null @@ -1,126 +0,0 @@ -//! What a conversation hands its run's setup, and how it runs the agent -//! and takes the run's report: the recorder tee, the live pieces of the -//! run's own rounds, and the drive that parses the agent, runs it, and -//! ends the conversation with its run. - -use std::sync::Arc; - -use runvil::harness::{IntoShared, RunRecorder}; -use runvil::ids::RoundId; -use runvil::{Error, Harness, Host, Prompt, RunReport, RunSetup}; - -use super::{Conversation, lock}; -use crate::protocol::{Delta, DeltaKind}; -use crate::state::{FailureKind, SessionState}; -use crate::tee::ConversationRecorder; - -/// The report of a run a close or an uncaught stop cut short. -const CANCELED: &str = "the agent run was canceled"; - -impl Conversation { - /// The recorder the run writes through: every call goes on to - /// `inner`, and each event `inner` accepted reaches this - /// conversation. `inner` is taken in each form in which a run's - /// setup takes a recorder: the recorder itself, an `Arc` of it, or - /// an `Arc`. - #[must_use] - pub fn recorder(&self, inner: impl IntoShared) -> Arc { - Arc::new(ConversationRecorder::new(self.clone(), inner.into_shared())) - } - - /// Parses the agent `name` on `host` on the blocking pool, then runs - /// it with `setup`. A parse failure is reported as a run failure with - /// its located message; no run is recorded. - /// - /// The run's Harness control is held while the run goes on, so the - /// operator's messages, a stop, and a close reach the run. The - /// conversation ends with its run, or with the parse failure. - pub async fn run(&self, host: Arc, name: &str, setup: RunSetup) { - let prompt = match parse(&host, name).await { - Ok(prompt) => prompt, - Err(message) => { - tracing::warn!( - conversation = %self.core.id, - agent = %self.core.agent, - %message, - "agent failed to parse" - ); - self.report(FailureKind::RunFailed, message); - self.end(); - return; - } - }; - let harness = Harness::new(host, prompt, setup); - { - let mut control = lock(&self.core.control); - let held = control.insert(harness.control()); - if self.state() != SessionState::Alive { - held.cancel(); - } - } - let result = harness.run().await; - self.take_report(result); - self.end(); - } - - /// Notes the report's run, logs how many of the operator's messages - /// it never read, and reports a run that failed or was cut short; a - /// completed run reports nothing. - fn take_report(&self, result: Result) { - let message = match result { - Ok(report) => { - self.note_run(report.run_id); - tracing::info!( - conversation = %self.core.id, - agent = %self.core.agent, - unread = report.unread.len(), - "the agent run ended; this many of the operator's messages went unread" - ); - match report.result { - Ok(_) => return, - Err(error) if error.is_canceled() => { - self.report(FailureKind::Canceled, CANCELED.to_owned()); - return; - } - Err(error) => error.located_message(), - } - } - Err(error) => error.to_string(), - }; - tracing::warn!( - conversation = %self.core.id, - agent = %self.core.agent, - %message, - "agent run failed" - ); - self.report(FailureKind::RunFailed, message); - } - - /// Broadcasts one live piece of the run's round `round` as a - /// [`Delta`] of `kind`, stamped with the round's id, the id the - /// round's reply event carries. No client listening is not a failure: - /// the completed reply travels in the round's answer. - pub fn publish_delta(&self, round: RoundId, kind: DeltaKind, content: String) { - if let Some(channels) = self.channels() { - // No receiver means no client is attached; deltas are - // ephemeral and the completed-reply event is the repair. - let _ = channels.deltas.send(Delta { - kind, - content, - reply: round.get(), - }); - } - } -} - -/// The agent `name` parsed on `host` on the blocking pool, since finding -/// it reads the agents folder, or the message of why it did not parse: the -/// parse failure's located message, or the blocking task's failure. -async fn parse(host: &Arc, name: &str) -> Result, String> { - let host = Arc::clone(host); - let name = name.to_owned(); - match tokio::task::spawn_blocking(move || host.parse(&name)).await { - Ok(parsed) => parsed.map_err(|error| error.located_message()), - Err(join) => Err(format!("the agent could not be parsed: {join}")), - } -} diff --git a/crates/workshop/agents/src/conversation.rs b/crates/workshop/agents/src/conversation.rs index e6c0332d..49621ceb 100644 --- a/crates/workshop/agents/src/conversation.rs +++ b/crates/workshop/agents/src/conversation.rs @@ -1,5 +1,6 @@ -//! One conversation: the handle a socket holds, and the state that -//! outlives any socket connection. +//! One conversation: the handle a socket holds, the state that outlives +//! any socket connection, the drive that parses and runs the agent, and +//! the recorder tee the run writes through. //! //! A conversation owns one agent's one run. Its transcript is every event //! the run has reported, numbered from zero and held in memory. A live @@ -10,18 +11,17 @@ //! to the run's main chain through its Harness control. Its channels //! close when the run ends. -#[path = "conversation-run.rs"] -mod run; - use std::fmt; use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak}; -use runvil::RunControl; use runvil::event::Event; -use runvil::harness::RunId; +use runvil::harness::{IntoShared, Record, RunId, RunMeta, RunRecorder}; +use runvil::ids::RoundId; +use runvil::{BoxFuture, Error, Harness, Host, RunControl, RunSetup}; use tokio::sync::{broadcast, watch}; +use tokio::task; -use crate::protocol::{ConversationId, Delta, SessionEvent}; +use crate::protocol::{ConversationId, Delta, DeltaKind, SessionEvent}; use crate::state::{FailureKind, SessionFailure, SessionState}; use crate::table::{self, Table}; use crate::transcript::Transcript; @@ -41,6 +41,9 @@ const DELTA_CAPACITY: usize = 256; /// transcript already shows as a turn without a reply. const ERROR_CAPACITY: usize = 8; +/// The report of a run a close or an uncaught stop cut short. +const CANCELED: &str = "the agent run was canceled"; + /// A running agent conversation: the handle a socket launches, sends the /// operator's messages through, stops, closes, and subscribes through. /// Cheap to clone; every clone names the same conversation. @@ -83,7 +86,6 @@ struct Core { } /// A conversation's live senders. -#[derive(Clone)] struct Channels { events: broadcast::Sender, deltas: broadcast::Sender, @@ -151,14 +153,16 @@ impl Conversation { /// lost between the two. #[must_use] pub fn subscribe_events(&self) -> broadcast::Receiver { - self.channels() + lock(&self.core.channels) + .as_ref() .map_or_else(closed, |channels| channels.events.subscribe()) } /// Subscribes to the conversation's live deltas from this call on. #[must_use] pub fn subscribe_deltas(&self) -> broadcast::Receiver { - self.channels() + lock(&self.core.channels) + .as_ref() .map_or_else(closed, |channels| channels.deltas.subscribe()) } @@ -166,7 +170,8 @@ impl Conversation { /// on. Ephemeral like the deltas. #[must_use] pub fn subscribe_errors(&self) -> broadcast::Receiver { - self.channels() + lock(&self.core.channels) + .as_ref() .map_or_else(closed, |channels| channels.errors.subscribe()) } @@ -224,13 +229,105 @@ impl Conversation { let _ = state.wait_for(|state| *state != SessionState::Alive).await; } - /// The live senders, or `None` once the conversation has ended. - fn channels(&self) -> Option { - lock(&self.core.channels).clone() + /// The recorder the run writes through: every call goes on to + /// `inner`, and each event `inner` accepted reaches this + /// conversation. `inner` is taken in each form in which a run's + /// setup takes a recorder: the recorder itself, an `Arc` of it, or + /// an `Arc`. + #[must_use] + pub fn recorder(&self, inner: impl IntoShared) -> Arc { + Arc::new(ConversationRecorder { + conversation: self.clone(), + inner: inner.into_shared(), + }) + } + + /// Parses the agent `name` on `host` on the blocking pool, then runs + /// it with `setup`. A parse failure is reported as a run failure with + /// its located message; no run is recorded. + /// + /// The run's Harness control is held while the run goes on, so the + /// operator's messages, a stop, and a close reach the run. The + /// conversation ends with its run, or with the parse failure. + pub async fn run(&self, host: Arc, name: &str, setup: RunSetup) { + let parse_host = Arc::clone(&host); + let parse_name = name.to_owned(); + let parsed = match task::spawn_blocking(move || parse_host.parse(&parse_name)).await { + Ok(parsed) => parsed.map_err(|error| error.located_message()), + Err(join) => Err(format!("the agent could not be parsed: {join}")), + }; + let prompt = match parsed { + Ok(prompt) => prompt, + Err(message) => { + tracing::warn!( + conversation = %self.core.id, + agent = %self.core.agent, + %message, + "agent failed to parse" + ); + self.report(FailureKind::RunFailed, message); + self.end(); + return; + } + }; + let harness = Harness::new(host, prompt, setup); + { + let mut control = lock(&self.core.control); + let held = control.insert(harness.control()); + if self.state() != SessionState::Alive { + held.cancel(); + } + } + let failure = match harness.run().await { + Ok(report) => { + self.note_run(report.run_id); + tracing::info!( + conversation = %self.core.id, + agent = %self.core.agent, + unread = report.unread.len(), + "the agent run ended; this many of the operator's messages went unread" + ); + match report.result { + Ok(_) => None, + Err(error) if error.is_canceled() => { + self.report(FailureKind::Canceled, CANCELED.to_owned()); + None + } + Err(error) => Some(error.located_message()), + } + } + Err(error) => Some(error.to_string()), + }; + if let Some(message) = failure { + tracing::warn!( + conversation = %self.core.id, + agent = %self.core.agent, + %message, + "agent run failed" + ); + self.report(FailureKind::RunFailed, message); + } + self.end(); + } + + /// Broadcasts one live piece of the run's round `round` as a + /// [`Delta`] of `kind`, stamped with the round's id, the id the + /// round's reply event carries. No client listening is not a failure: + /// the completed reply travels in the round's answer. + pub fn publish_delta(&self, round: RoundId, kind: DeltaKind, content: String) { + if let Some(channels) = lock(&self.core.channels).as_ref() { + // No receiver means no client is attached; deltas are + // ephemeral and the completed-reply event is the repair. + let _ = channels.deltas.send(Delta { + kind, + content, + reply: round.get(), + }); + } } /// Notes the run the recorder began. - pub(crate) fn note_run(&self, run: RunId) { + fn note_run(&self, run: RunId) { *lock(&self.core.run) = Some(run); } @@ -238,38 +335,11 @@ impl Conversation { /// `message`. No receiver means no client is attached; reports are /// ephemeral by design. fn report(&self, kind: FailureKind, message: String) { - if let Some(channels) = self.channels() { + if let Some(channels) = lock(&self.core.channels).as_ref() { let _ = channels.errors.send(SessionFailure { kind, message }); } } - /// Applies one recorded event: a failed model round or tool dispatch - /// is reported first, then the event is appended to the transcript - /// under the next index and that same entry is broadcast. - pub(crate) fn observe(&self, event: &Event) { - // The program survives a failed round or tool dispatch (the - // built-in chat pcalls `models.loop` and returns to waiting), so - // the run never fails and only the conversation can tell the - // client. - match event { - Event::ModelTurnFailed { section, .. } => self.report( - FailureKind::ModelTurnFailed, - format!("Model turn failed in agent `{section}`"), - ), - Event::ToolCallFailed { section, .. } => self.report( - FailureKind::ToolCallFailed, - format!("Tool call failed in agent `{section}`"), - ), - _ => {} - } - let entry = self.core.transcript.push(event); - if let Some(channels) = self.channels() { - // No receiver means no client is attached; the transcript - // already holds the entry, so a late client reads it there. - let _ = channels.events.send(entry); - } - } - /// Ends the conversation once its run has: the state is `Closed`, the /// channels close, and the conversation leaves its table. fn end(&self) { @@ -281,8 +351,79 @@ impl Conversation { } } +/// A [`RunRecorder`] over an inner recorder that feeds one conversation: +/// every call goes on to `inner`, and each event `inner` accepted also +/// reaches the conversation once stored, so the record, the live +/// broadcast, and the transcript agree event for event. +struct ConversationRecorder { + conversation: Conversation, + inner: Arc, +} + +impl RunRecorder for ConversationRecorder { + fn begin_run(&self, meta: RunMeta) -> BoxFuture<'_, Result> { + Box::pin(async move { + let run = self.inner.begin_run(meta).await?; + self.conversation.note_run(run); + Ok(run) + }) + } + + fn append(&self, run: RunId, record: Record) -> BoxFuture<'_, Result<(), Error>> { + self.inner.append(run, record) + } + + fn append_event<'a>( + &'a self, + run: RunId, + record: Record, + event: &'a Event, + ) -> BoxFuture<'a, Result<(), Error>> { + Box::pin(async move { + self.inner.append_event(run, record, event).await?; + // The program survives a failed round or tool dispatch (the + // built-in chat pcalls `models.loop` and returns to waiting), so + // the run never fails and only the conversation can tell the + // client. + match event { + Event::ModelTurnFailed { section, .. } => self.conversation.report( + FailureKind::ModelTurnFailed, + format!("Model turn failed in agent `{section}`"), + ), + Event::ToolCallFailed { section, .. } => self.conversation.report( + FailureKind::ToolCallFailed, + format!("Tool call failed in agent `{section}`"), + ), + _ => {} + } + self.conversation.core.transcript.push(event, |entry| { + if let Some(channels) = lock(&self.conversation.core.channels).as_ref() + && channels.events.receiver_count() > 0 + { + // No receiver means no client is attached; the transcript + // already holds the entry, so a late client reads it there. + let _ = channels.events.send(entry.clone()); + } + }); + Ok(()) + }) + } + + fn end_run( + &self, + run: RunId, + result: Result, + ) -> BoxFuture<'_, Result<(), Error>> { + self.inner.end_run(run, result) + } +} + /// Locks one of the core's slots. Every write is one store, so a poisoned /// lock still holds a usable value. fn lock(slot: &Mutex) -> MutexGuard<'_, T> { slot.lock().unwrap_or_else(PoisonError::into_inner) } + +#[cfg(test)] +#[path = "tee-tests.rs"] +mod tests; diff --git a/crates/workshop/agents/src/discovery-tests.rs b/crates/workshop/agents/src/discovery-tests.rs index 7d0a5884..ec0b53d4 100644 --- a/crates/workshop/agents/src/discovery-tests.rs +++ b/crates/workshop/agents/src/discovery-tests.rs @@ -74,6 +74,8 @@ fn an_unreadable_chat_md_surfaces_its_error_rather_than_the_built_in() { ); } +const REFUSED_NAMES: &[&str] = &["ghost", "hidden", "../echo", "echo.md", "", "sub/echo"]; + #[test] fn a_launch_loads_only_a_name_the_agent_menu_lists() { let dir = tempfile::TempDir::new().expect("tempdir"); @@ -86,7 +88,7 @@ fn a_launch_loads_only_a_name_the_agent_menu_lists() { "# echo".to_owned() ) ); - for refused in ["ghost", "hidden", "../echo", "echo.md"] { + for &refused in REFUSED_NAMES { let error = load_agent(dir.path(), refused) .expect_err("a name the menu does not list never reaches the filesystem"); assert!( @@ -96,7 +98,7 @@ fn a_launch_loads_only_a_name_the_agent_menu_lists() { assert_eq!( error.to_string(), format!("unknown agent {refused:?}: not in the agents directory"), - "the refusal keeps its text" + "{refused:?}: refusal keeps its text" ); } } diff --git a/crates/workshop/agents/src/discovery.rs b/crates/workshop/agents/src/discovery.rs index 35cb658b..ca5c97db 100644 --- a/crates/workshop/agents/src/discovery.rs +++ b/crates/workshop/agents/src/discovery.rs @@ -2,6 +2,7 @@ //! the built-in `chat` agent embedded at compile time, the shadowing rule //! between them, and the launch's read of one agent's source. +use std::fs; use std::io; use std::path::Path; @@ -42,7 +43,7 @@ pub enum LaunchError { /// shadows the embedded source instead of duplicating the name. #[must_use] pub fn discover_agents(dir: &Path) -> Vec { - let mut names: Vec = std::fs::read_dir(dir) + let mut names: Vec = fs::read_dir(dir) .into_iter() .flatten() .filter_map(Result::ok) @@ -90,7 +91,7 @@ pub fn load_agent(dir: &Path, name: &str) -> Result<(String, String), LaunchErro /// built-in would mask the operator's own file. fn agent_source(dir: &Path, name: &str) -> io::Result<(String, String)> { let path = dir.join(format!("{name}.md")); - match std::fs::read_to_string(&path) { + match fs::read_to_string(&path) { Ok(source) => Ok((path.display().to_string(), source)), Err(error) if name == BUILTIN_CHAT_NAME && error.kind() == io::ErrorKind::NotFound => { Ok((BUILTIN_CHAT_FILE.to_owned(), BUILTIN_CHAT_SOURCE.to_owned())) diff --git a/crates/workshop/agents/src/lib.rs b/crates/workshop/agents/src/lib.rs index 1ffcfffd..b10535e8 100644 --- a/crates/workshop/agents/src/lib.rs +++ b/crates/workshop/agents/src/lib.rs @@ -41,7 +41,6 @@ mod discovery; mod protocol; mod state; mod table; -mod tee; mod transcript; pub use conversation::Conversation; diff --git a/crates/workshop/agents/src/protocol.rs b/crates/workshop/agents/src/protocol.rs index 8d63c40e..673dbc35 100644 --- a/crates/workshop/agents/src/protocol.rs +++ b/crates/workshop/agents/src/protocol.rs @@ -4,6 +4,7 @@ use std::fmt; +use rand::Rng as _; use serde::{Deserialize, Serialize}; /// A conversation's unguessable id, minted by Workshop at launch. It is @@ -26,7 +27,6 @@ impl ConversationId { /// conversation. #[must_use] pub fn fresh() -> Self { - use rand::Rng as _; let mut rng = rand::rng(); Self(format!( "{:016x}{:016x}", diff --git a/crates/workshop/agents/src/tee-tests.rs b/crates/workshop/agents/src/tee-tests.rs index 7e5a4dc9..fc69ff9e 100644 --- a/crates/workshop/agents/src/tee-tests.rs +++ b/crates/workshop/agents/src/tee-tests.rs @@ -11,11 +11,10 @@ use runvil::harness::{ use runvil::ids::Provenance; use runvil::{BoxFuture, Error, RunSeed, Timestamp}; +use super::*; use crate::state::FailureKind; use crate::table::Conversations; -use super::*; - fn meta() -> RunMeta { RunMeta { seed: RunSeed::from_bytes([7; 32]), @@ -89,7 +88,7 @@ fn watched(refuse: bool) -> (Conversation, Arc, Arc) held_at_append: Mutex::new(Vec::new()), refuse, }); - let tee = conversation.recorder(inner.clone()); + let tee = conversation.recorder(Arc::clone(&inner)); (conversation, inner, tee) } diff --git a/crates/workshop/agents/src/tee.rs b/crates/workshop/agents/src/tee.rs deleted file mode 100644 index 1e0c7087..00000000 --- a/crates/workshop/agents/src/tee.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! The recorder a conversation's run writes through: every call goes on -//! to the inner recorder, and what the inner recorder accepted also -//! reaches the conversation. -//! -//! The tee notes the run the inner recorder begins. The Harness hands it -//! each event with the event's record. The tee passes both on to the -//! inner recorder, and it hands the event to the conversation once the -//! inner recorder has accepted the record, so the record, the live -//! broadcast, and the transcript agree event for event. A refused write -//! is returned as the inner recorder's own, and its event reaches no one. - -use std::sync::Arc; - -use runvil::event::Event; -use runvil::harness::{Record, RunId, RunMeta, RunRecorder}; -use runvil::{BoxFuture, Error}; - -use crate::conversation::Conversation; - -/// A [`RunRecorder`] over an inner recorder that feeds one conversation. -pub(crate) struct ConversationRecorder { - conversation: Conversation, - inner: Arc, -} - -impl ConversationRecorder { - /// The tee over `inner` feeding `conversation`. - pub(crate) fn new(conversation: Conversation, inner: Arc) -> Self { - Self { - conversation, - inner, - } - } -} - -impl RunRecorder for ConversationRecorder { - fn begin_run(&self, meta: RunMeta) -> BoxFuture<'_, Result> { - Box::pin(async move { - let run = self.inner.begin_run(meta).await?; - self.conversation.note_run(run); - Ok(run) - }) - } - - fn append(&self, run: RunId, record: Record) -> BoxFuture<'_, Result<(), Error>> { - self.inner.append(run, record) - } - - fn append_event<'a>( - &'a self, - run: RunId, - record: Record, - event: &'a Event, - ) -> BoxFuture<'a, Result<(), Error>> { - Box::pin(async move { - self.inner.append_event(run, record, event).await?; - self.conversation.observe(event); - Ok(()) - }) - } - - fn end_run( - &self, - run: RunId, - result: Result, - ) -> BoxFuture<'_, Result<(), Error>> { - self.inner.end_run(run, result) - } -} - -#[cfg(test)] -#[path = "tee-tests.rs"] -mod tests; diff --git a/crates/workshop/agents/src/transcript-tests.rs b/crates/workshop/agents/src/transcript-tests.rs index 9d358ab7..342b3847 100644 --- a/crates/workshop/agents/src/transcript-tests.rs +++ b/crates/workshop/agents/src/transcript-tests.rs @@ -68,7 +68,7 @@ fn every_event_is_numbered_from_zero_in_the_order_it_lands() { let transcript = Transcript::new(); let stamped: Vec = [answered("one"), thinking(0), reply(0, ReplyOrigin::Chat)] .iter() - .map(|event| transcript.push(event).index) + .map(|event| transcript.push(event, |entry| entry.index)) .collect(); assert_eq!(stamped, [0, 1, 2], "the live entries number from zero"); let read: Vec = transcript @@ -91,23 +91,32 @@ fn every_event_is_numbered_from_zero_in_the_order_it_lands() { #[test] fn a_rounds_content_events_take_their_reply_from_the_round() { let transcript = Transcript::new(); + let (section, provenance) = at(); // A nested infer round numbered 4 lands between a section's rounds 3 // and 5: each event names its own round, whatever landed before it. let cases = [ - (thinking(3), Some(3)), - (reply(3, ReplyOrigin::Chat), Some(3)), - (reply(4, ReplyOrigin::Infer), Some(4)), - (tool_calls(5), Some(5)), - (answered("next"), None), - (reply(5, ReplyOrigin::Chat), Some(5)), + ("thinking_round_3", thinking(3), Some(3)), + ("chat_reply_round_3", reply(3, ReplyOrigin::Chat), Some(3)), + ("infer_reply_round_4", reply(4, ReplyOrigin::Infer), Some(4)), + ("tool_calls_round_5", tool_calls(5), Some(5)), + ("inbox_message_no_round", answered("next"), None), + ( + "section_started_no_round", + Event::SectionStarted { + section, + provenance, + }, + None, + ), + ("chat_reply_round_5", reply(5, ReplyOrigin::Chat), Some(5)), ]; - for (event, expected) in cases { - let entry = transcript.push(&event); - assert_eq!(entry.reply, expected, "{event:?}"); + for (label, event, expected) in cases { + let (index, reply) = transcript.push(&event, |entry| (entry.index, entry.reply)); + assert_eq!(reply, expected, "{label}: live stamp"); assert_eq!( - transcript.since(entry.index)[0].reply, + transcript.since(index)[0].reply, expected, - "the transcript keeps the stamp the live entry carried" + "{label}: stored transcript keeps the live stamp" ); } } @@ -116,7 +125,7 @@ fn a_rounds_content_events_take_their_reply_from_the_round() { fn an_entry_carries_the_event_in_its_persisted_shape() { let transcript = Transcript::new(); let event = answered("ping"); - let entry = transcript.push(&event); + let entry = transcript.push(&event, Clone::clone); assert_eq!( entry.event, serde_json::to_value(&event).expect("an event serializes"), diff --git a/crates/workshop/agents/src/transcript.rs b/crates/workshop/agents/src/transcript.rs index b91120a2..defa6227 100644 --- a/crates/workshop/agents/src/transcript.rs +++ b/crates/workshop/agents/src/transcript.rs @@ -27,20 +27,27 @@ impl Transcript { } } - /// Stamps `event` with the next index and its round, appends it, and - /// returns the stamped entry for the live broadcast. - pub(crate) fn push(&self, event: &Event) -> SessionEvent { - let mut events = self.lock(); + /// Stamps `event` with the next index and its round, runs `on_push` + /// with the stamped entry under the lock, and appends it. + pub(crate) fn push(&self, event: &Event, on_push: impl FnOnce(&SessionEvent) -> R) -> R { // The run serialized this same event for its recorder a moment // ago, so this cannot fail; `Null` keeps the index sequence whole // if it ever did. + let payload = serde_json::to_value(event).unwrap_or(serde_json::Value::Null); + let mut events = self.lock(); let stamped = SessionEvent { index: events.len() as u64, - reply: reply_of(event), - event: serde_json::to_value(event).unwrap_or(serde_json::Value::Null), + reply: match event { + Event::Thinking { round, .. } + | Event::AssistantReply { round, .. } + | Event::AssistantToolCalls { round, .. } => Some(round.get()), + _ => None, + }, + event: payload, }; - events.push(stamped.clone()); - stamped + let result = on_push(&stamped); + events.push(stamped); + result } /// The entries with an index of at least `from`, in order. @@ -59,17 +66,6 @@ impl Transcript { } } -/// The reply id of a model round's content event: the round that -/// produced it. Every other event settles no deltas. -fn reply_of(event: &Event) -> Option { - match event { - Event::Thinking { round, .. } - | Event::AssistantReply { round, .. } - | Event::AssistantToolCalls { round, .. } => Some(round.get()), - _ => None, - } -} - #[cfg(test)] #[path = "transcript-tests.rs"] mod tests; diff --git a/crates/workshop/agents/tests/it/conversation.rs b/crates/workshop/agents/tests/it/conversation.rs index a8d9cc8d..86594ba0 100644 --- a/crates/workshop/agents/tests/it/conversation.rs +++ b/crates/workshop/agents/tests/it/conversation.rs @@ -1,300 +1,148 @@ -//! A conversation over its one run: the run's report becomes the -//! conversation's failure report, an agent that fails to parse is a -//! run-failed report with no run recorded, a message sent before the run -//! is handed its Harness reaches no run, a stop leaves the agent waiting -//! on its inbox, a close cancels the run, and the conversation ends with -//! its run. +//! A conversation over its one run: failures, parse errors, completion, +//! early messages, stop, close, and end-of-run cleanup. -// clippy.toml's allow-expect-in-tests covers #[test] functions only, not -// the helpers they share; failing a test by panicking with the invariant -// named is exactly what these are for. -#![expect( - clippy::expect_used, - reason = "test helpers fail by panicking with the invariant named" -)] - -use std::sync::Arc; -use std::time::Duration; - -use runvil::harness::{MemoryRecorder, RunId}; +use runvil::harness::RunId; use tokio::sync::broadcast; -use workshop_agents::{ - Conversation, Conversations, FailureKind, SessionEvent, SessionFailure, SessionState, -}; - -use crate::support::{AGENT, prompt, run_for}; - -const DEADLINE: Duration = Duration::from_secs(10); - -/// A section that returns the operator's next message. -const RECEIVES: &str = "return (tasks.receive())"; - -/// Runs the conversation's one run over `source` on its own task. -fn start( - conversation: &Conversation, - recorder: &Arc, - source: String, -) -> tokio::task::JoinHandle<()> { - let (host, setup) = run_for(conversation, Arc::clone(recorder), source); - let conversation = conversation.clone(); - tokio::spawn(async move { conversation.run(host, AGENT, setup).await }) -} - -/// Waits until the run's main chain parks on its empty inbox, as the -/// conversation's live events report it. -async fn waits_on_its_inbox(events: &mut broadcast::Receiver) { - tokio::time::timeout(DEADLINE, async { - loop { - let entry = events.recv().await.expect("the event channel is open"); - if entry.event["kind"] == "inbox_waiting" { - return; - } - } - }) - .await - .expect("the agent waits on its inbox in time"); -} +use workshop_agents::{FailureKind, SessionFailure, SessionState}; -async fn ended(run: tokio::task::JoinHandle<()>) { - tokio::time::timeout(DEADLINE, run) - .await - .expect("the run ends in time") - .expect("the run's task joins"); -} - -/// Every failure report still queued. -fn reports(errors: &mut broadcast::Receiver) -> Vec { - std::iter::from_fn(|| errors.try_recv().ok()).collect() -} +use crate::support::{AGENT, ConversationFixture, RECEIVES, prompt}; #[tokio::test] async fn a_failed_report_becomes_a_run_failed_report_and_ends_the_conversation() { - let table = Conversations::new(); - let conversation = table.open("boom"); - let recorder = Arc::new(MemoryRecorder::new()); - let mut errors = conversation.subscribe_errors(); - let mut events = conversation.subscribe_events(); + let mut fx = ConversationFixture::open("boom"); + fx.run_to_end(prompt("error('kaboom')")).await; - ended(start(&conversation, &recorder, prompt("error('kaboom')"))).await; - - let reports = reports(&mut errors); + let reports = fx.reports(); assert_eq!(reports.len(), 1, "one report: {reports:?}"); assert_eq!(reports[0].kind, FailureKind::RunFailed); assert!( reports[0].message.contains("kaboom"), - "the run's own failure is the message: {reports:?}" + "failure message: {reports:?}" ); - assert_eq!(conversation.state(), SessionState::Closed); - let run = conversation.run_id().expect("the recorder began the run"); - let Some(Err(error)) = recorder.result(run) else { + assert_eq!(fx.conversation.state(), SessionState::Closed); + let Some(Err(error)) = fx.result() else { panic!("the run is recorded as failed"); }; assert!(!error.is_canceled(), "a failure is not a cancel: {error:?}"); - assert_eq!( - reports[0].message, - error.located_message(), - "the report is the recorded failure's located message" - ); + assert_eq!(reports[0].message, error.located_message()); assert!( - table.get(conversation.id()).is_none(), - "an ended conversation leaves the table" - ); - while let Ok(_entry) = events.try_recv() {} - assert!( - matches!( - events.try_recv(), - Err(broadcast::error::TryRecvError::Closed) - ), - "an ended conversation's channels close" + fx.table.get(fx.conversation.id()).is_none(), + "ended conversation leaves table" ); + while fx.events.try_recv().is_ok() {} + assert!(matches!( + fx.events.try_recv(), + Err(broadcast::error::TryRecvError::Closed) + )); } #[tokio::test] async fn an_agent_that_fails_to_parse_reports_a_run_failure_and_records_no_run() { - let table = Conversations::new(); - let conversation = table.open("unclosed"); - let recorder = Arc::new(MemoryRecorder::new()); - let mut errors = conversation.subscribe_errors(); + let mut fx = ConversationFixture::open("unclosed"); let unclosed = "---\nname: unclosed\ndescription: d\nrunvil: 0\n\n## Only\n".to_owned(); - let (host, _setup) = run_for(&conversation, Arc::clone(&recorder), unclosed.clone()); + let (host, _setup) = fx.run_for(unclosed.clone()); let parse_failure = host .parse(AGENT) - .expect_err("a frontmatter that is never closed does not parse"); + .expect_err("unclosed frontmatter does not parse"); - ended(start(&conversation, &recorder, unclosed)).await; + fx.run_to_end(unclosed).await; - let reports = reports(&mut errors); assert_eq!( - reports, + fx.reports(), [SessionFailure { kind: FailureKind::RunFailed, - message: parse_failure.located_message(), - }], - "the parse failure's located message is the one run-failed report" + message: parse_failure.located_message() + }] ); - assert_eq!(conversation.run_id(), None, "no run began"); + assert_eq!(fx.conversation.run_id(), None, "no run began"); assert_eq!( - recorder.meta(RunId::from_raw(1)), + fx.recorder.meta(RunId::from_raw(1)), None, - "the recorder holds no run" - ); - assert_eq!(conversation.state(), SessionState::Closed); - assert!( - table.get(conversation.id()).is_none(), - "the conversation ends with its parse failure" + "recorder holds no run" ); + assert_eq!(fx.conversation.state(), SessionState::Closed); + assert!(fx.table.get(fx.conversation.id()).is_none()); } #[tokio::test] async fn a_completed_report_reports_nothing_and_ends_the_conversation() { - let table = Conversations::new(); - let conversation = table.open("done"); - let recorder = Arc::new(MemoryRecorder::new()); - let mut errors = conversation.subscribe_errors(); + let mut fx = ConversationFixture::open("done"); + fx.run_to_end(prompt("return 'finished'")).await; - ended(start(&conversation, &recorder, prompt("return 'finished'"))).await; - - assert!( - reports(&mut errors).is_empty(), - "a completed run reports nothing" - ); - assert_eq!(conversation.state(), SessionState::Closed); - let run = conversation.run_id().expect("the recorder began the run"); - assert_eq!( - recorder.result(run), - Some(Ok("finished".to_owned())), - "the result is the text the agent's Lua returned, where a run with no text ends as `done`" - ); - assert!(table.get(conversation.id()).is_none()); + assert!(fx.reports().is_empty(), "a completed run reports nothing"); + assert_eq!(fx.conversation.state(), SessionState::Closed); + assert_eq!(fx.result(), Some(Ok("finished".to_owned()))); + assert!(fx.table.get(fx.conversation.id()).is_none()); } #[tokio::test] async fn a_close_while_the_agent_waits_on_its_inbox_cancels_the_run_and_reports_the_cancel() { - let table = Conversations::new(); - let conversation = table.open("receive"); - let recorder = Arc::new(MemoryRecorder::new()); - let mut errors = conversation.subscribe_errors(); - let mut events = conversation.subscribe_events(); - let run = start(&conversation, &recorder, prompt(RECEIVES)); - waits_on_its_inbox(&mut events).await; + let mut fx = ConversationFixture::open("receive"); + let run = fx.start_until_waiting(prompt(RECEIVES)).await; assert!( - table.close(conversation.id()), - "the open conversation closes" + fx.table.close(fx.conversation.id()), + "open conversation closes" ); - assert_eq!( - conversation.state(), - SessionState::Closing, - "a close is Closing until the run ends" - ); - ended(run).await; + assert_eq!(fx.conversation.state(), SessionState::Closing); + ConversationFixture::finish(run).await; - let reports = reports(&mut errors); - assert_eq!( - reports.iter().map(|report| report.kind).collect::>(), - [FailureKind::Canceled], - "a canceled report is the cancel's one report" - ); - assert_eq!(conversation.state(), SessionState::Closed); + assert_eq!(fx.failure_kinds(), [FailureKind::Canceled]); + assert_eq!(fx.conversation.state(), SessionState::Closed); + assert!(!fx.conversation.send_input("after the close".to_owned())); + assert!(matches!(fx.result(), Some(Err(error)) if error.is_canceled())); assert!( - !conversation.send_input("after the close".to_owned()), - "an ended run refuses the message" + !fx.table.close(fx.conversation.id()), + "second close is a no-op" ); - let run = conversation.run_id().expect("the recorder began the run"); - assert!(matches!( - recorder.result(run), - Some(Err(error)) if error.is_canceled() - )); - assert!(!table.close(conversation.id()), "a second close is a no-op"); } #[tokio::test] async fn a_close_before_the_run_starts_ends_its_recorded_run_canceled() { - let table = Conversations::new(); - let conversation = table.open("early"); - let recorder = Arc::new(MemoryRecorder::new()); - let mut errors = conversation.subscribe_errors(); + let mut fx = ConversationFixture::open("early"); + fx.conversation.close(); + fx.run_to_end(prompt("return 'never'")).await; - conversation.close(); - ended(start(&conversation, &recorder, prompt("return 'never'"))).await; - - let run = conversation.run_id().expect("the recorder began the run"); - assert!(matches!( - recorder.result(run), - Some(Err(error)) if error.is_canceled() - )); + assert!(matches!(fx.result(), Some(Err(error)) if error.is_canceled())); assert!( - recorder.records(run).is_empty(), - "the run ended before it started" + fx.recorder.records(fx.run_id()).is_empty(), + "ended before starting" ); - assert_eq!( - reports(&mut errors) - .iter() - .map(|report| report.kind) - .collect::>(), - [FailureKind::Canceled] - ); - assert_eq!(conversation.state(), SessionState::Closed); + assert_eq!(fx.failure_kinds(), [FailureKind::Canceled]); + assert_eq!(fx.conversation.state(), SessionState::Closed); } #[tokio::test] async fn a_stop_while_the_agent_waits_on_its_inbox_leaves_the_wait_and_a_message_answers_it() { - let table = Conversations::new(); - let conversation = table.open("receive"); - let recorder = Arc::new(MemoryRecorder::new()); - let mut errors = conversation.subscribe_errors(); - let mut events = conversation.subscribe_events(); - let run = start(&conversation, &recorder, prompt(RECEIVES)); - waits_on_its_inbox(&mut events).await; + let mut fx = ConversationFixture::open("receive"); + let run = fx.start_until_waiting(prompt(RECEIVES)).await; - conversation.stop_round(); - // The stop is taken by the run's loop; the agent's wait on its inbox - // has nothing in flight for it to drop, so a message still answers it. + fx.conversation.stop_round(); tokio::task::yield_now().await; assert!( - conversation.send_input("still here".to_owned()), - "the live run accepts the message" + fx.conversation.send_input("still here".to_owned()), + "live run accepts input" ); - ended(run).await; + ConversationFixture::finish(run).await; - assert!(reports(&mut errors).is_empty(), "a stop is never an error"); - let run = conversation.run_id().expect("the recorder began the run"); - assert_eq!( - recorder.result(run), - Some(Ok("still here".to_owned())), - "the run went on past the stop to the operator's message" - ); + assert!(fx.reports().is_empty(), "a stop is never an error"); + assert_eq!(fx.result(), Some(Ok("still here".to_owned()))); } #[tokio::test] async fn a_message_sent_before_the_run_is_handed_its_harness_returns_false_and_reaches_no_run() { - let table = Conversations::new(); - let conversation = table.open("early"); - let recorder = Arc::new(MemoryRecorder::new()); - assert!( - !conversation.send_input("too early".to_owned()), - "a conversation whose run has no Harness yet refuses the message" - ); - let mut events = conversation.subscribe_events(); - let run = start(&conversation, &recorder, prompt(RECEIVES)); - waits_on_its_inbox(&mut events).await; - assert!( - conversation.send_input("in time".to_owned()), - "the run, handed its Harness, accepts the message" - ); - ended(run).await; + let mut fx = ConversationFixture::open("early"); + assert!(!fx.conversation.send_input("too early".to_owned())); + let run = fx.start_until_waiting(prompt(RECEIVES)).await; + assert!(fx.conversation.send_input("in time".to_owned())); + ConversationFixture::finish(run).await; - let run = conversation.run_id().expect("the recorder began the run"); - assert_eq!( - recorder.result(run), - Some(Ok("in time".to_owned())), - "the run read the message sent once it had its Harness" - ); + assert_eq!(fx.result(), Some(Ok("in time".to_owned()))); assert!( - !recorder - .records(run) + !fx.recorder + .records(fx.run_id()) .iter() .any(|record| record.payload.to_string().contains("too early")), - "the refused message reached no record" + "refused message reached no record" ); } diff --git a/crates/workshop/agents/tests/it/support.rs b/crates/workshop/agents/tests/it/support.rs index 62eff50a..75abbe11 100644 --- a/crates/workshop/agents/tests/it/support.rs +++ b/crates/workshop/agents/tests/it/support.rs @@ -1,18 +1,22 @@ -//! Shared fixtures: a Host and a per-run setup built around the recorder -//! tee a conversation hands it. +//! Shared fixtures: a Host, a per-run setup built around the recorder +//! tee, and [`ConversationFixture`] for driving a run through a Harness. + +#![expect(clippy::expect_used, reason = "test helpers fail by panicking")] use std::sync::Arc; +use std::time::Duration; use harness_gateway_client::TokioTimer; -use runvil::harness::{FindTextPrompt, MemoryRecorder, OfflineBroker}; -use runvil::{Host, RunSetup}; -use workshop_agents::Conversation; +use runvil::harness::{FindTextPrompt, MemoryRecorder, OfflineBroker, RunId}; +use runvil::{Error, Host, RunSetup}; +use tokio::sync::broadcast; +use tokio::task::JoinHandle; +use workshop_agents::{Conversation, Conversations, FailureKind, SessionEvent, SessionFailure}; -/// The name the fixture Host finds its one agent by. pub(crate) const AGENT: &str = "fixture"; +pub(crate) const RECEIVES: &str = "return (tasks.receive())"; +const DEADLINE: Duration = Duration::from_secs(10); -/// A prompt whose one section runs `lua`, declaring the user Pack, as a -/// conversation's agent does. pub(crate) fn prompt(lua: &str) -> String { format!( "---\nname: fixture\ndescription: a conversation fixture\nrunvil: 0\n\ @@ -21,15 +25,78 @@ pub(crate) fn prompt(lua: &str) -> String { ) } -/// A Host that finds `source` as [`AGENT`], beside the setup of a run with -/// a user, recording into `recorder` through the conversation's tee. -pub(crate) fn run_for( - conversation: &Conversation, - recorder: Arc, - source: String, -) -> (Arc, RunSetup) { - let host = Host::builder(FindTextPrompt::new(AGENT, source)).build(); - let setup = - RunSetup::new(conversation.recorder(recorder), OfflineBroker, TokioTimer).has_user(true); - (host, setup) +pub(crate) struct ConversationFixture { + pub(crate) table: Conversations, + pub(crate) conversation: Conversation, + pub(crate) recorder: Arc, + pub(crate) errors: broadcast::Receiver, + pub(crate) events: broadcast::Receiver, +} + +impl ConversationFixture { + pub(crate) fn open(agent: &str) -> Self { + let table = Conversations::new(); + let conversation = table.open(agent); + let errors = conversation.subscribe_errors(); + let events = conversation.subscribe_events(); + Self { + table, + conversation, + recorder: Arc::new(MemoryRecorder::new()), + errors, + events, + } + } + + pub(crate) fn run_for(&self, source: String) -> (Arc, RunSetup) { + let host = Host::builder(FindTextPrompt::new(AGENT, source)).build(); + let tee = self.conversation.recorder(Arc::clone(&self.recorder)); + let setup = RunSetup::new(tee, OfflineBroker, TokioTimer).has_user(true); + (host, setup) + } + + pub(crate) fn start(&self, source: String) -> JoinHandle<()> { + let (host, setup) = self.run_for(source); + let conversation = self.conversation.clone(); + tokio::spawn(async move { conversation.run(host, AGENT, setup).await }) + } + + pub(crate) async fn run_to_end(&self, source: String) { + Self::finish(self.start(source)).await; + } + + pub(crate) async fn start_until_waiting(&mut self, source: String) -> JoinHandle<()> { + let handle = self.start(source); + tokio::time::timeout(DEADLINE, async { + while self.events.recv().await.expect("event channel open").event["kind"] + != "inbox_waiting" + {} + }) + .await + .expect("agent waits on its inbox in time"); + handle + } + + pub(crate) async fn finish(run: JoinHandle<()>) { + tokio::time::timeout(DEADLINE, run) + .await + .expect("run ends in time") + .expect("run task joins"); + } + + pub(crate) fn reports(&mut self) -> Vec { + std::iter::from_fn(|| self.errors.try_recv().ok()).collect() + } + + pub(crate) fn failure_kinds(&mut self) -> Vec { + self.reports().into_iter().map(|r| r.kind).collect() + } + + pub(crate) fn run_id(&self) -> RunId { + self.conversation.run_id().expect("recorder began the run") + } + + pub(crate) fn result(&self) -> Option> { + self.recorder.result(self.run_id()) + } } diff --git a/crates/workshop/desktop/build.rs b/crates/workshop/desktop/build.rs index d2200271..bd71a2fa 100644 --- a/crates/workshop/desktop/build.rs +++ b/crates/workshop/desktop/build.rs @@ -25,113 +25,82 @@ use std::env; use std::error::Error; use std::fs; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; /// The variable naming a sidecar to install, shared with `build-workshop`. const GATEWAY_SIDECAR_VARIABLE: &str = "RUNVIL_GATEWAY_SIDECAR"; fn main() -> Result<(), Box> { - install_gateway_sidecar()?; - tauri_build::try_build(tauri_build::Attributes::new().app_manifest( - tauri_build::AppManifest::new().commands(&["desktop_update_supported", "quit"]), - ))?; - Ok(()) -} + if env::var("CARGO_CFG_TARGET_OS")? == "windows" { + let target = env::var("TARGET")?; + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?); + let sidecar = manifest_dir + .join("binaries") + .join(format!("runvil-gateway-{target}.exe")); + let mut marker = sidecar.as_os_str().to_owned(); + marker.push(".pinned"); + let marker = PathBuf::from(marker); -/// Puts the sidecar where `bundle.externalBin` resolves it: an explicit -/// `RUNVIL_GATEWAY_SIDECAR` file when one is named, else what is already -/// staged, with a warning when the staged file is the stub. -fn install_gateway_sidecar() -> Result<(), Box> { - if env::var("CARGO_CFG_TARGET_OS")? != "windows" { - return Ok(()); - } - let target = env::var("TARGET")?; - let exe_suffix = ".exe"; - let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?); - let sidecar = manifest_dir - .join("binaries") - .join(format!("runvil-gateway-{target}{exe_suffix}")); - - println!("cargo:rerun-if-env-changed={GATEWAY_SIDECAR_VARIABLE}"); - // The marker is written only by `tools/fetch-gateway-sidecar.mjs`, never - // here, so watching it cannot loop. Watching it means re-staging a - // release over a stub re-runs this script and the warning below clears. - println!("cargo:rerun-if-changed={}", pin_marker(&sidecar).display()); - if let Some(named) = env::var_os(GATEWAY_SIDECAR_VARIABLE) { - let named = PathBuf::from(named); - if named.as_os_str().is_empty() { - return Err(format!("{GATEWAY_SIDECAR_VARIABLE} names no file").into()); - } - if !named.is_file() { - return Err(format!( - "{GATEWAY_SIDECAR_VARIABLE} names {}, which is not a file", - named.display() - ) - .into()); + println!("cargo:rerun-if-env-changed={GATEWAY_SIDECAR_VARIABLE}"); + // The marker is written only by `tools/fetch-gateway-sidecar.mjs`, never + // here, so watching it cannot loop. Watching it means re-staging a + // release over a stub re-runs this script and the warning below clears. + println!("cargo:rerun-if-changed={}", marker.display()); + if let Some(named) = env::var_os(GATEWAY_SIDECAR_VARIABLE) { + let named = PathBuf::from(named); + if named.as_os_str().is_empty() { + return Err(format!("{GATEWAY_SIDECAR_VARIABLE} names no file").into()); + } + if !named.is_file() { + return Err(format!( + "{GATEWAY_SIDECAR_VARIABLE} names {}, which is not a file", + named.display() + ) + .into()); + } + // `cargo workshop` stages the file it names here before this script + // runs. Copying it again would fail on Windows when the file is + // read-only, since the first copy carries that attribute to the slot: + // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfilew + if !fs::read(&sidecar) + .is_ok_and(|staged| fs::read(&named).is_ok_and(|source| source == staged)) + { + if let Some(parent) = sidecar.parent() { + fs::create_dir_all(parent) + .map_err(|e| format!("create {}: {e}", parent.display()))?; + } + fs::copy(&named, &sidecar).map_err(|e| { + format!( + "copy the gateway sidecar {} to {}: {e}", + named.display(), + sidecar.display() + ) + })?; + println!( + "cargo:warning=installed gateway sidecar {} from {}", + sidecar.display(), + named.display() + ); + } + } else if fs::read_to_string(&marker).is_ok_and(|text| { + text.contains("\"kind\": \"stub\"") || text.contains("\"kind\":\"stub\"") + }) { + // CI stages a stub for compile-only jobs, so a build that copies + // one is expected there. A person building locally gets the same + // warning, which is the last chance to notice before an app that + // cannot start exists on disk. + println!( + "cargo:warning={} is a compile-only stub Gateway and cannot run; \ + run `node tools/fetch-gateway-sidecar.mjs --target {}` and rebuild for a \ + Gateway that starts", + sidecar.display(), + target + ); } - copy_forward(&named, &sidecar)?; - return Ok(()); } - if sidecar_is_stub(&sidecar) { - // CI stages a stub for compile-only jobs, so a build that copies - // one is expected there. A person building locally gets the same - // warning, which is the last chance to notice before an app that - // cannot start exists on disk. - println!( - "cargo:warning={} is a compile-only stub Gateway and cannot run; \ - run `node tools/fetch-gateway-sidecar.mjs --target {}` and rebuild for a \ - Gateway that starts", - sidecar.display(), - target - ); - } - Ok(()) -} - -/// Copies `source` over `sidecar`, creating the directory and reporting -/// the copy so a surprising sidecar is visible in the build log. -fn copy_forward(source: &Path, sidecar: &Path) -> Result<(), String> { - // `cargo workshop` stages the file it names here before this script - // runs. Copying it again would fail on Windows when the file is - // read-only, since the first copy carries that attribute to the slot: - // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfilew - if fs::read(sidecar).is_ok_and(|staged| fs::read(source).is_ok_and(|named| named == staged)) { - return Ok(()); - } - if let Some(parent) = sidecar.parent() { - fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?; - } - fs::copy(source, sidecar).map_err(|e| { - format!( - "copy the gateway sidecar {} to {}: {e}", - source.display(), - sidecar.display() - ) - })?; - println!( - "cargo:warning=installed gateway sidecar {} from {}", - sidecar.display(), - source.display() - ); + tauri_build::try_build(tauri_build::Attributes::new().app_manifest( + tauri_build::AppManifest::new().commands(&["desktop_update_supported", "quit"]), + ))?; Ok(()) } - -/// The marker beside the sidecar: `.pinned`. -fn pin_marker(sidecar: &Path) -> PathBuf { - let mut marker = sidecar.as_os_str().to_owned(); - marker.push(".pinned"); - PathBuf::from(marker) -} - -/// Whether the marker says the staged sidecar is the compile-only stub -/// rather than the pinned release. The marker is the fetch script's JSON, -/// so a substring check keeps this script free of a JSON dependency. A -/// missing or malformed marker reads as unknown, and unknown is not a stub: -/// the app's own boot check still refuses to run one. -fn sidecar_is_stub(sidecar: &Path) -> bool { - let Ok(text) = fs::read_to_string(pin_marker(sidecar)) else { - return false; - }; - text.contains("\"kind\": \"stub\"") || text.contains("\"kind\":\"stub\"") -} diff --git a/crates/workshop/desktop/src/bridge.rs b/crates/workshop/desktop/src/bridge.rs index 438e946a..2d88535d 100644 --- a/crates/workshop/desktop/src/bridge.rs +++ b/crates/workshop/desktop/src/bridge.rs @@ -27,10 +27,10 @@ use std::path::PathBuf; use std::sync::mpsc; use anyhow::Context as _; +use tauri::WebviewWindow; use webview2_com::Microsoft::Web::WebView2::Win32::{ COREWEBVIEW2_PERMISSION_KIND, COREWEBVIEW2_PERMISSION_KIND_MICROPHONE, - COREWEBVIEW2_PERMISSION_STATE_ALLOW, ICoreWebView2, ICoreWebView2File, - ICoreWebView2PermissionRequestedEventArgs, ICoreWebView2Settings3, + COREWEBVIEW2_PERMISSION_STATE_ALLOW, ICoreWebView2File, ICoreWebView2Settings3, ICoreWebView2WebMessageReceivedEventArgs, ICoreWebView2WebMessageReceivedEventArgs2, }; use webview2_com::{PermissionRequestedEventHandler, WebMessageReceivedEventHandler, take_pwstr}; @@ -53,12 +53,77 @@ const DROP_MESSAGE: &str = "workspace-drop"; /// Returns an error when the webview dispatch or a COM subscription fails; /// the caller logs it and Explorer drops plus the mic grant degrade, /// nothing else. -pub(crate) fn attach(window: &tauri::WebviewWindow) -> anyhow::Result<()> { +pub(crate) fn attach(window: &WebviewWindow) -> anyhow::Result<()> { let window_for_handler = window.clone(); let (tx, rx) = mpsc::channel(); window .with_webview(move |webview| { - let _ = tx.send(attach_handlers(&webview, window_for_handler)); + let result = (|| -> windows_core::Result<()> { + let controller = webview.controller(); + // SAFETY: `controller` is the live controller of this window's webview, + // called on the webview's own thread (with_webview guarantees it), and + // the generated out-param write is valid by construction. + let core = unsafe { controller.CoreWebView2()? }; + + // WebView2's built-in keyboard shortcuts (Ctrl+=, Ctrl+-, F5, Ctrl+U, + // etc.) race the app's JS keydown handler. Disabling them here makes + // the JS handler in shortcuts.ts the sole zoom path. + // SAFETY: `core` is the live interface supplied by the webview controller, + // and this call runs on that webview's thread. + let settings = unsafe { core.Settings()? }; + let settings3: ICoreWebView2Settings3 = settings.cast()?; + // SAFETY: `settings3` was queried from the live settings interface and is + // called on the owning webview thread. + unsafe { settings3.SetAreBrowserAcceleratorKeysEnabled(false)? }; + + // Forward the real OS paths of a `workspace-drop` message's attached `File` + // objects into the page's grant flow. The dispatch is queued onto the next + // event-loop turn, never run inside the callback: on a real Explorer drop + // the message can arrive with the OLE drop still on the UI thread's stack, + // and eval'ing into the page from inside the callback is the reentrancy + // that hangs the app (WebView2Feedback #2498/#3559). + let mut token = 0_i64; + let drop_handler = + WebMessageReceivedEventHandler::create(Box::new(move |_, args| { + let Some(args) = args else { + return Ok(()); + }; + handle_web_message(&args, |paths| { + let dispatch_window = window_for_handler.clone(); + if let Err(error) = window_for_handler.run_on_main_thread(move || { + dispatch_file_drop(&dispatch_window, &paths); + }) { + eprintln!("could not queue the file-drop dispatch: {error}"); + } + }); + Ok(()) + })); + // SAFETY: `core` is live on its owning thread, `drop_handler` outlives the + // subscription (the webview holds it), and `token` is a valid out-pointer + // to a stack local. + unsafe { core.add_WebMessageReceived(&drop_handler, &raw mut token)? }; + + // Grant the microphone automatically. Every other permission kind returns + // without a `SetState` call, keeping WebView2's default handling. + let permission_handler = + PermissionRequestedEventHandler::create(Box::new(move |_, args| { + let Some(args) = args else { + return Ok(()); + }; + let mut kind = COREWEBVIEW2_PERMISSION_KIND::default(); + // SAFETY: `args` is the live event argument WebView2 handed the handler, + // and `kind` is a valid out-pointer to a stack local. + unsafe { args.PermissionKind(&raw mut kind) }?; + if kind == COREWEBVIEW2_PERMISSION_KIND_MICROPHONE { + // SAFETY: `args` is live as above. + unsafe { args.SetState(COREWEBVIEW2_PERMISSION_STATE_ALLOW) }?; + } + Ok(()) + })); + // SAFETY: same preconditions as the drop subscription above. + unsafe { core.add_PermissionRequested(&permission_handler, &raw mut token) } + })(); + let _ = tx.send(result); }) .context("dispatch the bridge attach to the webview thread")?; rx.recv() @@ -66,69 +131,6 @@ pub(crate) fn attach(window: &tauri::WebviewWindow) -> anyhow::Result<()> { .context("attach the WebView2 bridge") } -/// The COM subscriptions, run on the thread that owns the webview. -fn attach_handlers( - webview: &tauri::webview::PlatformWebview, - window: tauri::WebviewWindow, -) -> windows_core::Result<()> { - let controller = webview.controller(); - // SAFETY: `controller` is the live controller of this window's webview, - // called on the webview's own thread (with_webview guarantees it), and - // the generated out-param write is valid by construction. - let core = unsafe { controller.CoreWebView2()? }; - disable_browser_accelerator_keys(&core)?; - attach_drop_bridge(&core, window)?; - attach_permission_grant(&core)?; - Ok(()) -} - -/// WebView2's built-in keyboard shortcuts (Ctrl+=, Ctrl+-, F5, Ctrl+U, -/// etc.) race the app's JS keydown handler. Disabling them here makes -/// the JS handler in shortcuts.ts the sole zoom path. -fn disable_browser_accelerator_keys(core: &ICoreWebView2) -> windows_core::Result<()> { - // SAFETY: `core` is the live interface supplied by the webview controller, - // and this call runs on that webview's thread. - let settings = unsafe { core.Settings()? }; - let settings3: ICoreWebView2Settings3 = settings.cast()?; - // SAFETY: `settings3` was queried from the live settings interface and is - // called on the owning webview thread. - unsafe { settings3.SetAreBrowserAcceleratorKeysEnabled(false) } -} - -/// The drop half: forward the real OS paths of a `workspace-drop` -/// message's attached `File` objects into the page's grant flow. The -/// dispatch is queued onto the next event-loop turn, never run inside -/// the callback: on a real Explorer drop the message can arrive with -/// the OLE drop still on the UI thread's stack, and eval'ing into the -/// page from inside the callback is the reentrancy that hangs the app -/// (WebView2Feedback #2498/#3559). -fn attach_drop_bridge( - core: &ICoreWebView2, - window: tauri::WebviewWindow, -) -> windows_core::Result<()> { - let handler = WebMessageReceivedEventHandler::create(Box::new(move |_, args| { - let Some(args) = args else { - return Ok(()); - }; - let window = window.clone(); - handle_web_message(&args, move |paths| { - let queued = window.run_on_main_thread({ - let window = window.clone(); - move || dispatch_file_drop(&window, &paths) - }); - if let Err(error) = queued { - eprintln!("could not queue the file-drop dispatch: {error}"); - } - }); - Ok(()) - })); - let mut token = 0_i64; - // SAFETY: `core` is live on its owning thread, `handler` outlives the - // subscription (the webview holds it), and `token` is a valid out-pointer - // to a stack local. - unsafe { core.add_WebMessageReceived(&handler, &raw mut token) } -} - /// Handles one web message: when it is the drop message with file /// attachments, hands their real OS paths to `defer`. The event args die /// with the callback, so the paths are read here; everything after - @@ -146,35 +148,6 @@ fn handle_web_message( } } -/// The permission half: grant the microphone automatically. Every other -/// permission kind returns without a `SetState` call, keeping WebView2's -/// default handling. -fn attach_permission_grant(core: &ICoreWebView2) -> windows_core::Result<()> { - let handler = PermissionRequestedEventHandler::create(Box::new(move |_, args| { - let Some(args) = args else { - return Ok(()); - }; - grant_microphone(&args) - })); - let mut token = 0_i64; - // SAFETY: same preconditions as the drop subscription above. - unsafe { core.add_PermissionRequested(&handler, &raw mut token) } -} - -/// Answers one permission request: allow for the microphone, default -/// handling for everything else. -fn grant_microphone(args: &ICoreWebView2PermissionRequestedEventArgs) -> windows_core::Result<()> { - let mut kind = COREWEBVIEW2_PERMISSION_KIND::default(); - // SAFETY: `args` is the live event argument WebView2 handed the handler, - // and `kind` is a valid out-pointer to a stack local. - unsafe { args.PermissionKind(&raw mut kind) }?; - if kind == COREWEBVIEW2_PERMISSION_KIND_MICROPHONE { - // SAFETY: `args` is live as above. - unsafe { args.SetState(COREWEBVIEW2_PERMISSION_STATE_ALLOW) }?; - } - Ok(()) -} - /// The message's string payload, or `None` when the message is not a /// string (a JSON object posted by some other page code, say). fn message_string(args: &ICoreWebView2WebMessageReceivedEventArgs) -> Option { @@ -341,94 +314,86 @@ mod tests { FakeArgs { message, objects }.into() } - /// A fake file attachment, as the plain IUnknown the collection holds. - fn file_object(path: &'static str) -> IUnknown { - let file = ICoreWebView2File::from(FakeFile { path }); - match file.cast() { - Ok(unknown) => unknown, - Err(error) => panic!("a file must cast to IUnknown: {error}"), - } - } - - #[test] - fn the_drop_message_string_is_read_back() { - let args = args_with(Some(DROP_MESSAGE), Vec::new()); - assert_eq!(message_string(&args).as_deref(), Some(DROP_MESSAGE)); - } - - #[test] - fn a_non_string_message_reads_as_none() { - let args = args_with(None, Vec::new()); - assert_eq!(message_string(&args), None); - } - - #[test] - fn file_attachments_become_their_os_paths() { - let files = vec![ - file_object(r"C:\Users\Vinnie\Documents\project"), - file_object(r"D:\src\notes.md"), - ]; - let args = args_with(Some(DROP_MESSAGE), files); - assert_eq!( - dropped_paths(&args), - vec![ - PathBuf::from(r"C:\Users\Vinnie\Documents\project"), - PathBuf::from(r"D:\src\notes.md"), - ] - ); - } - - #[test] - fn non_file_attachments_are_skipped() { - // The collection object itself is included as a non-file IUnknown. - let not_a_file: IUnknown = ICoreWebView2ObjectCollectionView::from(FakeObjects { - objects: Vec::new(), - }) - .cast() - .unwrap_or_else(|error| panic!("a collection must cast to IUnknown: {error}")); - let objects = vec![not_a_file, file_object(r"C:\only\this\one.txt")]; - let args = args_with(Some(DROP_MESSAGE), objects); - assert_eq!( - dropped_paths(&args), - vec![PathBuf::from(r"C:\only\this\one.txt")] - ); - } - - #[test] - fn a_message_with_no_attachments_yields_no_paths() { - let args = args_with(Some(DROP_MESSAGE), Vec::new()); - assert!(dropped_paths(&args).is_empty()); - } - - #[test] - fn a_drop_message_defers_its_paths() { - let args = args_with( + // `Some(path)` is a file attachment; `None` is a non-file COM attachment. + type Case = ( + &'static str, + Option<&'static str>, + &'static [Option<&'static str>], + &'static [&'static str], + bool, + ); + + const CASES: &[Case] = &[ + ( + "drop with files", Some(DROP_MESSAGE), - vec![file_object(r"C:\Users\Vinnie\Documents\project")], - ); - let (tx, rx) = std::sync::mpsc::channel(); - handle_web_message(&args, move |paths| { - tx.send(paths).expect("the test channel is open"); - }); - assert_eq!( - rx.recv().expect("the drop's paths were deferred"), - vec![PathBuf::from(r"C:\Users\Vinnie\Documents\project")] - ); - } - - #[test] - fn a_non_drop_message_defers_nothing() { - let args = args_with(Some("other-message"), vec![file_object(r"D:\src\notes.md")]); - let called = std::cell::Cell::new(false); - handle_web_message(&args, |_| called.set(true)); - assert!(!called.get()); + &[ + Some(r"C:\Users\Vinnie\Documents\project"), + Some(r"D:\src\notes.md"), + ], + &[r"C:\Users\Vinnie\Documents\project", r"D:\src\notes.md"], + true, + ), + ( + "drop skips non-file", + Some(DROP_MESSAGE), + &[None, Some(r"C:\only\this\one.txt")], + &[r"C:\only\this\one.txt"], + true, + ), + ( + "drop only non-file", + Some(DROP_MESSAGE), + &[None], + &[], + false, + ), + ("drop empty", Some(DROP_MESSAGE), &[], &[], false), + ( + "other message", + Some("other-message"), + &[Some(r"D:\src\notes.md")], + &[r"D:\src\notes.md"], + false, + ), + ( + "non-string with file", + None, + &[Some(r"D:\src\notes.md")], + &[r"D:\src\notes.md"], + false, + ), + ("non-string empty", None, &[], &[], false), + ]; + + fn attachment_object(path: Option<&'static str>) -> IUnknown { + match path { + Some(path) => ICoreWebView2File::from(FakeFile { path }) + .cast() + .unwrap_or_else(|e| panic!("file casts to IUnknown: {e}")), + None => ICoreWebView2ObjectCollectionView::from(FakeObjects { + objects: Vec::new(), + }) + .cast() + .unwrap_or_else(|e| panic!("collection casts to IUnknown: {e}")), + } } #[test] - fn a_drop_message_with_no_files_defers_nothing() { - let args = args_with(Some(DROP_MESSAGE), Vec::new()); - let called = std::cell::Cell::new(false); - handle_web_message(&args, |_| called.set(true)); - assert!(!called.get()); + fn web_message_handling_cases() { + for &(label, message, attachments, expected, defers) in CASES { + let objects = attachments.iter().copied().map(attachment_object).collect(); + let args = args_with(message, objects); + assert_eq!( + message_string(&args).as_deref(), + message, + "{label}: message" + ); + let expected: Vec = expected.iter().map(PathBuf::from).collect(); + assert_eq!(dropped_paths(&args), expected, "{label}: dropped_paths"); + let mut deferred = None; + handle_web_message(&args, |paths| deferred = Some(paths)); + assert_eq!(deferred, defers.then_some(expected), "{label}: deferred"); + } } } diff --git a/crates/workshop/desktop/src/config.rs b/crates/workshop/desktop/src/config.rs index c4e9493d..e698070a 100644 --- a/crates/workshop/desktop/src/config.rs +++ b/crates/workshop/desktop/src/config.rs @@ -13,10 +13,11 @@ //! where the installer lays it out: beside Workshop on Windows, and //! inside Workshop's bundle on macOS and Linux. +use std::env; use std::path::{Path, PathBuf}; use anyhow::Context as _; -use workshop_server_api::Config; +use workshop_server_api::{AgentsConfig, Config, GatewayConfig, ServerConfig, discovery}; /// Canonical file name searched for at each candidate location. const CONFIG_FILE_NAME: &str = "workshop.toml"; @@ -43,18 +44,18 @@ const DESKTOP_BIND: &str = "127.0.0.1:0"; /// Returns an error when a discovered file cannot be loaded or the /// executable or current directory cannot be determined. pub(crate) fn load() -> anyhow::Result { - let exe = std::env::current_exe().context("locate the executable")?; + let exe = env::current_exe().context("locate the executable")?; let exe_dir = exe .parent() .context("the executable has no parent directory")?; - let cwd = std::env::current_dir().context("locate the current directory")?; - let appimage = workshop_server_api::discovery::running_appimage( + let cwd = env::current_dir().context("locate the current directory")?; + let appimage = discovery::running_appimage( &exe, - std::env::var_os("APPIMAGE").as_deref(), - std::env::var_os("APPDIR").as_deref(), + env::var_os("APPIMAGE").as_deref(), + env::var_os("APPDIR").as_deref(), ); - let plugins = workshop_server_api::discovery::installed_plugin_dir(&exe, appimage.as_deref()); - let mut config = load_in(exe_dir, &cwd, std::env::home_dir().as_deref())?; + let plugins = discovery::installed_plugin_dir(&exe, appimage.as_deref()); + let mut config = load_in(exe_dir, &cwd, env::home_dir().as_deref())?; name_plugin_dir(&mut config, plugins); Ok(config) } @@ -64,16 +65,25 @@ pub(crate) fn load() -> anyhow::Result { /// candidate and anchoring the no-file default at the current directory, /// matching `Config::parse`'s anchor degradation. fn load_in(exe_dir: &Path, cwd: &Path, home: Option<&Path>) -> anyhow::Result { - let candidates = candidates_from(exe_dir, cwd, home); - match first_existing(&candidates) { - Some(path) => { - let mut config = - Config::load(&path).with_context(|| format!("load {}", path.display()))?; - shape_for_desktop(&mut config); - Ok(config) - } - None => Ok(default_config(home)), + if let Some(path) = candidates_from(exe_dir, cwd, home).find(|path| path.is_file()) { + let mut config = Config::load(&path).with_context(|| format!("load {}", path.display()))?; + DESKTOP_BIND.clone_into(&mut config.server.bind); + return Ok(config); } + let mut config = Config { + gateway: GatewayConfig { + base_url: String::new(), + api_key: String::new(), + }, + server: ServerConfig { + bind: DESKTOP_BIND.to_owned(), + state_dir: PathBuf::new(), + }, + agents: AgentsConfig::default(), + }; + let anchor = home.map_or_else(|| PathBuf::from("."), profile_dir); + config.anchor_path_defaults(&anchor); + Ok(config) } /// Gives `config` the installation's Plugin directory, `installed`, unless @@ -86,17 +96,18 @@ fn name_plugin_dir(config: &mut Config, installed: Option) { /// Builds the candidate list in search order from the three base /// directories. -fn candidates_from(exe_dir: &Path, cwd: &Path, home: Option<&Path>) -> Vec { - let mut candidates = vec![exe_dir.join(CONFIG_FILE_NAME), cwd.join(CONFIG_FILE_NAME)]; - if let Some(home) = home { - candidates.push(profile_dir(home).join(CONFIG_FILE_NAME)); - } - candidates -} - -/// Returns the first candidate path that exists, if any. -fn first_existing(candidates: &[PathBuf]) -> Option { - candidates.iter().find(|path| path.is_file()).cloned() +fn candidates_from( + exe_dir: &Path, + cwd: &Path, + home: Option<&Path>, +) -> impl Iterator { + [ + Some(exe_dir.join(CONFIG_FILE_NAME)), + Some(cwd.join(CONFIG_FILE_NAME)), + home.map(|home| profile_dir(home).join(CONFIG_FILE_NAME)), + ] + .into_iter() + .flatten() } /// The profile directory: `/.runvil`. @@ -104,32 +115,6 @@ fn profile_dir(home: &Path) -> PathBuf { home.join(".runvil") } -/// Forces the listener settings the desktop app owns onto a loaded config: the -/// ephemeral loopback bind. -fn shape_for_desktop(config: &mut Config) { - config.server.bind = DESKTOP_BIND.to_string(); -} - -/// The no-file configuration: no explicit gateway (endpoint resolution -/// attaches through the gateway discovery file or fails plainly), with the -/// state and agent prompt paths anchored at the profile directory. -fn default_config(home: Option<&Path>) -> Config { - let mut config = Config { - gateway: workshop_server_api::GatewayConfig { - base_url: String::new(), - api_key: String::new(), - }, - server: workshop_server_api::ServerConfig { - bind: DESKTOP_BIND.to_string(), - state_dir: PathBuf::new(), - }, - agents: workshop_server_api::AgentsConfig::default(), - }; - let anchor = home.map_or_else(|| PathBuf::from("."), profile_dir); - config.anchor_path_defaults(&anchor); - config -} - #[cfg(test)] mod tests { use super::*; @@ -156,11 +141,12 @@ mod tests { #[test] fn candidates_are_ordered_exe_then_cwd_then_profile() { - let candidates = candidates_from( + let candidates: Vec<_> = candidates_from( Path::new("exe-dir"), Path::new("cwd-dir"), Some(Path::new("home-dir")), - ); + ) + .collect(); assert_eq!( candidates, vec![ @@ -173,8 +159,8 @@ mod tests { #[test] fn a_missing_home_skips_the_profile_candidate() { - let candidates = candidates_from(Path::new("exe-dir"), Path::new("cwd-dir"), None); - assert_eq!(candidates.len(), 2, "no profile candidate without a home"); + let candidates = candidates_from(Path::new("exe-dir"), Path::new("cwd-dir"), None).count(); + assert_eq!(candidates, 2, "no profile candidate without a home"); } #[test] diff --git a/crates/workshop/desktop/src/drops.rs b/crates/workshop/desktop/src/drops.rs index 753f318a..eb881546 100644 --- a/crates/workshop/desktop/src/drops.rs +++ b/crates/workshop/desktop/src/drops.rs @@ -1,12 +1,15 @@ //! The `runvil:file-drop` dispatch shared by both drop paths: the -//! Windows WebView2 web-message bridge ([`crate::bridge`]) and Tauri's own +//! Windows WebView2 web-message bridge (`bridge`) and Tauri's own //! drag-drop window event everywhere else. //! //! The page grants each path through the workspace HTTP API; the app never //! reads file bytes merely because a file was dragged onto the window. +use std::borrow::Cow; use std::path::{Path, PathBuf}; +use tauri::WebviewWindow; + /// Renders a dropped OS path for the browser event: the path's own text /// with any Windows verbatim (`\\?\`) prefix stripped, so the page hands /// the workspace API the same spelling Explorer shows. The verbatim UNC @@ -14,22 +17,33 @@ use std::path::{Path, PathBuf}; /// (`\\server\share`). Separators stay native - the workspace server runs /// on this same machine and canonicalizes whatever it receives. #[must_use] -fn normalize_dropped_path(path: &Path) -> String { - let text = path.to_string_lossy().into_owned(); - if let Some(unc) = text.strip_prefix(r"\\?\UNC\") { - return format!(r"\\{unc}"); - } - match text.strip_prefix(r"\\?\") { - Some(stripped) => stripped.to_owned(), - None => text, +fn normalize_dropped_path(path: &Path) -> Cow<'_, str> { + match path.to_string_lossy() { + Cow::Borrowed(text) => { + if let Some(unc) = text.strip_prefix(r"\\?\UNC\") { + Cow::Owned(format!(r"\\{unc}")) + } else if let Some(stripped) = text.strip_prefix(r"\\?\") { + Cow::Borrowed(stripped) + } else { + Cow::Borrowed(text) + } + } + Cow::Owned(mut text) => { + if text.starts_with(r"\\?\UNC\") { + text.replace_range(..r"\\?\UNC\".len(), r"\\"); + } else if text.starts_with(r"\\?\") { + text.drain(..r"\\?\".len()); + } + Cow::Owned(text) + } } } /// Dispatches the `runvil:file-drop` event with the normalized /// dropped paths. The page listens for the event and grants each path /// through the workspace HTTP API. -pub(crate) fn dispatch_file_drop(window: &tauri::WebviewWindow, paths: &[PathBuf]) { - let normalized: Vec = paths +pub(crate) fn dispatch_file_drop(window: &WebviewWindow, paths: &[PathBuf]) { + let normalized: Vec> = paths .iter() .map(|path| normalize_dropped_path(path)) .collect(); @@ -54,31 +68,47 @@ mod tests { use super::normalize_dropped_path; - #[test] - fn dropped_paths_keep_backslashes_spaces_and_unicode() { - for path in [ - r"C:\Users\Vinnie\Documents\project", + // `None` means the path passes through unchanged. + const CASES: &[(&str, &str, Option<&str>)] = &[ + ("plain", r"C:\Users\Vinnie\Documents\project", None), + ( + "spaces", r"C:\Users\Vinnie\My Documents\file name.txt", + None, + ), + ( + "unicode", "C:\\Users\\Vinnie\\caf\u{e9} \u{4e2d}\u{6587}.txt", - r"D:\src\runvil\crates", - ] { - assert_eq!(normalize_dropped_path(Path::new(path)), path, "{path}"); - } - } + None, + ), + ("drive dir", r"D:\src\runvil\crates", None), + ("plain unc", r"\\server\share\file.txt", None), + ("posix", "/home/vinnie/project/file.txt", None), + ( + "verbatim", + r"\\?\C:\Users\Vinnie\file.txt", + Some(r"C:\Users\Vinnie\file.txt"), + ), + ( + "verbatim unicode", + "\\\\?\\D:\\src\\caf\u{e9}.txt", + Some("D:\\src\\caf\u{e9}.txt"), + ), + ( + "verbatim unc", + r"\\?\UNC\server\share\file.txt", + Some(r"\\server\share\file.txt"), + ), + ]; #[test] - fn dropped_paths_shed_the_verbatim_prefix() { - assert_eq!( - normalize_dropped_path(Path::new(r"\\?\C:\Users\Vinnie\file.txt")), - r"C:\Users\Vinnie\file.txt" - ); - assert_eq!( - normalize_dropped_path(Path::new("\\\\?\\D:\\src\\caf\u{e9}.txt")), - "D:\\src\\caf\u{e9}.txt" - ); - assert_eq!( - normalize_dropped_path(Path::new(r"\\?\UNC\server\share\file.txt")), - r"\\server\share\file.txt" - ); + fn dropped_path_normalization_cases() { + for &(label, input, expected) in CASES { + assert_eq!( + normalize_dropped_path(Path::new(input)), + expected.unwrap_or(input), + "{label}: {input}" + ); + } } } diff --git a/crates/workshop/desktop/src/gateway.rs b/crates/workshop/desktop/src/gateway.rs index 26fb360d..8d9a708b 100644 --- a/crates/workshop/desktop/src/gateway.rs +++ b/crates/workshop/desktop/src/gateway.rs @@ -1,29 +1,970 @@ -//! Attach-or-launch lifecycle for the desktop app's Gateway sidecar. +//! Attach-or-launch lifecycle and continuous supervision for the desktop +//! app's Gateway sidecar. //! -//! The sidecar is the local `runvil-gateway` process found through -//! its gateway discovery file or launched detached beside the desktop app. -//! An explicit `workshop.toml` `[gateway]` endpoint is not a sidecar and -//! gets no supervision. -//! -//! Boot planning and detached spawn (`boot`), validated identity -//! (`identity`), and launch-and-wait plus continuous supervision -//! (`supervisor`) are private sibling modules whose imports run both -//! ways. `boot` and `supervisor` import each other: boot launches through -//! the supervisor's cancellable launch-and-wait and authenticates the -//! child as its `RecoveryCandidate`, and the supervisor relaunches -//! through boot's sibling lookup and detached spawn. `identity` and -//! `supervisor` import each other too: `GatewayAttachment` wraps that -//! candidate, and recovery compares processes with -//! `same_gateway_identity`. `boot` also returns `identity`'s -//! `GatewayAttachment`, and `identity` never imports `boot`. - -mod boot; -mod identity; -mod supervisor; - -pub(crate) use boot::ensure_gateway; -pub(crate) use identity::GatewayAttachment; -pub(crate) use supervisor::{GatewaySupervisor, SupervisorShutdown, supervise}; +//! The sidecar is the local `runvil-gateway` process found through its +//! gateway discovery file or launched detached beside the desktop app. An +//! explicit `workshop.toml` `[gateway]` endpoint is not a sidecar and gets +//! no supervision. + +use std::env; +use std::fmt; +use std::fs::File; +use std::io::{self, Read as _}; +#[cfg(unix)] +use std::os::unix::process::CommandExt as _; +#[cfg(windows)] +use std::os::windows::process::CommandExt as _; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitStatus, Stdio}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use anyhow::Context as _; +use workshop_server_api::discovery::{ + self, CancellationToken, GatewayDiscoveryFile, HealthError, LaunchDecision, Resolution, + ShutdownError, SidecarError, ValidatedConnection, +}; +use workshop_server_api::{Config, GatewayUpdater}; + +#[cfg(windows)] +const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000; +#[cfg(windows)] +const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; +#[cfg(windows)] +const DETACHED_PROCESS: u32 = 0x0000_0008; +#[cfg(windows)] +const WINDOWS_DETACHED_CREATION_FLAGS: u32 = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS; +#[cfg(windows)] +const WINDOWS_BREAKAWAY_CREATION_FLAGS: u32 = + CREATE_BREAKAWAY_FROM_JOB | WINDOWS_DETACHED_CREATION_FLAGS; + +/// The text `tools/fetch-gateway-sidecar.mjs --stub` writes, and the only +/// content a file may hold and still be called a Gateway. Checked before a +/// launch because Windows answers a text file with "This version of %1 is +/// not compatible with the version of Windows you're running" and no clue +/// which file was at fault. +const STUB_PREFIX: &str = "This is a placeholder staged by"; + +/// Separate bound for authenticated cleanup of an unpublished owned child. +const LATE_CHILD_SHUTDOWN_BUDGET: Duration = Duration::from_secs(1); + +/// Budget for the launch-race and readiness phases. +const RECOVERY_TIMEOUT: Duration = Duration::from_secs(30); + +/// Delay between readiness polls. +const RECOVERY_POLL_INTERVAL: Duration = Duration::from_millis(25); + +/// Longest single health probe, so a discovery file rewritten while a +/// probe is failing is read again well before the readiness budget ends. +const HEALTH_PROBE_WINDOW: Duration = Duration::from_millis(250); + +/// Healthy-sidecar supervision cadence. +const SUPERVISION_INTERVAL: Duration = Duration::from_secs(5); + +/// First delay after a failed re-resolution or relaunch. +const SUPERVISION_BASE_DELAY: Duration = Duration::from_millis(250); + +/// Ceiling on repeated sidecar recovery attempts. +const SUPERVISION_MAX_DELAY: Duration = Duration::from_secs(30); + +/// Maximum designed supervisor shutdown latency. +const SUPERVISOR_SHUTDOWN_BUDGET: Duration = Duration::from_secs(3); + +/// What the boot decision concluded. +#[derive(Debug, PartialEq, Eq)] +enum GatewayPlan { + /// A live gateway discovery file exists. + Attach(GatewayDiscoveryFile), + /// No live file exists and an installed Gateway can be launched. + Launch(PathBuf), + /// Explicit configuration is the only available endpoint. + ConfigOnly, + /// No attachment path exists. + Fail, +} + +/// The result of a launch election, retaining the spawned pid only for the +/// branch that actually created a child. +#[derive(Debug)] +enum RecoveryLaunch { + /// A race winner had already published a live Gateway. + Attached(GatewayDiscoveryFile), + /// This process spawned a child and observed a gateway discovery file. + Launched { + child_pid: u32, + file: GatewayDiscoveryFile, + }, +} + +impl RecoveryLaunch { + /// Validates the discovered file and authenticates child ownership by exact pid. + fn authenticate( + self, + validate: impl FnOnce(GatewayDiscoveryFile) -> anyhow::Result, + ) -> anyhow::Result { + let (child_pid, file) = match self { + Self::Attached(file) => (None, file), + Self::Launched { child_pid, file } => (Some(child_pid), file), + }; + let validated = validate(file)?; + Ok(match child_pid { + Some(child_pid) => RecoveryCandidate::authenticate(child_pid, validated), + None => SidecarIdentity::Stable(validated), + }) + } +} + +/// A validated recovery process whose pid proves it is the child we spawned. +#[derive(Debug)] +pub(crate) struct RecoveryCandidate { + child_pid: u32, + validated: ValidatedConnection, + published: bool, +} + +impl RecoveryCandidate { + /// Claims cleanup authority only when validation names the spawned pid. + fn authenticate(child_pid: u32, validated: ValidatedConnection) -> SidecarIdentity { + if validated.pid() != child_pid { + return SidecarIdentity::Stable(validated); + } + SidecarIdentity::Candidate(Self { + child_pid, + validated, + published: false, + }) + } + + fn validated(&self) -> &ValidatedConnection { + &self.validated + } + + fn mark_published(&mut self) { + self.published = true; + } + + /// Shuts down the unpublished recovered child within the late-child + /// budget. + /// + /// This is the blocking, error-reporting path; `Drop` only signals on + /// a detached thread. The drop signal is disarmed either way: the + /// caller receives the outcome, so a failed delivery is reported here + /// rather than retried silently. + fn shutdown(mut self) -> Result<(), ShutdownError> { + if self.published { + return Ok(()); + } + debug_assert_eq!(self.child_pid, self.validated.pid()); + self.published = true; + let deadline = Instant::now() + LATE_CHILD_SHUTDOWN_BUDGET; + discovery::request_shutdown_before(&self.validated, deadline) + } +} + +impl Drop for RecoveryCandidate { + fn drop(&mut self) { + if self.published { + return; + } + debug_assert_eq!(self.child_pid, self.validated.pid()); + // Drop can neither block nor report: the bounded authenticated + // request runs on a detached thread, so a missed explicit + // `shutdown()` still signals the unpublished gateway process. + let validated = self.validated.clone(); + let signalled = thread::Builder::new() + .name("gateway-late-child-shutdown".to_owned()) + .spawn(move || { + let deadline = Instant::now() + LATE_CHILD_SHUTDOWN_BUDGET; + if let Err(error) = discovery::request_shutdown_before(&validated, deadline) { + // The detached signal has no error return channel, so + // diagnostics are the only place this cleanup failure + // can surface. + eprintln!("could not shut down an unpublished recovered gateway: {error}"); + } + }); + if let Err(error) = signalled { + eprintln!("could not signal an unpublished recovered gateway: {error}"); + } + } +} + +/// A validated local sidecar Gateway identity, distinguishing a child we +/// launched (which owns unpublished cleanup until disarmed) from an attached +/// sidecar. +#[derive(Debug)] +pub(crate) enum SidecarIdentity { + /// A local sidecar Gateway this process did not launch (or no longer owns). + Stable(ValidatedConnection), + /// A child launched by this process that owns unpublished cleanup. + Candidate(RecoveryCandidate), +} + +impl SidecarIdentity { + fn validated(&self) -> &ValidatedConnection { + match self { + Self::Stable(validated) => validated, + Self::Candidate(candidate) => candidate.validated(), + } + } +} + +/// One sidecar liveness observation. +enum SupervisionProbe { + /// Another process already published a live replacement. + Replacement(Identity), + /// No live local Gateway is currently discoverable. + Missing, +} + +/// A validated identity retained across supervision classifications. +trait SupervisedGatewayIdentity { + /// Whether both values prove the same process boot. + fn same_boot(&self, other: &Self) -> bool; + + /// Disarms cleanup after this identity becomes authoritative. + fn publication_succeeded(&mut self) {} + + /// Shuts down an unpublished owned child through the explicit, + /// error-reporting path. Identities that own no child do nothing. + fn shutdown_unpublished(self) + where + Self: Sized, + { + } +} + +impl SupervisedGatewayIdentity for SidecarIdentity { + fn same_boot(&self, other: &Self) -> bool { + self.validated().same_boot(other.validated()) + } + + fn publication_succeeded(&mut self) { + if let Self::Candidate(candidate) = self { + candidate.mark_published(); + } + } + + fn shutdown_unpublished(self) { + if let Self::Candidate(candidate) = self + && let Err(error) = candidate.shutdown() + { + eprintln!("could not shut down an unpublished recovered gateway: {error}"); + } + } +} + +/// The readiness wait's only source of time. +trait WaitClock { + /// The current instant. + fn now(&self) -> Instant; + + /// Pauses for `delay`, returning `true` when `cancellation` fires first. + fn pause(&self, delay: Duration, cancellation: &CancellationToken) -> bool; +} + +/// The monotonic clock and the token's own timed wait. +struct SystemClock; + +impl WaitClock for SystemClock { + fn now(&self) -> Instant { + Instant::now() + } + + fn pause(&self, delay: Duration, cancellation: &CancellationToken) -> bool { + cancellation.wait_timeout(delay) + } +} + +/// A one-shot latch shared between the supervisor and its stop/completion +/// waiters. +#[derive(Clone, Debug, Default)] +struct Signal { + state: Arc, +} + +#[derive(Debug, Default)] +struct SignalState { + set: Mutex, + wake: Condvar, +} + +impl Signal { + fn lock(&self) -> MutexGuard<'_, bool> { + self.state + .set + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + fn signal(&self) { + let mut set = self.lock(); + *set = true; + self.state.wake.notify_all(); + drop(set); + } + + fn wait(&self) { + let set = self.lock(); + drop( + self.state + .wake + .wait_while(set, |set| !*set) + .unwrap_or_else(PoisonError::into_inner), + ); + } + + fn wait_until(&self, deadline: Instant) -> bool { + let mut set = self.lock(); + loop { + if *set { + return true; + } + let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { + return false; + }; + if remaining.is_zero() { + return false; + } + let (next, timeout) = self + .state + .wake + .wait_timeout(set, remaining) + .unwrap_or_else(PoisonError::into_inner); + set = next; + if timeout.timed_out() && !*set { + return false; + } + } + } + + fn guard(&self) -> SignalGuard { + SignalGuard(self.clone()) + } +} + +struct SignalGuard(Signal); + +impl Drop for SignalGuard { + fn drop(&mut self) { + self.0.signal(); + } +} + +/// The running local-sidecar supervisor. +#[derive(Debug)] +pub(crate) struct GatewaySupervisor { + stop: Signal, + completion: Signal, + stop_bridge_completion: Signal, + thread: Option>, + stop_bridge: Option>, + publication: Option, + shutdown_budget: Duration, +} + +/// How bounded supervisor shutdown ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SupervisorShutdown { + /// The worker completed and joined normally. + Joined, + /// The worker completed but panicked. + Panicked, + /// The deadline elapsed, so the worker handle was detached. + Detached, +} + +impl GatewaySupervisor { + fn spawn_with_publication( + publication: GatewayUpdater, + supervise: impl FnOnce(CancellationToken) + Send + 'static, + ) -> anyhow::Result { + Self::spawn_inner(Some(publication), SUPERVISOR_SHUTDOWN_BUDGET, supervise) + } + + fn spawn_inner( + publication: Option, + shutdown_budget: Duration, + supervise: impl FnOnce(CancellationToken) + Send + 'static, + ) -> anyhow::Result { + let cancellation = CancellationToken::new(); + let stop = Signal::default(); + let worker_stop = stop.clone(); + let completion = Signal::default(); + let worker_completion = completion.clone(); + let stop_bridge_completion = Signal::default(); + let bridge_completion = stop_bridge_completion.clone(); + let bridge_cancellation = cancellation.clone(); + let stop_bridge = thread::Builder::new() + .name("gateway-supervisor-stop".to_owned()) + .spawn(move || { + let _completion = bridge_completion.guard(); + worker_stop.wait(); + bridge_cancellation.cancel(); + }) + .context("spawn the gateway supervisor stop bridge")?; + let thread = match thread::Builder::new() + .name("gateway-supervisor".to_owned()) + .spawn(move || { + let _completion = worker_completion.guard(); + supervise(cancellation); + }) { + Ok(thread) => thread, + Err(source) => { + stop.signal(); + let error = anyhow::Error::new(source).context("spawn the gateway supervisor"); + return match stop_bridge.join() { + Ok(()) => Err(error), + Err(_) => Err(error.context( + "the gateway supervisor stop bridge panicked during spawn rollback", + )), + }; + } + }; + Ok(Self { + stop, + completion, + stop_bridge_completion, + thread: Some(thread), + stop_bridge: Some(stop_bridge), + publication, + shutdown_budget, + }) + } + + fn begin_stop(&mut self) -> (Option>, Option>) { + if let Some(publication) = self.publication.as_ref() { + publication.close_publication(); + } + self.stop.signal(); + (self.thread.take(), self.stop_bridge.take()) + } + + /// Revokes publication, requests stop, and waits at most one deadline. + /// + /// This is the blocking, outcome-reporting path; `Drop` only signals + /// and detaches. + pub(crate) fn shutdown(mut self) -> SupervisorShutdown { + let deadline = Instant::now() + self.shutdown_budget; + let (Some(thread), Some(stop_bridge)) = self.begin_stop() else { + return SupervisorShutdown::Joined; + }; + if !self.completion.wait_until(deadline) + || !self.stop_bridge_completion.wait_until(deadline) + { + drop(thread); + drop(stop_bridge); + return SupervisorShutdown::Detached; + } + match (thread.join(), stop_bridge.join()) { + (Ok(()), Ok(())) => SupervisorShutdown::Joined, + (Err(_), _) | (_, Err(_)) => SupervisorShutdown::Panicked, + } + } +} + +impl Drop for GatewaySupervisor { + fn drop(&mut self) { + // `shutdown()` is the bounded, outcome-reporting path. Drop can + // neither wait nor report, so it revokes publication, signals the + // stop, and detaches both threads; the worker captures only owned + // state, so a detached thread finishes on its own. + let _ = self.begin_stop(); + } +} + +/// Connects the Gateway for boot, returning `Some` for a local sidecar and +/// `None` for an explicitly configured LAN Gateway. +/// +/// # Errors +/// Returns an error when no attachment path exists or launch fails. +pub(crate) fn ensure_gateway(config: &Config) -> anyhow::Result> { + let installed = installed_gateway()?; + let explicit = !config.gateway.base_url.is_empty(); + let Some(run_dir) = discovery::default_run_dir() else { + return if explicit { + Ok(None) + } else { + Err(no_gateway_error()) + }; + }; + match plan_gateway(&run_dir, installed, explicit, discovery::resolve) { + GatewayPlan::Attach(file) => ValidatedConnection::validate(file) + .map(|validated| Some(SidecarIdentity::Stable(validated))) + .context("validate the selected gateway process identity"), + GatewayPlan::ConfigOnly => Ok(None), + GatewayPlan::Fail => Err(no_gateway_error()), + GatewayPlan::Launch(exe) => { + if sibling_is_placeholder(&exe) { + return Err(placeholder_gateway_error(&exe)); + } + let recovery = launch_and_attach_cancellable(&run_dir, &exe, &CancellationToken::new()) + .context("launch the sidecar gateway")?; + recovery + .authenticate(|file| { + ValidatedConnection::validate(file) + .context("validate the launched gateway process identity") + }) + .context("launch the sidecar gateway") + .map(Some) + } + } +} + +/// Reconciles the desktop app's boot candidate with the identity the server +/// actually published, disarming launched-child cleanup only for an exact +/// match. +pub(crate) fn reconcile_publication( + sidecar: Option, + published: Option<&ValidatedConnection>, +) -> Option { + match (sidecar, published) { + (Some(SidecarIdentity::Candidate(mut candidate)), Some(published)) + if candidate.validated().same_boot(published) => + { + candidate.mark_published(); + Some(SidecarIdentity::Candidate(candidate)) + } + (_, Some(published)) => Some(SidecarIdentity::Stable(published.clone())), + (_, None) => None, + } +} + +/// Starts runtime supervision only for a gateway discovery file sidecar. +/// +/// # Errors +/// Returns an error when the supervisor cannot locate its runtime paths or +/// spawn its owned thread. +pub(crate) fn supervise( + sidecar: Option<&SidecarIdentity>, + updater: GatewayUpdater, +) -> anyhow::Result> { + let Some(initial) = sidecar.map(|identity| identity.validated().clone()) else { + return Ok(None); + }; + let run_dir = discovery::default_run_dir().context("locate the sidecar run directory")?; + let sibling = installed_gateway()?; + let supervisor_publication = updater.clone(); + GatewaySupervisor::spawn_with_publication(supervisor_publication, move |cancellation| { + run_supervision( + SidecarIdentity::Stable(initial), + |_, cancellation| match discovery::resolve_cancellable(&run_dir, cancellation) { + Ok(Resolution::Attach(file)) => { + match ValidatedConnection::validate_cancellable(file, cancellation) { + Ok(identity) => { + SupervisionProbe::Replacement(SidecarIdentity::Stable(identity)) + } + Err(error) => { + eprintln!("could not retain the replacement gateway identity: {error}"); + SupervisionProbe::Missing + } + } + } + Ok(_) | Err(SidecarError::Canceled) => SupervisionProbe::Missing, + Err(error) => { + eprintln!("could not re-resolve the local gateway: {error}"); + SupervisionProbe::Missing + } + }, + |cancellation| { + let exe = sibling.as_deref().context( + "the local gateway disappeared and no gateway executable is installed", + )?; + let recovery = launch_and_attach_cancellable(&run_dir, exe, cancellation)?; + validate_recovery(recovery, cancellation) + }, + |identity, cancellation| { + if cancellation.is_canceled() { + anyhow::bail!("gateway publication was canceled"); + } + if updater.publication_closed() { + anyhow::bail!("gateway publication is closed"); + } + if updater + .replace_sidecar_cancellable(identity.validated(), cancellation) + .context("publish the replacement gateway endpoint")? + { + Ok(()) + } else { + anyhow::bail!("gateway publication was canceled") + } + }, + |delay, cancellation| cancellation.wait_timeout(delay), + &cancellation, + ); + }) + .map(Some) +} + +/// Chooses attach, launch, configured fallback, or failure. +fn plan_gateway( + run_dir: &Path, + installed: Option, + explicit_config: bool, + resolve: fn(&Path) -> Result, +) -> GatewayPlan { + match resolve(run_dir) { + Ok(Resolution::Attach(file)) => return GatewayPlan::Attach(file), + Ok(_) => {} + Err(error) => { + eprintln!("could not resolve the gateway discovery file: {error}"); + } + } + match installed { + Some(exe) => GatewayPlan::Launch(exe), + None if explicit_config => GatewayPlan::ConfigOnly, + None => GatewayPlan::Fail, + } +} + +/// Locates the installed Gateway for the running Workshop: beside it on +/// Windows and in development, as the sibling `Runvil Gateway.app` on +/// macOS, and beside `Runvil.AppImage` on Linux, where Workshop runs from +/// the AppImage's mount. +/// +/// # Errors +/// Returns an error when the executable path cannot be read. +fn installed_gateway() -> anyhow::Result> { + let exe = env::current_exe().context("locate the executable")?; + let appimage = discovery::running_appimage( + &exe, + env::var_os("APPIMAGE").as_deref(), + env::var_os("APPDIR").as_deref(), + ); + Ok(discovery::installed_gateway(&exe, appimage.as_deref())) +} + +/// Whether the installed Gateway is a compile-only stub rather than an +/// executable. A real Gateway starts with `MZ` on Windows and something +/// other than this text everywhere else, so a byte-prefix compare is the +/// whole test. +fn sibling_is_placeholder(exe: &Path) -> bool { + let Ok(mut file) = File::open(exe) else { + return false; + }; + let mut prefix = [0_u8; STUB_PREFIX.len()]; + let Ok(read) = file.read(&mut prefix) else { + return false; + }; + &prefix[..read] == STUB_PREFIX.as_bytes() +} + +/// The failure for a stub sidecar, naming the file and the one command that +/// replaces it with a runnable Gateway. +fn placeholder_gateway_error(exe: &Path) -> anyhow::Error { + anyhow::anyhow!( + "the gateway beside this program is a compile-only stub, not an executable: {}; \ + run `node tools/fetch-gateway-sidecar.mjs` from the repository root to stage the \ + pinned Gateway release, then rebuild", + exe.display() + ) +} + +/// Builds the loud boot failure naming both supported remedies. +fn no_gateway_error() -> anyhow::Error { + anyhow::anyhow!( + "no gateway configured or running; install the Gateway component, which \ + puts runvil-gateway where Workshop looks for it (in a development tree, \ + build with `cargo workshop`, which places it beside Workshop), or set \ + gateway.base_url and gateway.api_key in workshop.toml to attach to \ + a gateway over the network" + ) +} + +#[cfg(windows)] +fn spawn_detached_windows_with(mut spawn: Spawn) -> io::Result +where + Spawn: FnMut(u32) -> io::Result, +{ + match spawn(WINDOWS_BREAKAWAY_CREATION_FLAGS) { + Err(error) if error.kind() == io::ErrorKind::PermissionDenied => { + // Hosted runners can forbid breakaway from their job object. + // https://github.com/actions/runner/issues/595 + spawn(WINDOWS_DETACHED_CREATION_FLAGS) + } + result => result, + } +} + +fn detached_command(exe: &Path) -> Command { + let mut command = Command::new(exe); + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + command +} + +/// Spawns the Gateway detached from the desktop app's lifetime. The reaper +/// thread records the child's exit status in `exit`, so a launch wait can +/// stop as soon as the child dies instead of running out its budget. +fn spawn_detached(exe: &Path, exit: Arc>) -> io::Result { + #[cfg(windows)] + let mut child = + spawn_detached_windows_with(|flags| detached_command(exe).creation_flags(flags).spawn())?; + #[cfg(unix)] + let mut child = { + let mut command = detached_command(exe); + command.process_group(0); + command.spawn()? + }; + #[cfg(not(any(windows, unix)))] + let mut child = detached_command(exe).spawn()?; + let child_pid = child.id(); + if let Err(error) = thread::Builder::new().spawn(move || { + if let Ok(status) = child.wait() { + let _ = exit.set(status); + } + }) { + eprintln!("could not spawn the gateway reaper thread; the child goes unreaped: {error}"); + } + Ok(child_pid) +} + +/// Settles and performs a cancellable launch. Boot passes a token that is +/// never canceled. +fn launch_and_attach_cancellable( + run_dir: &Path, + exe: &Path, + cancellation: &CancellationToken, +) -> anyhow::Result { + let exit = Arc::new(OnceLock::new()); + launch_and_attach_cancellable_with( + run_dir, + exe, + cancellation, + discovery::launch_or_attach_cancellable, + |exe, _| spawn_detached(exe, Arc::clone(&exit)), + |run_dir, timeout, cancellation| { + wait_for_launched_file_cancellable_with( + run_dir, + timeout, + cancellation, + &SystemClock, + discovery::wait_for_health_cancellable, + discovery::resolve_cancellable, + || exit.get().copied(), + ) + }, + ) +} + +/// Launch with each blocking phase injected. +fn launch_and_attach_cancellable_with( + run_dir: &Path, + exe: &Path, + cancellation: &CancellationToken, + settle: Settle, + spawn: Spawn, + wait: Wait, +) -> anyhow::Result +where + Settle: FnOnce(&Path, Duration, &CancellationToken) -> Result, + Spawn: FnOnce(&Path, &CancellationToken) -> io::Result, + Wait: FnOnce(&Path, Duration, &CancellationToken) -> anyhow::Result, +{ + match settle(run_dir, RECOVERY_TIMEOUT, cancellation) + .context("settle the gateway launch race")? + { + LaunchDecision::Attach(file) => { + if cancellation.is_canceled() { + anyhow::bail!("gateway attachment was canceled"); + } + Ok(RecoveryLaunch::Attached(file)) + } + LaunchDecision::Launch(lock) => { + let child_pid = cancellation + .run_if_active(|| { + if cancellation.is_canceled() { + anyhow::bail!("gateway launch was canceled"); + } + spawn(exe, cancellation).with_context(|| format!("spawn {}", exe.display())) + }) + .ok_or_else(|| anyhow::anyhow!("gateway launch was canceled"))??; + let file = wait(run_dir, RECOVERY_TIMEOUT, cancellation)?; + drop(lock); + Ok(RecoveryLaunch::Launched { child_pid, file }) + } + decision => anyhow::bail!("an unknown launch decision: {decision:?}"), + } +} + +/// Readiness wait with time, health, validation, and the launched child's +/// exit status injected. A failed probe does not end the wait; the budget +/// does, reporting the last probe error. A child that has exited ends the +/// wait at once when no discovery file exists, naming the gateway log. +fn wait_for_launched_file_cancellable_with( + run_dir: &Path, + timeout: Duration, + cancellation: &CancellationToken, + clock: &Clock, + mut health: Health, + mut resolve: Resolve, + mut exited: Exited, +) -> anyhow::Result +where + Clock: WaitClock, + Health: FnMut(&str, Duration, &CancellationToken) -> Result<(), HealthError>, + Resolve: FnMut(&Path, &CancellationToken) -> Result, + Exited: FnMut() -> Option, +{ + let canceled = || anyhow::anyhow!("the launched gateway wait was canceled"); + let ensure_active = || { + if cancellation.is_canceled() { + Err(canceled()) + } else { + Ok(()) + } + }; + let deadline = clock.now() + timeout; + let mut last_probe_error = None; + loop { + ensure_active()?; + // Sampled before the read: a launched gateway that hands off to a + // running owner exits only after the owner publishes, so the read + // below sees the owner's file. + let exit = exited(); + if let Ok(Some(file)) = GatewayDiscoveryFile::read(run_dir) { + let remaining = deadline.saturating_duration_since(clock.now()); + let url = format!("http://127.0.0.1:{}", file.port); + match health(&url, remaining.min(HEALTH_PROBE_WINDOW), cancellation) { + Ok(()) => { + ensure_active()?; + match resolve(run_dir, cancellation) { + Ok(Resolution::Attach(validated)) => { + ensure_active()?; + return Ok(validated); + } + Err(SidecarError::Canceled) => return Err(canceled()), + Ok(Resolution::Stale(reason)) => { + last_probe_error = + Some(anyhow::Error::new(reason).context( + "the launched gateway discovery file failed validation", + )); + } + Err(error) => { + last_probe_error = Some( + anyhow::Error::new(error) + .context("resolve the launched gateway discovery file"), + ); + } + Ok(_) => {} + } + } + Err(HealthError::Canceled) => { + return Err(canceled()); + } + Err(error) => { + last_probe_error = Some( + anyhow::Error::new(error) + .context("the launched gateway did not answer its health probe"), + ); + } + } + } else if let Some(status) = exit { + let state_dir = run_dir.parent().unwrap_or(run_dir); + anyhow::bail!( + "the launched gateway exited ({status}) without writing a gateway discovery \ + file; see the gateway log at {}", + discovery::gateway_log_path(state_dir).display() + ); + } + ensure_active()?; + if clock.now() >= deadline { + let failure = format!( + "the launched gateway wrote no validated gateway discovery file within {timeout:?}" + ); + return Err(match last_probe_error { + Some(error) => error.context(failure), + None => anyhow::anyhow!(failure), + }); + } + if clock.pause(RECOVERY_POLL_INTERVAL, cancellation) { + return Err(canceled()); + } + } +} + +/// Validates a recovery result and authenticates child ownership by exact pid. +fn validate_recovery( + recovery: RecoveryLaunch, + cancellation: &CancellationToken, +) -> anyhow::Result { + recovery.authenticate(|file| { + ValidatedConnection::validate_cancellable(file, cancellation) + .context("retain the recovered gateway identity") + }) +} + +/// Runs the supervision state machine with I/O injected for tests. +fn run_supervision( + mut current: Identity, + mut probe: Probe, + mut recover: Recover, + mut publish: Publish, + mut wait: Wait, + cancellation: &CancellationToken, +) where + Identity: SupervisedGatewayIdentity, + Probe: FnMut(&Identity, &CancellationToken) -> SupervisionProbe, + Recover: FnMut(&CancellationToken) -> Result, + Publish: FnMut(&Identity, &CancellationToken) -> Result<(), Error>, + Wait: FnMut(Duration, &CancellationToken) -> bool, + Error: fmt::Display, +{ + let mut retry_delay = SUPERVISION_BASE_DELAY; + loop { + if cancellation.is_canceled() { + return; + } + let observation = probe(¤t, cancellation); + if cancellation.is_canceled() { + return; + } + let candidate = match observation { + SupervisionProbe::Replacement(identity) if identity.same_boot(¤t) => { + retry_delay = SUPERVISION_BASE_DELAY; + if wait(SUPERVISION_INTERVAL, cancellation) { + return; + } + continue; + } + SupervisionProbe::Replacement(identity) => Some(identity), + SupervisionProbe::Missing => match recover(cancellation) { + Ok(_) if cancellation.is_canceled() => return, + Ok(identity) => Some(identity), + Err(error) => { + eprintln!("could not recover the local gateway: {error}"); + None + } + }, + }; + if let Some(mut identity) = candidate { + match publish(&identity, cancellation) { + Ok(()) => { + identity.publication_succeeded(); + if cancellation.is_canceled() { + return; + } + current = identity; + retry_delay = SUPERVISION_BASE_DELAY; + continue; + } + Err(error) => { + eprintln!("could not publish a replacement local gateway: {error}"); + // A recovered child this process launched stays + // unpublished, so it is shut down through the + // explicit, error-reporting path. + identity.shutdown_unpublished(); + } + } + } + if cancellation.is_canceled() || wait(retry_delay, cancellation) { + return; + } + retry_delay = retry_delay.saturating_mul(2).min(SUPERVISION_MAX_DELAY); + } +} #[cfg(test)] mod tests; diff --git a/crates/workshop/desktop/src/gateway/boot.rs b/crates/workshop/desktop/src/gateway/boot.rs deleted file mode 100644 index bd1e89e6..00000000 --- a/crates/workshop/desktop/src/gateway/boot.rs +++ /dev/null @@ -1,256 +0,0 @@ -//! Boot planning and detached Gateway spawn. - -use std::path::{Path, PathBuf}; -use std::process::ExitStatus; -use std::sync::{Arc, OnceLock}; - -use anyhow::Context as _; -use workshop_server_api::Config; -use workshop_server_api::discovery::{ - CancellationToken, GatewayDiscoveryFile, Resolution, SidecarError, ValidatedConnection, -}; - -use super::identity::GatewayAttachment; -use super::supervisor::{RecoveryCandidate, RecoveryOwnership, launch_and_attach_cancellable}; - -/// The Gateway executable's file name, which test fixtures plant. -#[cfg(all(test, windows))] -pub(super) const GATEWAY_EXE_NAME: &str = "runvil-gateway.exe"; -/// The Gateway executable's file name, which test fixtures plant. -#[cfg(all(test, not(windows)))] -pub(super) const GATEWAY_EXE_NAME: &str = "runvil-gateway"; - -#[cfg(windows)] -const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000; -#[cfg(windows)] -const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; -#[cfg(windows)] -const DETACHED_PROCESS: u32 = 0x0000_0008; -#[cfg(windows)] -const WINDOWS_DETACHED_CREATION_FLAGS: u32 = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS; -#[cfg(windows)] -const WINDOWS_BREAKAWAY_CREATION_FLAGS: u32 = - CREATE_BREAKAWAY_FROM_JOB | WINDOWS_DETACHED_CREATION_FLAGS; - -/// What the boot decision concluded. -#[derive(Debug, PartialEq, Eq)] -pub(super) enum GatewayPlan { - /// A live gateway discovery file exists. - Attach(GatewayDiscoveryFile), - /// No live file exists and an installed Gateway can be launched. - Launch(PathBuf), - /// Explicit configuration is the only available endpoint. - ConfigOnly, - /// No attachment path exists. - Fail, -} - -/// The result of a launch election, retaining the spawned pid only for the -/// branch that actually created a child. -#[derive(Debug)] -pub(super) enum RecoveryLaunch { - /// A race winner had already published a live Gateway. - Attached(GatewayDiscoveryFile), - /// This process spawned a child and observed a gateway discovery file. - Launched { - child_pid: u32, - file: GatewayDiscoveryFile, - }, -} - -/// Connects the Gateway for boot. -/// -/// # Errors -/// Returns an error when no attachment path exists or launch fails. -pub(crate) fn ensure_gateway(config: &Config) -> anyhow::Result { - let installed = installed_gateway()?; - let explicit = !config.gateway.base_url.is_empty(); - let Some(run_dir) = workshop_server_api::discovery::default_run_dir() else { - return if explicit { - Ok(GatewayAttachment::Config) - } else { - Err(no_gateway_error()) - }; - }; - match plan_gateway( - &run_dir, - installed, - explicit, - workshop_server_api::discovery::resolve, - ) { - GatewayPlan::Attach(file) => validated_attachment(file), - GatewayPlan::ConfigOnly => Ok(GatewayAttachment::Config), - GatewayPlan::Fail => Err(no_gateway_error()), - GatewayPlan::Launch(exe) => { - if sibling_is_placeholder(&exe) { - return Err(placeholder_gateway_error(&exe)); - } - launch_and_attach_cancellable(&run_dir, &exe, &CancellationToken::new()) - .and_then(validated_recovery_attachment) - .context("launch the sidecar gateway") - } - } -} - -/// Retains the selected process proof instead of reducing it to file fields. -fn validated_attachment(file: GatewayDiscoveryFile) -> anyhow::Result { - ValidatedConnection::validate(file) - .map(GatewayAttachment::Sidecar) - .context("validate the selected gateway process identity") -} - -fn validated_recovery_attachment(recovery: RecoveryLaunch) -> anyhow::Result { - match recovery { - RecoveryLaunch::Attached(file) => validated_attachment(file), - RecoveryLaunch::Launched { child_pid, file } => { - let validated = ValidatedConnection::validate(file) - .context("validate the launched gateway process identity")?; - Ok( - match RecoveryCandidate::authenticate(child_pid, validated) { - RecoveryOwnership::Owned(candidate) => GatewayAttachment::Launched(candidate), - RecoveryOwnership::Unowned(unowned) => GatewayAttachment::Sidecar(unowned), - }, - ) - } - } -} - -/// Chooses attach, launch, configured fallback, or failure. -pub(super) fn plan_gateway( - run_dir: &Path, - installed: Option, - explicit_config: bool, - resolve: fn(&Path) -> Result, -) -> GatewayPlan { - match resolve(run_dir) { - Ok(Resolution::Attach(file)) => return GatewayPlan::Attach(file), - Ok(_) => {} - Err(error) => { - eprintln!("could not resolve the gateway discovery file: {error}"); - } - } - match installed { - Some(exe) => GatewayPlan::Launch(exe), - None if explicit_config => GatewayPlan::ConfigOnly, - None => GatewayPlan::Fail, - } -} - -/// Locates the installed Gateway for the running Workshop: beside it on -/// Windows and in development, as the sibling `Runvil Gateway.app` on -/// macOS, and beside `Runvil.AppImage` on Linux, where Workshop runs from -/// the AppImage's mount. -/// -/// # Errors -/// Returns an error when the executable path cannot be read. -pub(super) fn installed_gateway() -> anyhow::Result> { - let exe = std::env::current_exe().context("locate the executable")?; - let appimage = workshop_server_api::discovery::running_appimage( - &exe, - std::env::var_os("APPIMAGE").as_deref(), - std::env::var_os("APPDIR").as_deref(), - ); - Ok(workshop_server_api::discovery::installed_gateway( - &exe, - appimage.as_deref(), - )) -} - -/// The text `tools/fetch-gateway-sidecar.mjs --stub` writes, and the only -/// content a file may hold and still be called a Gateway. Checked before a -/// launch because Windows answers a text file with "This version of %1 is -/// not compatible with the version of Windows you're running" and no clue -/// which file was at fault. -const STUB_PREFIX: &str = "This is a placeholder staged by"; - -/// Whether the installed Gateway is a compile-only stub rather than an -/// executable. A real Gateway starts with `MZ` on Windows and something -/// other than this text everywhere else, so a byte-prefix compare is the -/// whole test. -pub(super) fn sibling_is_placeholder(exe: &Path) -> bool { - use std::io::Read as _; - let Ok(mut file) = std::fs::File::open(exe) else { - return false; - }; - let mut prefix = vec![0_u8; STUB_PREFIX.len()]; - let Ok(read) = file.read(&mut prefix) else { - return false; - }; - prefix.truncate(read); - prefix == STUB_PREFIX.as_bytes() -} - -/// The failure for a stub sidecar, naming the file and the one command that -/// replaces it with a runnable Gateway. -pub(super) fn placeholder_gateway_error(exe: &Path) -> anyhow::Error { - anyhow::anyhow!( - "the gateway beside this program is a compile-only stub, not an executable: {}; \ - run `node tools/fetch-gateway-sidecar.mjs` from the repository root to stage the \ - pinned Gateway release, then rebuild", - exe.display() - ) -} - -/// Builds the loud boot failure naming both supported remedies. -pub(super) fn no_gateway_error() -> anyhow::Error { - anyhow::anyhow!( - "no gateway configured or running; install the Gateway component, which \ - puts runvil-gateway where Workshop looks for it (in a development tree, \ - build with `cargo workshop`, which places it beside Workshop), or set \ - gateway.base_url and gateway.api_key in workshop.toml to attach to \ - a gateway over the network" - ) -} - -#[cfg(windows)] -pub(super) fn spawn_detached_windows_with(mut spawn: Spawn) -> std::io::Result -where - Spawn: FnMut(u32) -> std::io::Result, -{ - match spawn(WINDOWS_BREAKAWAY_CREATION_FLAGS) { - Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { - // Hosted runners can forbid breakaway from their job object. - // https://github.com/actions/runner/issues/595 - spawn(WINDOWS_DETACHED_CREATION_FLAGS) - } - result => result, - } -} - -fn detached_command(exe: &Path) -> std::process::Command { - let mut command = std::process::Command::new(exe); - command - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()); - command -} - -/// Spawns the Gateway detached from the desktop app's lifetime. The reaper -/// thread records the child's exit status in `exit`, so a launch wait can -/// stop as soon as the child dies instead of running out its budget. -pub(super) fn spawn_detached(exe: &Path, exit: Arc>) -> std::io::Result { - #[cfg(windows)] - let mut child = spawn_detached_windows_with(|flags| { - use std::os::windows::process::CommandExt as _; - detached_command(exe).creation_flags(flags).spawn() - })?; - #[cfg(unix)] - let mut child = { - use std::os::unix::process::CommandExt as _; - let mut command = detached_command(exe); - command.process_group(0); - command.spawn()? - }; - #[cfg(not(any(windows, unix)))] - let mut child = detached_command(exe).spawn()?; - let child_pid = child.id(); - if let Err(error) = std::thread::Builder::new().spawn(move || { - if let Ok(status) = child.wait() { - let _ = exit.set(status); - } - }) { - eprintln!("could not spawn the gateway reaper thread; the child goes unreaped: {error}"); - } - Ok(child_pid) -} diff --git a/crates/workshop/desktop/src/gateway/identity.rs b/crates/workshop/desktop/src/gateway/identity.rs deleted file mode 100644 index 57e889ac..00000000 --- a/crates/workshop/desktop/src/gateway/identity.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! Local Gateway attachment and validated process identity. - -use workshop_server_api::discovery::ValidatedConnection; - -use super::supervisor::RecoveryCandidate; - -/// How boot connected the Gateway. -#[derive(Debug)] -pub(crate) enum GatewayAttachment { - /// A local sidecar Gateway the desktop app attached to. - Sidecar(ValidatedConnection), - /// A child launched by this boot that has not yet entered server state. - Launched(RecoveryCandidate), - /// An explicit-config Gateway that the desktop app does not own. - Config, -} - -impl GatewayAttachment { - /// Returns the validated sidecar identity, when the Gateway is local. - pub(crate) fn sidecar_identity(&self) -> Option<&ValidatedConnection> { - match self { - Self::Sidecar(identity) => Some(identity), - Self::Launched(candidate) => Some(candidate.validated()), - Self::Config => None, - } - } - - /// Reconciles the desktop app's candidate with the identity the server actually - /// published, disarming launched-child cleanup only for an exact match. - pub(crate) fn reconcile_publication(self, published: Option) -> Self { - match (self, published) { - (Self::Launched(mut candidate), Some(published)) - if candidate.validated().same_boot(&published) => - { - candidate.mark_published(); - Self::Launched(candidate) - } - (_, Some(published)) => Self::Sidecar(published), - (_, None) => Self::Config, - } - } -} - -/// Whether two capabilities prove the same Gateway process boot. -pub(super) fn same_gateway_identity( - left: &ValidatedConnection, - right: &ValidatedConnection, -) -> bool { - left.same_boot(right) -} diff --git a/crates/workshop/desktop/src/gateway/supervisor.rs b/crates/workshop/desktop/src/gateway/supervisor.rs deleted file mode 100644 index 3264b162..00000000 --- a/crates/workshop/desktop/src/gateway/supervisor.rs +++ /dev/null @@ -1,232 +0,0 @@ -//! Continuous local Gateway supervision and recovery. - -use std::time::Duration; - -use anyhow::Context as _; -use workshop_server_api::discovery::{ - CancellationToken, Resolution, SidecarError, ValidatedConnection, -}; - -use super::boot; -use super::identity::GatewayAttachment; - -mod launch; -mod lifecycle; -mod recovery; -mod signals; - -#[cfg(test)] -pub(super) use launch::{ - RECOVERY_POLL_INTERVAL, SystemClock, WaitClock, launch_and_attach_cancellable_with, - run_effect_if_active, wait_for_launched_file_cancellable_with, -}; -#[cfg(test)] -pub(super) use lifecycle::SUPERVISOR_SHUTDOWN_BUDGET; -pub(crate) use lifecycle::{GatewaySupervisor, SupervisorShutdown}; -use recovery::RecoveryIdentity; -pub(in crate::gateway) use recovery::{RecoveryCandidate, RecoveryOwnership}; - -pub(super) use launch::launch_and_attach_cancellable; - -/// Healthy-sidecar supervision cadence. -const SUPERVISION_INTERVAL: Duration = Duration::from_secs(5); - -/// First delay after a failed re-resolution or relaunch. -const SUPERVISION_BASE_DELAY: Duration = Duration::from_millis(250); - -/// Ceiling on repeated sidecar recovery attempts. -pub(super) const SUPERVISION_MAX_DELAY: Duration = Duration::from_secs(30); - -/// One sidecar liveness observation. -pub(super) enum SupervisionProbe { - /// Another process already published a live replacement. - Replacement(Identity), - /// No live local Gateway is currently discoverable. - Missing, -} - -/// A validated identity retained across supervision classifications. -pub(super) trait SupervisedGatewayIdentity { - /// Whether both values prove the same process boot. - fn same_boot(&self, other: &Self) -> bool; - - /// Disarms cleanup after this identity becomes authoritative. - fn publication_succeeded(&mut self) {} - - /// Shuts down an unpublished owned child through the explicit, - /// error-reporting path. Identities that own no child do nothing. - fn shutdown_unpublished(self) - where - Self: Sized, - { - } -} - -/// Starts runtime supervision only for a gateway discovery file sidecar. -/// -/// # Errors -/// Returns an error when the supervisor cannot locate its runtime paths or -/// spawn its owned thread. -pub(crate) fn supervise( - attachment: &GatewayAttachment, - updater: workshop_server_api::GatewayUpdater, -) -> anyhow::Result> { - let Some(initial) = attachment.sidecar_identity().cloned() else { - return Ok(None); - }; - let run_dir = workshop_server_api::discovery::default_run_dir() - .context("locate the sidecar run directory")?; - let sibling = boot::installed_gateway()?; - let supervisor_publication = updater.clone(); - GatewaySupervisor::spawn_with_publication(supervisor_publication, move |cancellation| { - run_supervision( - RecoveryIdentity::Stable(initial), - |_, cancellation| match workshop_server_api::discovery::resolve_cancellable( - &run_dir, - cancellation, - ) { - Ok(Resolution::Attach(file)) => { - match ValidatedConnection::validate_cancellable(file, cancellation) { - Ok(identity) => { - SupervisionProbe::Replacement(RecoveryIdentity::Stable(identity)) - } - Err(error) => { - eprintln!("could not retain the replacement gateway identity: {error}"); - SupervisionProbe::Missing - } - } - } - Ok(_) | Err(SidecarError::Canceled) => SupervisionProbe::Missing, - Err(error) => { - eprintln!("could not re-resolve the local gateway: {error}"); - SupervisionProbe::Missing - } - }, - |cancellation| { - let exe = sibling.as_deref().context( - "the local gateway disappeared and no gateway executable is installed", - )?; - let recovery = launch_and_attach_cancellable(&run_dir, exe, cancellation)?; - validate_recovery(recovery, cancellation) - }, - |identity, cancellation| { - if cancellation.is_canceled() { - anyhow::bail!("gateway publication was canceled"); - } - if updater.publication_closed() { - anyhow::bail!("gateway publication is closed"); - } - if updater - .replace_sidecar_cancellable(identity.validated(), cancellation) - .context("publish the replacement gateway endpoint")? - { - Ok(()) - } else { - anyhow::bail!("gateway publication was canceled") - } - }, - |delay, cancellation| cancellation.wait_timeout(delay), - &cancellation, - ); - }) - .map(Some) -} - -/// Validates a recovery result and authenticates child ownership by exact pid. -pub(super) fn validate_recovery( - recovery: boot::RecoveryLaunch, - cancellation: &CancellationToken, -) -> anyhow::Result { - let (child_pid, file) = match recovery { - boot::RecoveryLaunch::Attached(file) => (None, file), - boot::RecoveryLaunch::Launched { child_pid, file } => (Some(child_pid), file), - }; - let validated = ValidatedConnection::validate_cancellable(file, cancellation) - .context("retain the recovered gateway identity")?; - Ok(match child_pid { - Some(child_pid) => match RecoveryCandidate::authenticate(child_pid, validated) { - RecoveryOwnership::Owned(candidate) => RecoveryIdentity::Candidate(candidate), - RecoveryOwnership::Unowned(unowned) => RecoveryIdentity::Stable(unowned), - }, - None => RecoveryIdentity::Stable(validated), - }) -} - -/// Runs the supervision state machine with I/O injected for tests. -pub(super) fn run_supervision( - mut current: Identity, - mut probe: Probe, - mut recover: Recover, - mut publish: Publish, - mut wait: Wait, - cancellation: &CancellationToken, -) where - Identity: SupervisedGatewayIdentity, - Probe: FnMut(&Identity, &CancellationToken) -> SupervisionProbe, - Recover: FnMut(&CancellationToken) -> Result, - Publish: FnMut(&Identity, &CancellationToken) -> Result<(), Error>, - Wait: FnMut(Duration, &CancellationToken) -> bool, - Error: std::fmt::Display, -{ - let mut retry_delay = SUPERVISION_BASE_DELAY; - loop { - if cancellation.is_canceled() { - return; - } - let observation = probe(¤t, cancellation); - if cancellation.is_canceled() { - return; - } - match observation { - SupervisionProbe::Replacement(identity) if identity.same_boot(¤t) => { - retry_delay = SUPERVISION_BASE_DELAY; - if wait(SUPERVISION_INTERVAL, cancellation) { - return; - } - continue; - } - SupervisionProbe::Replacement(mut identity) => match publish(&identity, cancellation) { - Ok(()) => { - identity.publication_succeeded(); - if cancellation.is_canceled() { - return; - } - current = identity; - retry_delay = SUPERVISION_BASE_DELAY; - continue; - } - Err(error) => { - eprintln!("could not publish a replacement local gateway: {error}"); - } - }, - SupervisionProbe::Missing => match recover(cancellation) { - Ok(_) if cancellation.is_canceled() => return, - Ok(mut identity) => match publish(&identity, cancellation) { - Ok(()) => { - identity.publication_succeeded(); - if cancellation.is_canceled() { - return; - } - current = identity; - retry_delay = SUPERVISION_BASE_DELAY; - continue; - } - Err(error) => { - eprintln!("could not publish a replacement local gateway: {error}"); - // A recovered child this process launched stays - // unpublished, so it is shut down through the - // explicit, error-reporting path. - identity.shutdown_unpublished(); - } - }, - Err(error) => { - eprintln!("could not recover the local gateway: {error}"); - } - }, - } - if cancellation.is_canceled() || wait(retry_delay, cancellation) { - return; - } - retry_delay = retry_delay.saturating_mul(2).min(SUPERVISION_MAX_DELAY); - } -} diff --git a/crates/workshop/desktop/src/gateway/supervisor/launch.rs b/crates/workshop/desktop/src/gateway/supervisor/launch.rs deleted file mode 100644 index ffe36562..00000000 --- a/crates/workshop/desktop/src/gateway/supervisor/launch.rs +++ /dev/null @@ -1,237 +0,0 @@ -//! Cancellable launch and readiness wait, shared by boot and recovery. - -use std::path::Path; -use std::process::ExitStatus; -use std::sync::{Arc, OnceLock}; -use std::time::{Duration, Instant}; - -use anyhow::Context as _; -use workshop_server_api::discovery::{ - CancellationToken, GatewayDiscoveryFile, LaunchDecision, Resolution, SidecarError, -}; - -use super::boot; - -/// Budget for the launch-race and readiness phases. -const RECOVERY_TIMEOUT: Duration = Duration::from_secs(30); - -/// Delay between readiness polls. -pub(in crate::gateway) const RECOVERY_POLL_INTERVAL: Duration = Duration::from_millis(25); - -/// Longest single health probe, so a discovery file rewritten while a -/// probe is failing is read again well before the readiness budget ends. -const HEALTH_PROBE_WINDOW: Duration = Duration::from_millis(250); - -/// The readiness wait's only source of time. -pub(in crate::gateway) trait WaitClock { - /// The current instant. - fn now(&self) -> Instant; - - /// Pauses for `delay`, returning `true` when `cancellation` fires first. - fn pause(&self, delay: Duration, cancellation: &CancellationToken) -> bool; -} - -/// The monotonic clock and the token's own timed wait. -pub(in crate::gateway) struct SystemClock; - -impl WaitClock for SystemClock { - fn now(&self) -> Instant { - Instant::now() - } - - fn pause(&self, delay: Duration, cancellation: &CancellationToken) -> bool { - cancellation.wait_timeout(delay) - } -} - -/// Settles and performs a cancellable launch. Boot passes a token that is -/// never canceled. -pub(in crate::gateway) fn launch_and_attach_cancellable( - run_dir: &Path, - exe: &Path, - cancellation: &CancellationToken, -) -> anyhow::Result { - let exit = Arc::new(OnceLock::new()); - launch_and_attach_cancellable_with( - run_dir, - exe, - cancellation, - workshop_server_api::discovery::launch_or_attach_cancellable, - |exe, _| boot::spawn_detached(exe, Arc::clone(&exit)), - |run_dir, timeout, cancellation| { - wait_for_launched_file_cancellable(run_dir, timeout, cancellation, || { - exit.get().copied() - }) - }, - ) -} - -/// Launch with each blocking phase injected. -pub(in crate::gateway) fn launch_and_attach_cancellable_with( - run_dir: &Path, - exe: &Path, - cancellation: &CancellationToken, - settle: Settle, - spawn: Spawn, - wait: Wait, -) -> anyhow::Result -where - Settle: FnOnce(&Path, Duration, &CancellationToken) -> Result, - Spawn: FnOnce(&Path, &CancellationToken) -> std::io::Result, - Wait: FnOnce(&Path, Duration, &CancellationToken) -> anyhow::Result, -{ - match settle(run_dir, RECOVERY_TIMEOUT, cancellation) - .context("settle the gateway launch race")? - { - LaunchDecision::Attach(file) => { - if cancellation.is_canceled() { - anyhow::bail!("gateway attachment was canceled"); - } - Ok(boot::RecoveryLaunch::Attached(file)) - } - LaunchDecision::Launch(lock) => { - let child_pid = run_effect_if_active(cancellation, "gateway launch", |cancellation| { - if cancellation.is_canceled() { - anyhow::bail!("gateway launch was canceled"); - } - spawn(exe, cancellation).with_context(|| format!("spawn {}", exe.display())) - })?; - let file = wait(run_dir, RECOVERY_TIMEOUT, cancellation)?; - drop(lock); - Ok(boot::RecoveryLaunch::Launched { child_pid, file }) - } - decision => anyhow::bail!("an unknown launch decision: {decision:?}"), - } -} - -/// Linearizes one externally visible recovery effect with cancellation. -pub(in crate::gateway) fn run_effect_if_active( - cancellation: &CancellationToken, - phase: &'static str, - operation: impl FnOnce(&CancellationToken) -> anyhow::Result, -) -> anyhow::Result { - match cancellation.run_if_active(|| operation(cancellation)) { - Some(result) => result, - None => anyhow::bail!("{phase} was canceled"), - } -} - -/// Waits for a launched Gateway with production probes. -fn wait_for_launched_file_cancellable( - run_dir: &Path, - timeout: Duration, - cancellation: &CancellationToken, - exited: impl FnMut() -> Option, -) -> anyhow::Result { - wait_for_launched_file_cancellable_with( - run_dir, - timeout, - cancellation, - &SystemClock, - workshop_server_api::discovery::wait_for_health_cancellable, - workshop_server_api::discovery::resolve_cancellable, - exited, - ) -} - -/// Readiness wait with time, health, validation, and the launched child's -/// exit status injected. A failed probe does not end the wait; the budget -/// does, reporting the last probe error. A child that has exited ends the -/// wait at once when no discovery file exists, naming the gateway log. -pub(in crate::gateway) fn wait_for_launched_file_cancellable_with( - run_dir: &Path, - timeout: Duration, - cancellation: &CancellationToken, - clock: &Clock, - mut health: Health, - mut resolve: Resolve, - mut exited: Exited, -) -> anyhow::Result -where - Clock: WaitClock, - Health: FnMut( - &str, - Duration, - &CancellationToken, - ) -> Result<(), workshop_server_api::discovery::HealthError>, - Resolve: FnMut(&Path, &CancellationToken) -> Result, - Exited: FnMut() -> Option, -{ - let deadline = clock.now() + timeout; - let mut last_probe_error = None; - loop { - if cancellation.is_canceled() { - anyhow::bail!("the launched gateway wait was canceled"); - } - // Sampled before the read: a launched gateway that hands off to a - // running owner exits only after the owner publishes, so the read - // below sees the owner's file. - let exit = exited(); - if let Ok(Some(file)) = GatewayDiscoveryFile::read(run_dir) { - let remaining = deadline.saturating_duration_since(clock.now()); - let url = format!("http://127.0.0.1:{}", file.port); - match health(&url, remaining.min(HEALTH_PROBE_WINDOW), cancellation) { - Ok(()) => { - if cancellation.is_canceled() { - anyhow::bail!("the launched gateway wait was canceled"); - } - match resolve(run_dir, cancellation) { - Ok(Resolution::Attach(validated)) => { - if cancellation.is_canceled() { - anyhow::bail!("the launched gateway wait was canceled"); - } - return Ok(validated); - } - Err(SidecarError::Canceled) => { - anyhow::bail!("the launched gateway wait was canceled"); - } - Ok(Resolution::Stale(reason)) => { - last_probe_error = - Some(anyhow::Error::new(reason).context( - "the launched gateway discovery file failed validation", - )); - } - Err(error) => { - last_probe_error = Some( - anyhow::Error::new(error) - .context("resolve the launched gateway discovery file"), - ); - } - Ok(_) => {} - } - } - Err(workshop_server_api::discovery::HealthError::Canceled) => { - anyhow::bail!("the launched gateway wait was canceled"); - } - Err(error) => { - last_probe_error = Some( - anyhow::Error::new(error) - .context("the launched gateway did not answer its health probe"), - ); - } - } - } else if let Some(status) = exit { - let state_dir = run_dir.parent().unwrap_or(run_dir); - anyhow::bail!( - "the launched gateway exited ({status}) without writing a gateway discovery \ - file; see the gateway log at {}", - workshop_server_api::discovery::gateway_log_path(state_dir).display() - ); - } - if cancellation.is_canceled() { - anyhow::bail!("the launched gateway wait was canceled"); - } - if clock.now() >= deadline { - let failure = format!( - "the launched gateway wrote no validated gateway discovery file within {timeout:?}" - ); - return Err(match last_probe_error { - Some(error) => error.context(failure), - None => anyhow::anyhow!(failure), - }); - } - if clock.pause(RECOVERY_POLL_INTERVAL, cancellation) { - anyhow::bail!("the launched gateway wait was canceled"); - } - } -} diff --git a/crates/workshop/desktop/src/gateway/supervisor/lifecycle.rs b/crates/workshop/desktop/src/gateway/supervisor/lifecycle.rs deleted file mode 100644 index 6eb41e47..00000000 --- a/crates/workshop/desktop/src/gateway/supervisor/lifecycle.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! Supervisor thread lifecycle and bounded shutdown. - -use std::time::{Duration, Instant}; - -use anyhow::Context as _; -use workshop_server_api::discovery::CancellationToken; - -use super::signals::{Completion, StopSignal}; - -/// Maximum designed supervisor shutdown latency. -pub(in crate::gateway) const SUPERVISOR_SHUTDOWN_BUDGET: Duration = Duration::from_secs(3); - -/// The running local-sidecar supervisor. -#[derive(Debug)] -pub(crate) struct GatewaySupervisor { - stop: StopSignal, - completion: Completion, - stop_bridge_completion: Completion, - thread: Option>, - stop_bridge: Option>, - publication: Option, - shutdown_budget: Duration, -} - -/// How bounded supervisor shutdown ended. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum SupervisorShutdown { - /// The worker completed and joined normally. - Joined, - /// The worker completed but panicked. - Panicked, - /// The deadline elapsed, so the worker handle was detached. - Detached, -} - -impl GatewaySupervisor { - /// Spawns one owned supervisor thread. - #[cfg(test)] - pub(in crate::gateway) fn spawn( - supervise: impl FnOnce(CancellationToken) + Send + 'static, - ) -> anyhow::Result { - Self::spawn_inner(None, SUPERVISOR_SHUTDOWN_BUDGET, supervise) - } - - pub(in crate::gateway) fn spawn_with_publication( - publication: workshop_server_api::GatewayUpdater, - supervise: impl FnOnce(CancellationToken) + Send + 'static, - ) -> anyhow::Result { - Self::spawn_inner(Some(publication), SUPERVISOR_SHUTDOWN_BUDGET, supervise) - } - - #[cfg(test)] - pub(in crate::gateway) fn spawn_with_budget( - shutdown_budget: Duration, - supervise: impl FnOnce(CancellationToken) + Send + 'static, - ) -> anyhow::Result { - Self::spawn_inner(None, shutdown_budget, supervise) - } - - fn spawn_inner( - publication: Option, - shutdown_budget: Duration, - supervise: impl FnOnce(CancellationToken) + Send + 'static, - ) -> anyhow::Result { - let cancellation = CancellationToken::new(); - let stop = StopSignal::default(); - let worker_stop = stop.clone(); - let completion = Completion::default(); - let worker_completion = completion.clone(); - let stop_bridge_completion = Completion::default(); - let bridge_completion = stop_bridge_completion.clone(); - let bridge_cancellation = cancellation.clone(); - let stop_bridge = std::thread::Builder::new() - .name("gateway-supervisor-stop".to_owned()) - .spawn(move || { - let _completion = bridge_completion.guard(); - worker_stop.wait(); - bridge_cancellation.cancel(); - }) - .context("spawn the gateway supervisor stop bridge")?; - let thread = match std::thread::Builder::new() - .name("gateway-supervisor".to_owned()) - .spawn(move || { - let _completion = worker_completion.guard(); - supervise(cancellation); - }) { - Ok(thread) => thread, - Err(source) => { - stop.signal(); - let error = anyhow::Error::new(source).context("spawn the gateway supervisor"); - return match stop_bridge.join() { - Ok(()) => Err(error), - Err(_) => Err(error.context( - "the gateway supervisor stop bridge panicked during spawn rollback", - )), - }; - } - }; - Ok(Self { - stop, - completion, - stop_bridge_completion, - thread: Some(thread), - stop_bridge: Some(stop_bridge), - publication, - shutdown_budget, - }) - } - - /// Revokes publication, requests stop, and waits at most one deadline. - /// - /// This is the blocking, outcome-reporting path; `Drop` only signals - /// and detaches. - pub(crate) fn shutdown(mut self) -> SupervisorShutdown { - self.stop_and_join() - } - - fn stop_and_join(&mut self) -> SupervisorShutdown { - let deadline = Instant::now() + self.shutdown_budget; - if let Some(publication) = self.publication.as_ref() { - publication.close_publication(); - } - self.stop.signal(); - let thread = self.thread.take(); - let stop_bridge = self.stop_bridge.take(); - let (Some(thread), Some(stop_bridge)) = (thread, stop_bridge) else { - return SupervisorShutdown::Joined; - }; - if !self.completion.wait_until(deadline) - || !self.stop_bridge_completion.wait_until(deadline) - { - drop(thread); - drop(stop_bridge); - return SupervisorShutdown::Detached; - } - match (thread.join(), stop_bridge.join()) { - (Ok(()), Ok(())) => SupervisorShutdown::Joined, - (Err(_), _) | (_, Err(_)) => SupervisorShutdown::Panicked, - } - } - - #[cfg(test)] - pub(in crate::gateway) fn completion_waker_for_test(&self) -> impl Fn() + Send + 'static { - let completion = self.completion.clone(); - move || completion.wake() - } -} - -impl Drop for GatewaySupervisor { - fn drop(&mut self) { - // `shutdown()` is the bounded, outcome-reporting path. Drop can - // neither wait nor report, so it revokes publication, signals the - // stop, and detaches both threads; the worker captures only owned - // state, so a detached thread finishes on its own. - if let Some(publication) = self.publication.as_ref() { - publication.close_publication(); - } - self.stop.signal(); - drop(self.thread.take()); - drop(self.stop_bridge.take()); - } -} diff --git a/crates/workshop/desktop/src/gateway/supervisor/recovery.rs b/crates/workshop/desktop/src/gateway/supervisor/recovery.rs deleted file mode 100644 index 609b81a2..00000000 --- a/crates/workshop/desktop/src/gateway/supervisor/recovery.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Recovery-candidate ownership and identity classification. - -use std::time::{Duration, Instant}; - -use workshop_server_api::discovery::{ShutdownError, ValidatedConnection}; - -use super::super::identity::same_gateway_identity; -use super::SupervisedGatewayIdentity; - -/// Separate bound for authenticated cleanup of an unpublished owned child. -const LATE_CHILD_SHUTDOWN_BUDGET: Duration = Duration::from_secs(1); - -/// A validated recovery process whose pid proves it is the child we spawned. -#[derive(Debug)] -pub(crate) struct RecoveryCandidate { - child_pid: u32, - validated: ValidatedConnection, - published: bool, -} - -pub(in crate::gateway) enum RecoveryOwnership { - Owned(RecoveryCandidate), - Unowned(ValidatedConnection), -} - -impl RecoveryCandidate { - /// Claims cleanup authority only when validation names the spawned pid. - pub(in crate::gateway) fn authenticate( - child_pid: u32, - validated: ValidatedConnection, - ) -> RecoveryOwnership { - if validated.pid() != child_pid { - return RecoveryOwnership::Unowned(validated); - } - RecoveryOwnership::Owned(Self { - child_pid, - validated, - published: false, - }) - } - - pub(in crate::gateway) fn validated(&self) -> &ValidatedConnection { - &self.validated - } - - pub(in crate::gateway) fn mark_published(&mut self) { - self.published = true; - } - - /// Shuts down the unpublished recovered child within the late-child - /// budget. - /// - /// This is the blocking, error-reporting path; `Drop` only signals on - /// a detached thread. The drop signal is disarmed either way: the - /// caller receives the outcome, so a failed delivery is reported here - /// rather than retried silently. - pub(in crate::gateway) fn shutdown(mut self) -> Result<(), ShutdownError> { - if self.published { - return Ok(()); - } - debug_assert_eq!(self.child_pid, self.validated.pid()); - self.published = true; - let deadline = Instant::now() + LATE_CHILD_SHUTDOWN_BUDGET; - workshop_server_api::discovery::request_shutdown_before(&self.validated, deadline) - } -} - -impl Drop for RecoveryCandidate { - fn drop(&mut self) { - if self.published { - return; - } - debug_assert_eq!(self.child_pid, self.validated.pid()); - // Drop can neither block nor report: the bounded authenticated - // request runs on a detached thread, so a missed explicit - // `shutdown()` still signals the unpublished gateway process. - let validated = self.validated.clone(); - let signalled = std::thread::Builder::new() - .name("gateway-late-child-shutdown".to_owned()) - .spawn(move || { - let deadline = Instant::now() + LATE_CHILD_SHUTDOWN_BUDGET; - if let Err(error) = - workshop_server_api::discovery::request_shutdown_before(&validated, deadline) - { - // The detached signal has no error return channel, so - // diagnostics are the only place this cleanup failure - // can surface. - eprintln!("could not shut down an unpublished recovered gateway: {error}"); - } - }); - if let Err(error) = signalled { - eprintln!("could not signal an unpublished recovered gateway: {error}"); - } - } -} - -impl SupervisedGatewayIdentity for ValidatedConnection { - fn same_boot(&self, other: &Self) -> bool { - same_gateway_identity(self, other) - } -} - -#[derive(Debug)] -pub(in crate::gateway) enum RecoveryIdentity { - Stable(ValidatedConnection), - Candidate(RecoveryCandidate), -} - -impl RecoveryIdentity { - pub(super) fn validated(&self) -> &ValidatedConnection { - match self { - Self::Stable(validated) => validated, - Self::Candidate(candidate) => candidate.validated(), - } - } -} - -impl SupervisedGatewayIdentity for RecoveryIdentity { - fn same_boot(&self, other: &Self) -> bool { - self.validated().same_boot(other.validated()) - } - - fn publication_succeeded(&mut self) { - if let Self::Candidate(candidate) = self { - candidate.mark_published(); - } - } - - fn shutdown_unpublished(self) { - if let Self::Candidate(candidate) = self - && let Err(error) = candidate.shutdown() - { - eprintln!("could not shut down an unpublished recovered gateway: {error}"); - } - } -} diff --git a/crates/workshop/desktop/src/gateway/supervisor/signals.rs b/crates/workshop/desktop/src/gateway/supervisor/signals.rs deleted file mode 100644 index 37424206..00000000 --- a/crates/workshop/desktop/src/gateway/supervisor/signals.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! Stop and completion signals for bounded supervisor shutdown. - -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Condvar, Mutex, PoisonError}; -use std::time::Instant; - -/// A stop request that never waits for in-progress supervisor work. -#[derive(Clone, Debug, Default)] -pub(super) struct StopSignal { - state: Arc, -} - -#[derive(Debug, Default)] -struct StopState { - requested: AtomicBool, - waiter: Mutex<()>, - wake: Condvar, -} - -impl StopSignal { - pub(super) fn signal(&self) { - let waiter = self - .state - .waiter - .lock() - .unwrap_or_else(PoisonError::into_inner); - self.state.requested.store(true, Ordering::SeqCst); - self.state.wake.notify_all(); - drop(waiter); - } - - pub(super) fn wait(&self) { - if self.state.requested.load(Ordering::SeqCst) { - return; - } - let waiter = self - .state - .waiter - .lock() - .unwrap_or_else(PoisonError::into_inner); - drop( - self.state - .wake - .wait_while(waiter, |()| !self.state.requested.load(Ordering::SeqCst)) - .unwrap_or_else(PoisonError::into_inner), - ); - } -} - -#[derive(Clone, Debug, Default)] -pub(super) struct Completion { - state: Arc, -} - -#[derive(Debug, Default)] -struct CompletionState { - finished: Mutex, - wake: Condvar, -} - -impl Completion { - pub(super) fn guard(&self) -> CompletionGuard { - CompletionGuard(self.clone()) - } - - pub(super) fn wait_until(&self, deadline: Instant) -> bool { - let mut finished = self - .state - .finished - .lock() - .unwrap_or_else(PoisonError::into_inner); - loop { - if *finished { - return true; - } - let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { - return false; - }; - if remaining.is_zero() { - return false; - } - let (next, timeout) = self - .state - .wake - .wait_timeout(finished, remaining) - .unwrap_or_else(PoisonError::into_inner); - finished = next; - if timeout.timed_out() && !*finished { - return false; - } - } - } - - #[cfg(test)] - pub(super) fn wake(&self) { - self.state.wake.notify_all(); - } -} - -pub(super) struct CompletionGuard(Completion); - -impl Drop for CompletionGuard { - fn drop(&mut self) { - *self - .0 - .state - .finished - .lock() - .unwrap_or_else(PoisonError::into_inner) = true; - self.0.state.wake.notify_all(); - } -} diff --git a/crates/workshop/desktop/src/gateway/tests.rs b/crates/workshop/desktop/src/gateway/tests.rs index a861bdc0..dd20da31 100644 --- a/crates/workshop/desktop/src/gateway/tests.rs +++ b/crates/workshop/desktop/src/gateway/tests.rs @@ -4,16 +4,15 @@ use std::io::{Read, Write as _}; use std::net::{TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; use workshop_server_api::discovery::{ - GatewayDiscoveryFile, Resolution, SidecarError, ValidatedConnection, + CancellationToken, GatewayDiscoveryFile, Resolution, SidecarError, ValidatedConnection, }; -use super::boot as gateway_boot; -use super::supervisor::{ - GatewaySupervisor, RecoveryCandidate, RecoveryOwnership, SupervisedGatewayIdentity, - SupervisorShutdown, +use super::{ + GatewaySupervisor, RecoveryCandidate, SUPERVISOR_SHUTDOWN_BUDGET, SidecarIdentity, + SupervisedGatewayIdentity, }; mod boot; @@ -22,6 +21,32 @@ mod identity; mod recovery; mod shutdown; +/// The Gateway executable's file name, which test fixtures plant. +#[cfg(windows)] +const GATEWAY_EXE_NAME: &str = "runvil-gateway.exe"; +/// The Gateway executable's file name, which test fixtures plant. +#[cfg(not(windows))] +const GATEWAY_EXE_NAME: &str = "runvil-gateway"; + +impl GatewaySupervisor { + /// Spawns one owned supervisor thread. + fn spawn(supervise: impl FnOnce(CancellationToken) + Send + 'static) -> anyhow::Result { + Self::spawn_inner(None, SUPERVISOR_SHUTDOWN_BUDGET, supervise) + } + + fn spawn_with_budget( + shutdown_budget: Duration, + supervise: impl FnOnce(CancellationToken) + Send + 'static, + ) -> anyhow::Result { + Self::spawn_inner(None, shutdown_budget, supervise) + } + + fn completion_waker_for_test(&self) -> impl Fn() + Send + 'static { + let completion = self.completion.clone(); + move || completion.state.wake.notify_all() + } +} + /// A supervised identity whose boot token the test chooses. #[derive(Clone, Debug, PartialEq, Eq)] struct TestIdentity { @@ -48,23 +73,11 @@ fn test_identity(file: GatewayDiscoveryFile) -> TestIdentity { /// Claims ownership of a validated child through its own pid. fn owned_candidate(identity: ValidatedConnection) -> RecoveryCandidate { match RecoveryCandidate::authenticate(identity.pid(), identity) { - RecoveryOwnership::Owned(candidate) => candidate, - RecoveryOwnership::Unowned(_) => panic!("the validated child pid authenticates ownership"), + SidecarIdentity::Candidate(candidate) => candidate, + SidecarIdentity::Stable(_) => panic!("the validated child pid authenticates ownership"), } } -fn assert_bounded_supervisor_shutdown(supervisor: GatewaySupervisor, finished: &AtomicBool) { - assert_eq!( - supervisor.shutdown(), - SupervisorShutdown::Joined, - "Workshop exit joins the canceled supervisor within its budget" - ); - assert!( - finished.load(Ordering::SeqCst), - "shutdown returns only after the supervisor thread exits" - ); -} - /// Resolves against the test process's own image. fn probe_own_image(run_dir: &Path) -> Result { let image = std::env::current_exe() @@ -159,20 +172,6 @@ fn accepts_bearer(request: &str, expected_key: &str) -> bool { }) } -/// Starts the shared named-process Gateway fixture in this test binary. -fn validated_gateway(expected_key: &str) -> workshop_server_api::fixtures::ValidatedGateway { - workshop_server_api::fixtures::ValidatedGateway::spawn_in( - expected_key, - "gateway::tests::validated_gateway_fixture_process", - ) -} - -#[test] -#[ignore = "runs only as a named child process"] -fn validated_gateway_fixture_process() { - workshop_server_api::fixtures::run_validated_gateway_fixture_process(); -} - /// Sends one plain GET to the Workshop fixture. fn get(url: &str, path: &str) -> String { let url = url::Url::parse(url).expect("the Workshop URL parses"); @@ -195,7 +194,7 @@ fn get(url: &str, path: &str) -> String { fn exe_dir(with_gateway: bool) -> (tempfile::TempDir, PathBuf) { let dir = tempfile::TempDir::new().expect("tempdir"); if with_gateway { - let exe = dir.path().join(gateway_boot::GATEWAY_EXE_NAME); + let exe = dir.path().join(GATEWAY_EXE_NAME); std::fs::write(&exe, b"").expect("plant the sibling exe"); // The installed-Gateway lookup skips a file it cannot run. #[cfg(unix)] diff --git a/crates/workshop/desktop/src/gateway/tests/boot-launch-wait.rs b/crates/workshop/desktop/src/gateway/tests/boot-launch-wait.rs index 4a2b4ab9..9aa112e0 100644 --- a/crates/workshop/desktop/src/gateway/tests/boot-launch-wait.rs +++ b/crates/workshop/desktop/src/gateway/tests/boot-launch-wait.rs @@ -10,7 +10,7 @@ use workshop_server_api::discovery::{ }; use super::super::{fixture_gateway, live_file, probe_own_image}; -use crate::gateway::supervisor::{ +use crate::gateway::{ RECOVERY_POLL_INTERVAL, SystemClock, WaitClock, wait_for_launched_file_cancellable_with, }; diff --git a/crates/workshop/desktop/src/gateway/tests/boot.rs b/crates/workshop/desktop/src/gateway/tests/boot.rs index d06246f3..a12256fb 100644 --- a/crates/workshop/desktop/src/gateway/tests/boot.rs +++ b/crates/workshop/desktop/src/gateway/tests/boot.rs @@ -7,88 +7,84 @@ use std::time::{Duration, Instant}; use workshop_server_api::discovery::GatewayDiscoveryFile; use super::{ - dead_pid, exe_dir, fixture_gateway, installed_in, live_file, owned_candidate, probe_own_image, - probe_read_failure, + GATEWAY_EXE_NAME, dead_pid, exe_dir, fixture_gateway, installed_in, live_file, owned_candidate, + probe_own_image, probe_read_failure, }; #[cfg(windows)] -use crate::gateway::boot::spawn_detached_windows_with; -use crate::gateway::boot::{ - GATEWAY_EXE_NAME, GatewayPlan, no_gateway_error, placeholder_gateway_error, plan_gateway, - sibling_is_placeholder, spawn_detached, +use crate::gateway::spawn_detached_windows_with; +use crate::gateway::{ + GatewayPlan, RECOVERY_POLL_INTERVAL, SidecarIdentity, no_gateway_error, + placeholder_gateway_error, plan_gateway, reconcile_publication, sibling_is_placeholder, + spawn_detached, }; -use crate::gateway::identity::GatewayAttachment; -use crate::gateway::supervisor::RECOVERY_POLL_INTERVAL; +use crate::test_support::{validated_gateway, workshop_server}; #[path = "boot-launch-wait.rs"] mod launch_wait; const FIXTURE_PHASE_TIMEOUT: Duration = Duration::from_secs(10); -#[cfg(windows)] -#[test] -fn windows_detached_spawn_first_attempt_uses_all_required_flags() { - let mut attempts = Vec::new(); - - let child_pid = spawn_detached_windows_with(|flags| { - attempts.push(flags); - Ok(41) - }) - .expect("the first spawn succeeds"); - - assert_eq!(child_pid, 41); - assert_eq!(attempts, [0x0100_0208]); -} +/// The stub `tools/fetch-gateway-sidecar.mjs --stub` writes, which CI stages +/// so compile-only jobs need no Gateway release. +const STUB_TEXT: &str = "This is a placeholder staged by tools/fetch-gateway-sidecar.mjs --stub.\n\ + It stands in for the Gateway sidecar so compile-only jobs need no release.\n"; #[cfg(windows)] -#[test] -fn windows_detached_spawn_retries_access_denied_without_breakaway() { - let mut attempts = Vec::new(); - - let child_pid = spawn_detached_windows_with(|flags| { - attempts.push(flags); - if attempts.len() == 1 { - Err(std::io::Error::from_raw_os_error(5)) - } else { - Ok(42) - } - }) - .expect("access denied retries without breakaway"); - - assert_eq!(child_pid, 42); - assert_eq!(attempts, [0x0100_0208, 0x0000_0208]); -} +type SpawnCase = ( + &'static str, + &'static [Result], + Result, + &'static [u32], +); #[cfg(windows)] -#[test] -fn windows_detached_spawn_does_not_retry_after_success() { - let mut attempts = 0; - - spawn_detached_windows_with(|_| { - attempts += 1; - Ok(43) - }) - .expect("the first spawn succeeds"); - - assert_eq!(attempts, 1); -} +const WINDOWS_SPAWN_CASES: &[SpawnCase] = &[ + ("first succeeds", &[Ok(41)], Ok(41), &[0x0100_0208]), + ( + "access denied retries", + &[Err(5), Ok(42)], + Ok(42), + &[0x0100_0208, 0x0000_0208], + ), + ( + "retry access denied", + &[Err(5), Err(5)], + Err(5), + &[0x0100_0208, 0x0000_0208], + ), + ( + "retry other error", + &[Err(5), Err(2)], + Err(2), + &[0x0100_0208, 0x0000_0208], + ), + ( + "non-permission fails", + &[Err(123)], + Err(123), + &[0x0100_0208], + ), +]; #[cfg(windows)] #[test] -fn windows_detached_spawn_does_not_retry_other_errors() { - let mut attempts = 0; - - let error = spawn_detached_windows_with::(|_| { - attempts += 1; - Err(std::io::Error::from_raw_os_error(123)) - }) - .expect_err("non-permission errors propagate"); - - assert_eq!(error.raw_os_error(), Some(123)); - assert_eq!(attempts, 1); +fn windows_detached_spawn_flags_and_retry_cases() { + for &(label, responses, expected, expected_attempts) in WINDOWS_SPAWN_CASES { + let mut attempts = Vec::new(); + let outcome = spawn_detached_windows_with(|flags| { + let index = attempts.len(); + attempts.push(flags); + responses[index].map_err(std::io::Error::from_raw_os_error) + }); + assert_eq!(attempts, expected_attempts, "{label}"); + match (outcome, expected) { + (Ok(pid), Ok(want)) => assert_eq!(pid, want, "{label}"), + (Err(err), Err(code)) => assert_eq!(err.raw_os_error(), Some(code), "{label}"), + (actual, want) => panic!("{label}: expected {want:?}, got {actual:?}"), + } + } } -/// A program that exits by itself once it reads end of input from a null -/// stdin. fn self_exiting_program() -> PathBuf { if cfg!(windows) { std::env::var_os("ComSpec").map_or_else(|| PathBuf::from("cmd.exe"), PathBuf::from) @@ -113,236 +109,149 @@ fn the_reaper_records_the_exit_status_of_a_detached_child() { } } -fn workshop_server( - port: u16, - api_key: &str, -) -> (tempfile::TempDir, workshop_server_api::ServerHandle) { - let state_dir = tempfile::TempDir::new().expect("create Workshop state directory"); - let server = workshop_server_api::fixtures::spawn(workshop_server_api::Config { - gateway: workshop_server_api::GatewayConfig { - base_url: format!("http://127.0.0.1:{port}"), - api_key: api_key.to_owned(), - }, - server: workshop_server_api::ServerConfig { - bind: "127.0.0.1:0".to_owned(), - state_dir: state_dir.path().to_owned(), - }, - agents: workshop_server_api::AgentsConfig::default(), - }) - .expect("spawn Workshop fixture"); - (state_dir, server) +#[derive(Clone, Copy)] +enum Seed { + Absent, + Live, + Stale, + Unreadable, } -#[test] -fn a_live_file_attaches_without_looking_for_a_sibling_exe() { - let run = tempfile::TempDir::new().expect("tempdir"); - let file = live_file(fixture_gateway("key"), "key"); - file.write_to(run.path()).expect("write"); - let (_exe, exe_dir) = exe_dir(false); - - match plan_gateway(run.path(), installed_in(&exe_dir), false, probe_own_image) { - GatewayPlan::Attach(attached) => assert_eq!(attached, file), - other => panic!("a live gateway must be attached, not {other:?}"), - } +#[derive(Clone, Copy)] +enum Expect { + Attach, + Launch, + ConfigOnly, + Fail, } -#[test] -fn no_file_and_a_sibling_exe_launches() { - let run = tempfile::TempDir::new().expect("tempdir"); - let (_exe, exe_dir) = exe_dir(true); - - match plan_gateway(run.path(), installed_in(&exe_dir), false, probe_own_image) { - GatewayPlan::Launch(exe) => assert_eq!(exe, exe_dir.join(GATEWAY_EXE_NAME)), - other => panic!("a full install with no running gateway must launch, not {other:?}"), - } -} - -#[test] -fn no_file_and_no_sibling_exe_falls_through_to_explicit_config() { - let run = tempfile::TempDir::new().expect("tempdir"); - let (_exe, exe_dir) = exe_dir(false); - - assert_eq!( - plan_gateway(run.path(), installed_in(&exe_dir), true, probe_own_image), - GatewayPlan::ConfigOnly, - "a Workshop-only install attaches to the configured LAN gateway" - ); -} - -#[test] -fn no_file_no_sibling_exe_and_no_config_fails() { - let run = tempfile::TempDir::new().expect("tempdir"); - let (_exe, exe_dir) = exe_dir(false); - - assert_eq!( - plan_gateway(run.path(), installed_in(&exe_dir), false, probe_own_image), - GatewayPlan::Fail, - "nothing to connect to must fail loud, not serve a broken window" - ); -} - -#[test] -fn a_stale_file_is_cleaned_and_the_sibling_exe_launches() { - let run = tempfile::TempDir::new().expect("tempdir"); - GatewayDiscoveryFile { - pid: dead_pid(), - ..live_file(1, "k") - } - .write_to(run.path()) - .expect("write"); - let (_exe, exe_dir) = exe_dir(true); - - let plan = plan_gateway(run.path(), installed_in(&exe_dir), false, probe_own_image); - assert!( - matches!(plan, GatewayPlan::Launch(_)), - "a stale file must not block the relaunch: {plan:?}" - ); - assert!( - !workshop_server_api::discovery::gateway_discovery_file_path(run.path()).exists(), - "the stale file was cleaned" - ); -} +const PLAN_CASES: &[(&str, Seed, bool, bool, Expect)] = { + use Expect::{Attach, ConfigOnly, Fail, Launch}; + use Seed::{Absent, Live, Stale, Unreadable}; + &[ + ("live only", Live, false, false, Attach), + ("live beats sibling/config", Live, true, true, Attach), + ("absent + sibling", Absent, true, false, Launch), + ("absent + config", Absent, false, true, ConfigOnly), + ("absent + none", Absent, false, false, Fail), + ("stale + sibling", Stale, true, false, Launch), + ("stale + config", Stale, false, true, ConfigOnly), + ("stale + none", Stale, false, false, Fail), + ("unreadable + sibling", Unreadable, true, false, Launch), + ("unreadable + config", Unreadable, false, true, ConfigOnly), + ("unreadable + none", Unreadable, false, false, Fail), + ] +}; #[test] -fn a_stale_file_with_no_sibling_exe_falls_through_to_explicit_config() { - let run = tempfile::TempDir::new().expect("tempdir"); - GatewayDiscoveryFile { - pid: dead_pid(), - ..live_file(1, "k") +fn gateway_planning_cases() { + let live_port = fixture_gateway("key"); + let stale_pid = dead_pid(); + + for &(label, seed, has_sibling, has_config, expected) in PLAN_CASES { + let run = tempfile::TempDir::new().expect("tempdir"); + let (_exe, dir) = exe_dir(has_sibling); + let seeded_live = match seed { + Seed::Live => { + let file = live_file(live_port, "key"); + file.write_to(run.path()).expect("write live file"); + Some(file) + } + Seed::Stale => { + GatewayDiscoveryFile { + pid: stale_pid, + ..live_file(1, "k") + } + .write_to(run.path()) + .expect("write stale file"); + None + } + Seed::Absent | Seed::Unreadable => None, + }; + let resolve = match seed { + Seed::Unreadable => probe_read_failure, + Seed::Absent | Seed::Live | Seed::Stale => probe_own_image, + }; + let plan = plan_gateway(run.path(), installed_in(&dir), has_config, resolve); + let want = match expected { + Expect::Attach => GatewayPlan::Attach(seeded_live.expect("live file")), + Expect::Launch => GatewayPlan::Launch(dir.join(GATEWAY_EXE_NAME)), + Expect::ConfigOnly => GatewayPlan::ConfigOnly, + Expect::Fail => GatewayPlan::Fail, + }; + assert_eq!(plan, want, "{label}"); + if matches!(seed, Seed::Stale) { + assert!( + !workshop_server_api::discovery::gateway_discovery_file_path(run.path()).exists(), + "{label}: stale discovery file was cleaned" + ); + } } - .write_to(run.path()) - .expect("write"); - let (_exe, exe_dir) = exe_dir(false); - - assert_eq!( - plan_gateway(run.path(), installed_in(&exe_dir), true, probe_own_image), - GatewayPlan::ConfigOnly, - "a stale file must not wedge the LAN fallback" - ); - assert!( - !workshop_server_api::discovery::gateway_discovery_file_path(run.path()).exists(), - "the stale file was cleaned" - ); -} - -#[test] -fn a_resolve_error_still_launches_the_sibling_exe() { - let run = tempfile::TempDir::new().expect("tempdir"); - let (_exe, exe_dir) = exe_dir(true); - - let plan = plan_gateway( - run.path(), - installed_in(&exe_dir), - false, - probe_read_failure, - ); - assert!( - matches!(plan, GatewayPlan::Launch(_)), - "a discovery error must not read as no-gateway: {plan:?}" - ); } #[test] fn the_installed_lookup_finds_only_the_gateway_exe_beside_the_desktop_app() { let (_dir, with) = exe_dir(true); - assert_eq!( - installed_in(&with), - Some(with.join(GATEWAY_EXE_NAME)), - "the installed sibling is found" - ); + assert_eq!(installed_in(&with), Some(with.join(GATEWAY_EXE_NAME))); let (_dir, without) = exe_dir(false); - assert_eq!( - installed_in(&without), - None, - "a Workshop-only install has no Gateway" - ); + assert_eq!(installed_in(&without), None); } #[test] fn the_no_gateway_error_names_both_remedies() { let message = no_gateway_error().to_string(); - assert!( - message.contains("runvil-gateway"), - "the error names the Gateway component remedy: {message}" - ); - assert!( - message.contains("workshop.toml"), - "the error names the explicit-config remedy: {message}" - ); -} - -/// The stub `tools/fetch-gateway-sidecar.mjs --stub` writes, which CI stages -/// so compile-only jobs need no Gateway release. -const STUB_TEXT: &str = "This is a placeholder staged by tools/fetch-gateway-sidecar.mjs --stub.\n\ - It stands in for the Gateway sidecar so compile-only jobs need no release.\n"; - -fn sibling_with(content: &[u8]) -> (tempfile::TempDir, PathBuf) { - let dir = tempfile::TempDir::new().expect("tempdir"); - let exe = dir.path().join(GATEWAY_EXE_NAME); - std::fs::write(&exe, content).expect("write the sibling"); - (dir, exe) + assert!(message.contains("runvil-gateway"), "{message}"); + assert!(message.contains("workshop.toml"), "{message}"); } -#[test] -fn a_stub_sibling_is_recognized_before_a_launch_attempt() { - let (_dir, exe) = sibling_with(STUB_TEXT.as_bytes()); - assert!( - sibling_is_placeholder(&exe), - "the compile-only stub must be caught before spawning it" - ); -} - -#[test] -fn a_real_executable_sibling_is_not_a_placeholder() { - let (_dir, exe) = sibling_with(b"MZ\x90\x00\x03\x00\x00\x00"); - assert!( - !sibling_is_placeholder(&exe), - "an executable is left to the spawn to judge" - ); -} - -#[test] -fn an_empty_sibling_is_not_treated_as_a_placeholder() { - let (_dir, exe) = sibling_with(b""); - assert!( - !sibling_is_placeholder(&exe), - "an unreadable prefix must not read as a stub" - ); -} +const PLACEHOLDER_CASES: &[(&str, Option<&[u8]>, bool)] = &[ + ("stub", Some(STUB_TEXT.as_bytes()), true), + ("windows PE", Some(b"MZ\x90\x00\x03\x00\x00\x00"), false), + ("linux ELF", Some(b"\x7fELF\x02\x01\x01\x00"), false), + ( + "macos Mach-O", + Some(b"\xcf\xfa\xed\xfe\x07\x00\x00\x01"), + false, + ), + ("other text", Some(b"This is a different file.\n"), false), + ("empty", Some(b""), false), + ("missing", None, false), +]; #[test] -fn a_missing_sibling_is_not_treated_as_a_placeholder() { - let dir = tempfile::TempDir::new().expect("tempdir"); - assert!( - !sibling_is_placeholder(&dir.path().join(GATEWAY_EXE_NAME)), - "a file that is not there cannot be a stub" - ); +fn sibling_placeholder_detection_cases() { + for &(label, content, expected) in PLACEHOLDER_CASES { + let dir = tempfile::TempDir::new().expect("tempdir"); + let exe = dir.path().join(GATEWAY_EXE_NAME); + if let Some(bytes) = content { + std::fs::write(&exe, bytes).expect("write sibling"); + } + assert_eq!(sibling_is_placeholder(&exe), expected, "{label}"); + } } #[test] fn the_placeholder_error_names_the_file_and_the_fetch_command() { - let exe = PathBuf::from("/install/runvil-gateway"); - let message = placeholder_gateway_error(&exe).to_string(); - assert!( - message.contains("runvil-gateway"), - "the error names the file that is not runnable: {message}" - ); + let message = placeholder_gateway_error(&PathBuf::from("/install/runvil-gateway")).to_string(); + assert!(message.contains("runvil-gateway"), "{message}"); assert!( message.contains("node tools/fetch-gateway-sidecar.mjs"), - "the error names the one command that stages a real Gateway: {message}" + "{message}" ); } #[test] fn matching_boot_publication_survives_closure_and_server_teardown() { - let mut launched = super::validated_gateway("launched-key"); + let mut launched = validated_gateway("launched-key"); let identity = launched.validate("launched-key", 1_778_000_001, "2026-09-08T18:00:01Z"); - let attachment = GatewayAttachment::Launched(owned_candidate(identity.clone())); + let sidecar = Some(SidecarIdentity::Candidate(owned_candidate( + identity.clone(), + ))); let (_state_dir, server) = workshop_server(launched.port(), "launched-key"); - let attachment = attachment.reconcile_publication(Some(identity)); + let sidecar = reconcile_publication(sidecar, Some(&identity)); server.gateway_updater().close_publication(); - drop(attachment); + drop(sidecar); let outcome = server.shutdown().expect("server teardown continues"); assert_eq!(outcome, workshop_server_api::Termination::Graceful); @@ -354,18 +263,20 @@ fn matching_boot_publication_survives_closure_and_server_teardown() { #[test] fn closed_boot_publication_cleans_unpublished_owner_then_continues_teardown() { - let mut launched = super::validated_gateway("launched-key"); - let published = super::validated_gateway("published-key"); + let mut launched = validated_gateway("launched-key"); + let published = validated_gateway("published-key"); let launched_identity = launched.validate("launched-key", 1_778_000_001, "2026-09-08T18:00:01Z"); let published_identity = published.validate("published-key", 1_778_000_002, "2026-09-08T18:00:02Z"); - let attachment = GatewayAttachment::Launched(owned_candidate(launched_identity)); + let sidecar = Some(SidecarIdentity::Candidate(owned_candidate( + launched_identity, + ))); let (_state_dir, server) = workshop_server(published.port(), "published-key"); server.gateway_updater().close_publication(); - let attachment = attachment.reconcile_publication(Some(published_identity)); - drop(attachment); + let sidecar = reconcile_publication(sidecar, Some(&published_identity)); + drop(sidecar); assert!( launched.received_shutdown(FIXTURE_PHASE_TIMEOUT), "a closed boot cleans only its unpublished authenticated child" diff --git a/crates/workshop/desktop/src/gateway/tests/cancellation.rs b/crates/workshop/desktop/src/gateway/tests/cancellation.rs index 247ad698..1a1f7800 100644 --- a/crates/workshop/desktop/src/gateway/tests/cancellation.rs +++ b/crates/workshop/desktop/src/gateway/tests/cancellation.rs @@ -3,257 +3,297 @@ use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, mpsc}; -use std::time::Duration; +use std::time::{Duration, Instant}; -use workshop_server_api::discovery::Resolution; +use workshop_server_api::discovery::{CancellationToken, HealthError, LaunchDecision, Resolution}; -use super::{TestIdentity, assert_bounded_supervisor_shutdown, live_file, test_identity}; -use crate::gateway::supervisor::{ - GatewaySupervisor, SupervisionProbe, SystemClock, launch_and_attach_cancellable_with, - run_effect_if_active, run_supervision, wait_for_launched_file_cancellable_with, +use super::{TestIdentity, live_file, test_identity}; +use crate::gateway::{ + GatewaySupervisor, SupervisionProbe, SupervisorShutdown, SystemClock, WaitClock, + launch_and_attach_cancellable_with, run_supervision, wait_for_launched_file_cancellable_with, }; -#[test] -fn exit_joins_a_supervisor_blocked_in_resolve_before_recovery() { - let (entered, blocked) = mpsc::channel(); - let recoveries = Arc::new(AtomicUsize::new(0)); - let worker_recoveries = Arc::clone(&recoveries); - let finished = Arc::new(AtomicBool::new(false)); - let worker_finished = Arc::clone(&finished); - let supervisor = GatewaySupervisor::spawn(move |cancellation| { - run_supervision( - test_identity(live_file(54_375, "stable-key")), - |_, cancellation| { - entered.send(()).expect("announce blocked resolve"); - let _ = cancellation.wait_timeout(Duration::from_secs(30)); - SupervisionProbe::Missing - }, - |_| -> anyhow::Result { - worker_recoveries.fetch_add(1, Ordering::SeqCst); - anyhow::bail!("recovery must not start after cancellation") - }, - |_, _| Ok::<(), anyhow::Error>(()), - |delay, cancellation| cancellation.wait_timeout(delay), - &cancellation, - ); - worker_finished.store(true, Ordering::SeqCst); - }) - .expect("spawn test supervisor"); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the resolve phase blocks deterministically"); +const BLOCK_TIMEOUT: Duration = Duration::from_secs(30); +const ENTER_TIMEOUT: Duration = Duration::from_secs(1); - assert_bounded_supervisor_shutdown(supervisor, &finished); - assert_eq!( - recoveries.load(Ordering::SeqCst), - 0, - "cancellation prevents every later recovery launch" - ); +type PhaseRun = fn(&'static str, CancellationToken, mpsc::Sender<()>, Arc); + +struct BlockingClock { + label: &'static str, + entered: mpsc::Sender<()>, } -#[test] -fn exit_joins_a_supervisor_blocked_in_validation_before_publication() { - let (entered, blocked) = mpsc::channel(); - let publications = Arc::new(AtomicUsize::new(0)); - let worker_publications = Arc::clone(&publications); - let finished = Arc::new(AtomicBool::new(false)); - let worker_finished = Arc::clone(&finished); - let supervisor = GatewaySupervisor::spawn(move |cancellation| { - run_supervision( - test_identity(live_file(54_375, "stable-key")), - |current, cancellation| { - entered.send(()).expect("announce blocked validation"); - let _ = cancellation.wait_timeout(Duration::from_secs(30)); - SupervisionProbe::Replacement(current.clone()) - }, - |_| -> anyhow::Result { - panic!("canceled validation cannot start recovery") - }, - |_, _| { - worker_publications.fetch_add(1, Ordering::SeqCst); - Ok::<(), anyhow::Error>(()) - }, - |delay, cancellation| cancellation.wait_timeout(delay), - &cancellation, - ); - worker_finished.store(true, Ordering::SeqCst); - }) - .expect("spawn test supervisor"); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the validation phase blocks deterministically"); +impl WaitClock for BlockingClock { + fn now(&self) -> Instant { + Instant::now() + } - assert_bounded_supervisor_shutdown(supervisor, &finished); - assert_eq!( - publications.load(Ordering::SeqCst), - 0, - "canceled validation cannot publish into the snapshot" - ); + fn pause(&self, _delay: Duration, cancellation: &CancellationToken) -> bool { + signal_and_wait(self.label, &self.entered, cancellation) + } } -#[test] -fn exit_joins_a_supervisor_blocked_in_health_wait_before_resolve() { - let run = tempfile::TempDir::new().expect("tempdir"); - live_file(54_375, "stable-key") - .write_to(run.path()) - .expect("write candidate"); - let run_dir = run.path().to_owned(); - let (entered, blocked) = mpsc::channel(); - let resolves = Arc::new(AtomicUsize::new(0)); - let worker_resolves = Arc::clone(&resolves); - let finished = Arc::new(AtomicBool::new(false)); - let worker_finished = Arc::clone(&finished); - let supervisor = GatewaySupervisor::spawn(move |cancellation| { - let result = wait_for_launched_file_cancellable_with( - &run_dir, - Duration::from_secs(30), - &cancellation, - &SystemClock, - |_, _, cancellation| { - entered.send(()).expect("announce blocked health wait"); - let _ = cancellation.wait_timeout(Duration::from_secs(30)); - Err(workshop_server_api::discovery::HealthError::Canceled) - }, - |_, _| { - worker_resolves.fetch_add(1, Ordering::SeqCst); - Ok(Resolution::Absent) - }, - || None, - ); - assert!(result.is_err(), "the canceled health wait is rejected"); - worker_finished.store(true, Ordering::SeqCst); - }) - .expect("spawn test supervisor"); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the health-wait phase blocks deterministically"); +fn signal_and_wait( + label: &str, + entered: &mpsc::Sender<()>, + cancellation: &CancellationToken, +) -> bool { + entered + .send(()) + .unwrap_or_else(|e| panic!("{label}: announce blocked phase: {e}")); + cancellation.wait_timeout(BLOCK_TIMEOUT) +} - assert_bounded_supervisor_shutdown(supervisor, &finished); - assert_eq!( - resolves.load(Ordering::SeqCst), - 0, - "canceled health waiting cannot start a later resolve" - ); +fn stable_identity() -> TestIdentity { + test_identity(live_file(54_375, "stable-key")) } -#[test] -fn exit_joins_a_supervisor_blocked_in_launch_race_before_spawn() { - let run = tempfile::TempDir::new().expect("tempdir"); - let decision = - workshop_server_api::discovery::launch_or_attach(run.path(), Duration::from_secs(1)) - .expect("acquire a launch decision"); - let run_dir = run.path().to_owned(); +fn assert_canceled_phase(label: &'static str, expected_count: usize, run: PhaseRun) { let (entered, blocked) = mpsc::channel(); - let launches = Arc::new(AtomicUsize::new(0)); - let worker_launches = Arc::clone(&launches); + let count = Arc::new(AtomicUsize::new(0)); + let worker_count = Arc::clone(&count); let finished = Arc::new(AtomicBool::new(false)); let worker_finished = Arc::clone(&finished); let supervisor = GatewaySupervisor::spawn(move |cancellation| { - let mut decision = Some(decision); - let result = launch_and_attach_cancellable_with( - &run_dir, - Path::new("unused-gateway"), - &cancellation, - |_, _, cancellation| { - entered.send(()).expect("announce blocked launch race"); - let _ = cancellation.wait_timeout(Duration::from_secs(30)); - Ok(decision.take().expect("one launch decision")) - }, - |_, _| { - worker_launches.fetch_add(1, Ordering::SeqCst); - Ok(42) - }, - |_, _, _| anyhow::bail!("the canceled launch cannot wait for health"), - ); - assert!(result.is_err(), "the canceled launch race is rejected"); + run(label, cancellation, entered, worker_count); worker_finished.store(true, Ordering::SeqCst); }) - .expect("spawn test supervisor"); + .unwrap_or_else(|e| panic!("{label}: spawn supervisor: {e}")); blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the launch race blocks deterministically"); + .recv_timeout(ENTER_TIMEOUT) + .unwrap_or_else(|e| panic!("{label}: phase did not block in time: {e}")); - assert_bounded_supervisor_shutdown(supervisor, &finished); - assert_eq!( - launches.load(Ordering::SeqCst), - 0, - "canceled launch racing cannot create a process" - ); + assert_eq!(supervisor.shutdown(), SupervisorShutdown::Joined, "{label}"); + assert!(finished.load(Ordering::SeqCst), "{label}: worker exited"); + assert_eq!(count.load(Ordering::SeqCst), expected_count, "{label}"); } -#[test] -fn exit_joins_a_supervisor_blocked_inside_launch_without_process_creation() { - let run = tempfile::TempDir::new().expect("tempdir"); - let decision = - workshop_server_api::discovery::launch_or_attach(run.path(), Duration::from_secs(1)) - .expect("acquire a launch decision"); - let run_dir = run.path().to_owned(); - let (entered, blocked) = mpsc::channel(); - let launches = Arc::new(AtomicUsize::new(0)); - let worker_launches = Arc::clone(&launches); - let finished = Arc::new(AtomicBool::new(false)); - let worker_finished = Arc::clone(&finished); - let supervisor = GatewaySupervisor::spawn(move |cancellation| { - let mut decision = Some(decision); - let result = launch_and_attach_cancellable_with( - &run_dir, - Path::new("unused-gateway"), - &cancellation, - |_, _, _| Ok(decision.take().expect("one launch decision")), - |_, cancellation| { - entered.send(()).expect("announce blocked launch"); - if cancellation.wait_timeout(Duration::from_secs(30)) { - return Err(std::io::Error::from(std::io::ErrorKind::Interrupted)); - } - worker_launches.fetch_add(1, Ordering::SeqCst); - Ok(42) - }, - |_, _, _| anyhow::bail!("the canceled launch cannot wait for health"), - ); - assert!(result.is_err(), "the canceled launch is rejected"); - worker_finished.store(true, Ordering::SeqCst); - }) - .expect("spawn test supervisor"); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the process launch blocks deterministically inside its effect gate"); - - assert_bounded_supervisor_shutdown(supervisor, &finished); - assert_eq!( - launches.load(Ordering::SeqCst), +const CANCELLATION_CASES: &[(&str, usize, PhaseRun)] = &[ + ( + "resolve before recovery", 0, - "the canceled launch has no post-cancel effect" - ); -} + |label, cancel, entered, count| { + run_supervision( + stable_identity(), + |_, c| { + signal_and_wait(label, &entered, c); + SupervisionProbe::Missing + }, + |_| -> anyhow::Result { + count.fetch_add(1, Ordering::SeqCst); + anyhow::bail!("{label}: recovery started after cancel") + }, + |_, _| Ok::<(), anyhow::Error>(()), + |d, c| c.wait_timeout(d), + &cancel, + ); + }, + ), + ( + "validation before publication", + 0, + |label, cancel, entered, count| { + run_supervision( + stable_identity(), + |cur, c| { + signal_and_wait(label, &entered, c); + SupervisionProbe::Replacement(cur.clone()) + }, + |_| -> anyhow::Result { panic!("{label}: unexpected recovery") }, + |_, _| { + count.fetch_add(1, Ordering::SeqCst); + Ok::<(), anyhow::Error>(()) + }, + |d, c| c.wait_timeout(d), + &cancel, + ); + }, + ), + ( + "supervision wait before next probe", + 1, + |label, cancel, entered, count| { + run_supervision( + stable_identity(), + |cur, _| { + count.fetch_add(1, Ordering::SeqCst); + SupervisionProbe::Replacement(cur.clone()) + }, + |_| -> anyhow::Result { + panic!("{label}: healthy gateway recovered") + }, + |_, _| Ok::<(), anyhow::Error>(()), + |d, c| { + entered.send(()).unwrap_or_else(|e| panic!("{label}: {e}")); + c.wait_timeout(d) + }, + &cancel, + ); + }, + ), + ( + "backoff wait after failed recovery", + 1, + |label, cancel, entered, count| { + run_supervision( + stable_identity(), + |_, _| SupervisionProbe::Missing, + |_| -> anyhow::Result { + count.fetch_add(1, Ordering::SeqCst); + anyhow::bail!("injected failure") + }, + |_, _| Ok::<(), anyhow::Error>(()), + |d, c| { + entered.send(()).unwrap_or_else(|e| panic!("{label}: {e}")); + c.wait_timeout(d) + }, + &cancel, + ); + }, + ), + ( + "health wait before resolve", + 0, + |label, cancel, entered, count| { + let run = tempfile::TempDir::new().expect("tempdir"); + live_file(54_375, "stable-key") + .write_to(run.path()) + .expect("write"); + let res = wait_for_launched_file_cancellable_with( + run.path(), + BLOCK_TIMEOUT, + &cancel, + &SystemClock, + |_, _, c| { + signal_and_wait(label, &entered, c); + Err(HealthError::Canceled) + }, + |_, _| { + count.fetch_add(1, Ordering::SeqCst); + Ok(Resolution::Absent) + }, + || None, + ); + assert!(res.is_err(), "{label}: canceled wait rejected"); + }, + ), + ( + "launch wait pause before next poll", + 0, + |label, cancel, entered, count| { + let run = tempfile::TempDir::new().expect("tempdir"); + let clock = BlockingClock { label, entered }; + let res = wait_for_launched_file_cancellable_with( + run.path(), + BLOCK_TIMEOUT, + &cancel, + &clock, + |_, _, _| { + count.fetch_add(1, Ordering::SeqCst); + Ok(()) + }, + |_, _| Ok(Resolution::Absent), + || None, + ); + assert!(res.is_err(), "{label}: canceled pause rejected"); + }, + ), + ( + "launch race before spawn", + 0, + |label, cancel, entered, count| { + let run = tempfile::TempDir::new().expect("tempdir"); + let mut decision = Some( + workshop_server_api::discovery::launch_or_attach(run.path(), ENTER_TIMEOUT) + .expect("launch decision"), + ); + let res = launch_and_attach_cancellable_with( + run.path(), + Path::new("unused-gateway"), + &cancel, + |_, _, c| { + signal_and_wait(label, &entered, c); + Ok(decision.take().expect("decision")) + }, + |_, _| { + count.fetch_add(1, Ordering::SeqCst); + Ok(42) + }, + |_, _, _| anyhow::bail!("{label}: unexpected health wait"), + ); + assert!(res.is_err(), "{label}: canceled launch race rejected"); + }, + ), + ( + "launch race attach before return", + 0, + |label, cancel, entered, count| { + let run = tempfile::TempDir::new().expect("tempdir"); + let res = launch_and_attach_cancellable_with( + run.path(), + Path::new("unused-gateway"), + &cancel, + |_, _, c| { + signal_and_wait(label, &entered, c); + Ok(LaunchDecision::Attach(live_file(54_375, "stable-key"))) + }, + |_, _| { + count.fetch_add(1, Ordering::SeqCst); + Ok(42) + }, + |_, _, _| anyhow::bail!("{label}: unexpected health wait"), + ); + assert!(res.is_err(), "{label}: canceled attach rejected"); + }, + ), + ( + "process launch effect gate", + 0, + |label, cancel, entered, count| { + let run = tempfile::TempDir::new().expect("tempdir"); + let mut decision = Some( + workshop_server_api::discovery::launch_or_attach(run.path(), ENTER_TIMEOUT) + .expect("launch decision"), + ); + let res = launch_and_attach_cancellable_with( + run.path(), + Path::new("unused-gateway"), + &cancel, + |_, _, _| Ok(decision.take().expect("decision")), + |_, c| { + if signal_and_wait(label, &entered, c) { + return Err(std::io::Error::from(std::io::ErrorKind::Interrupted)); + } + count.fetch_add(1, Ordering::SeqCst); + Ok(42) + }, + |_, _, _| anyhow::bail!("{label}: unexpected health wait"), + ); + assert!(res.is_err(), "{label}: canceled launch rejected"); + }, + ), + ( + "publication effect gate", + 0, + |label, cancel, entered, count| { + let res = cancel + .run_if_active(|| { + if signal_and_wait(label, &entered, &cancel) { + anyhow::bail!("publication canceled"); + } + count.fetch_add(1, Ordering::SeqCst); + Ok(()) + }) + .ok_or_else(|| anyhow::anyhow!("publication canceled")) + .and_then(|outcome| outcome); + assert!(res.is_err(), "{label}: canceled publication rejected"); + }, + ), +]; #[test] -fn exit_joins_a_supervisor_blocked_inside_publication_without_replacement() { - let (entered, blocked) = mpsc::channel(); - let publications = Arc::new(AtomicUsize::new(0)); - let worker_publications = Arc::clone(&publications); - let finished = Arc::new(AtomicBool::new(false)); - let worker_finished = Arc::clone(&finished); - let supervisor = GatewaySupervisor::spawn(move |cancellation| { - let result = run_effect_if_active(&cancellation, "gateway publication", |cancellation| { - entered.send(()).expect("announce blocked publication"); - if cancellation.wait_timeout(Duration::from_secs(30)) { - anyhow::bail!("gateway publication was canceled"); - } - worker_publications.fetch_add(1, Ordering::SeqCst); - Ok(()) - }); - assert!(result.is_err(), "the canceled publication is rejected"); - worker_finished.store(true, Ordering::SeqCst); - }) - .expect("spawn test supervisor"); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("snapshot publication blocks deterministically inside its effect gate"); - - assert_bounded_supervisor_shutdown(supervisor, &finished); - assert_eq!( - publications.load(Ordering::SeqCst), - 0, - "cancellation prevents authoritative snapshot replacement" - ); +fn exit_joins_a_supervisor_blocked_in_any_recovery_phase() { + for &(label, expected_count, run) in CANCELLATION_CASES { + assert_canceled_phase(label, expected_count, run); + } } diff --git a/crates/workshop/desktop/src/gateway/tests/identity.rs b/crates/workshop/desktop/src/gateway/tests/identity.rs index 1e683782..c629531a 100644 --- a/crates/workshop/desktop/src/gateway/tests/identity.rs +++ b/crates/workshop/desktop/src/gateway/tests/identity.rs @@ -1,23 +1,23 @@ //! Attachment and process-boot identity coverage. -use super::{owned_candidate, validated_gateway}; -use crate::gateway::identity::{GatewayAttachment, same_gateway_identity}; +use super::owned_candidate; +use crate::gateway::{SidecarIdentity, reconcile_publication}; +use crate::test_support::validated_gateway; #[test] fn an_explicit_config_attachment_holds_no_local_sidecar_identity() { let gateway = validated_gateway("k"); let identity = gateway.validate("k", 1_757_000_000, "2026-09-03T12:00:00Z"); - let sidecar = GatewayAttachment::Sidecar(identity.clone()); + let sidecar = Some(SidecarIdentity::Stable(identity.clone())); assert!( sidecar - .sidecar_identity() - .is_some_and(|attached| attached.same_boot(&identity)), + .as_ref() + .is_some_and(|attached| attached.validated().same_boot(&identity)), "a sidecar attachment retains its validated process identity" ); - let config = GatewayAttachment::Config; - assert_eq!( - config.sidecar_identity(), - None, + let config = reconcile_publication(None, None); + assert!( + config.is_none(), "a LAN Gateway from explicit config reports None for the sidecar identity" ); } @@ -29,9 +29,9 @@ fn validated_process_boot_identity_distinguishes_live_gateway_children() { let original = first.validate("stable-key", 1_757_000_000, "2026-09-03T12:00:00Z"); let replacement = second.validate("stable-key", 1_757_000_000, "2026-09-03T12:00:00Z"); - assert!(same_gateway_identity(&original, &original.clone())); + assert!(original.same_boot(&original.clone())); assert!( - !same_gateway_identity(&original, &replacement), + !original.same_boot(&replacement), "equal file-supplied boot metadata cannot alias another validated process" ); } @@ -40,10 +40,12 @@ fn validated_process_boot_identity_distinguishes_live_gateway_children() { fn server_publication_disarms_launched_cleanup_only_for_the_same_process_boot() { let mut launched = validated_gateway("launched-key"); let identity = launched.validate("launched-key", 1_757_000_000, "2026-09-03T12:00:00Z"); - let attachment = GatewayAttachment::Launched(owned_candidate(identity.clone())); + let sidecar = Some(SidecarIdentity::Candidate(owned_candidate( + identity.clone(), + ))); - let attachment = attachment.reconcile_publication(Some(identity)); - drop(attachment); + let sidecar = reconcile_publication(sidecar, Some(&identity)); + drop(sidecar); assert!( !launched.received_shutdown(std::time::Duration::from_millis(100)), @@ -59,14 +61,16 @@ fn server_publication_replaces_a_mismatched_candidate_and_cleans_it_up() { launched.validate("launched-key", 1_757_000_000, "2026-09-03T12:00:00Z"); let published_identity = published.validate("published-key", 1_757_000_001, "2026-09-03T12:00:01Z"); - let attachment = GatewayAttachment::Launched(owned_candidate(launched_identity)); + let sidecar = Some(SidecarIdentity::Candidate(owned_candidate( + launched_identity, + ))); - let attachment = attachment.reconcile_publication(Some(published_identity.clone())); + let sidecar = reconcile_publication(sidecar, Some(&published_identity)); assert!( - attachment - .sidecar_identity() - .is_some_and(|identity| identity.same_boot(&published_identity)), + sidecar + .as_ref() + .is_some_and(|identity| identity.validated().same_boot(&published_identity)), "supervision follows the identity the server actually published" ); assert!( diff --git a/crates/workshop/desktop/src/gateway/tests/recovery.rs b/crates/workshop/desktop/src/gateway/tests/recovery.rs index d8ed47ae..fe290ed3 100644 --- a/crates/workshop/desktop/src/gateway/tests/recovery.rs +++ b/crates/workshop/desktop/src/gateway/tests/recovery.rs @@ -1,11 +1,11 @@ -//! Continuous supervision, recovery, and joined-shutdown coverage. +//! Continuous supervision, recovery, and candidate-ownership coverage. use std::cell::{Cell, RefCell}; use std::io::{Read as _, Write as _}; use std::net::TcpListener; use std::path::Path; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, mpsc}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use anyhow::Context as _; @@ -13,15 +13,12 @@ use workshop_server_api::discovery::{ CancellationToken, GatewayDiscoveryFile, ValidatedConnection, }; -use super::{ - TestIdentity, assert_bounded_supervisor_shutdown, get, live_file, test_identity, - validated_gateway, -}; -use crate::gateway::boot::RecoveryLaunch; -use crate::gateway::supervisor::{ - GatewaySupervisor, RecoveryCandidate, RecoveryOwnership, SUPERVISION_MAX_DELAY, - SupervisionProbe, launch_and_attach_cancellable_with, run_supervision, validate_recovery, +use super::{TestIdentity, dead_pid, get, live_file, owned_candidate, test_identity}; +use crate::gateway::{ + RecoveryCandidate, RecoveryLaunch, SUPERVISION_MAX_DELAY, SidecarIdentity, SupervisionProbe, + launch_and_attach_cancellable_with, run_supervision, validate_recovery, }; +use crate::test_support::{validated_gateway, workshop_server}; /// How long a test listens to prove the named fixture received no shutdown. /// The fixture reports only accepted shutdowns over its control socket, and @@ -35,19 +32,7 @@ fn supervision_lives_past_sixty_seconds_then_propagates_a_configured_key_edit_at let original = gateway.gateway_discovery_file("old-key", 1_757_000_000, "2026-09-03T12:00:00Z"); let replacement = gateway.gateway_discovery_file("new-key", 1_757_000_001, "2026-09-03T12:00:01Z"); - let state_dir = tempfile::TempDir::new().expect("create Workshop state directory"); - let server = workshop_server_api::fixtures::spawn(workshop_server_api::Config { - gateway: workshop_server_api::GatewayConfig { - base_url: format!("http://127.0.0.1:{}", original.port), - api_key: original.api_key.clone(), - }, - server: workshop_server_api::ServerConfig { - bind: "127.0.0.1:0".to_owned(), - state_dir: state_dir.path().to_owned(), - }, - agents: workshop_server_api::AgentsConfig::default(), - }) - .expect("spawn Workshop against the original same-port key"); + let (_state_dir, server) = workshop_server(original.port, &original.api_key); let updater = server.gateway_updater(); let publish_replacement = |file: &GatewayDiscoveryFile| -> anyhow::Result<()> { let validated = ValidatedConnection::validate(file.clone()) @@ -167,11 +152,7 @@ fn reused_pid_and_file_metadata_still_publish_a_new_validated_process_boot() { fn an_exact_spawned_pid_authenticates_late_child_cleanup() { let mut gateway = validated_gateway("owned-key"); let validated = gateway.validate("owned-key", 1_778_000_001, "2026-09-08T18:00:01Z"); - let RecoveryOwnership::Owned(candidate) = - RecoveryCandidate::authenticate(validated.pid(), validated) - else { - panic!("the validated file names the spawned child"); - }; + let candidate = owned_candidate(validated); drop(candidate); @@ -185,11 +166,7 @@ fn an_exact_spawned_pid_authenticates_late_child_cleanup() { fn explicit_candidate_shutdown_delivers_and_disarms_the_drop_signal() { let mut gateway = validated_gateway("owned-key"); let validated = gateway.validate("owned-key", 1_778_000_001, "2026-09-08T18:00:01Z"); - let RecoveryOwnership::Owned(candidate) = - RecoveryCandidate::authenticate(validated.pid(), validated) - else { - panic!("the validated file names the spawned child"); - }; + let candidate = owned_candidate(validated); candidate .shutdown() @@ -211,11 +188,7 @@ fn explicit_candidate_shutdown_reports_a_delivery_failure() { let gateway = validated_gateway("owned-key"); gateway.validate("owned-key", 1_778_000_001, "2026-09-08T18:00:01Z") }; - let RecoveryOwnership::Owned(candidate) = - RecoveryCandidate::authenticate(validated.pid(), validated) - else { - panic!("the validated file names the spawned child"); - }; + let candidate = owned_candidate(validated); let error = candidate .shutdown() @@ -276,11 +249,7 @@ fn dropping_a_candidate_signals_without_waiting_for_an_unresponsive_child() { }; let validated = ValidatedConnection::validate(file).expect("the hanging endpoint validates"); hang.store(true, Ordering::SeqCst); - let RecoveryOwnership::Owned(candidate) = - RecoveryCandidate::authenticate(validated.pid(), validated) - else { - panic!("the validated file names the spawned child"); - }; + let candidate = owned_candidate(validated); let started = Instant::now(); drop(candidate); @@ -303,7 +272,7 @@ fn a_mismatched_spawned_pid_never_claims_or_cleans_the_validated_process() { .write_to(run.path()) .expect("retain the uncertain connection record"); - let RecoveryOwnership::Unowned(unowned) = + let SidecarIdentity::Stable(unowned) = RecoveryCandidate::authenticate(validated.pid() + 1, validated) else { panic!("a different validated pid cannot prove ownership"); @@ -324,11 +293,7 @@ fn a_mismatched_spawned_pid_never_claims_or_cleans_the_validated_process() { fn successful_publication_disarms_late_child_cleanup() { let mut gateway = validated_gateway("published-key"); let validated = gateway.validate("published-key", 1_778_000_001, "2026-09-08T18:00:01Z"); - let RecoveryOwnership::Owned(mut candidate) = - RecoveryCandidate::authenticate(validated.pid(), validated) - else { - panic!("the validated file names the spawned child"); - }; + let mut candidate = owned_candidate(validated); candidate.mark_published(); drop(candidate); @@ -382,7 +347,7 @@ fn launched_recovery_retains_the_spawned_pid_and_releases_launch_lock() { fn failed_validation_never_claims_or_removes_a_spawned_process_record() { let run = tempfile::TempDir::new().expect("create run directory"); let file = GatewayDiscoveryFile { - pid: super::dead_pid(), + pid: dead_pid(), ..live_file(54_375, "unvalidated-key") }; file.write_to(run.path()).expect("write uncertain record"); @@ -405,40 +370,3 @@ fn failed_validation_never_claims_or_removes_a_spawned_process_record() { "failed validation retains an uncertain process record" ); } - -#[test] -fn exit_wakes_the_supervision_wait_without_a_later_probe() { - let (entered, blocked) = mpsc::channel(); - let probes = Arc::new(AtomicUsize::new(0)); - let worker_probes = Arc::clone(&probes); - let finished = Arc::new(AtomicBool::new(false)); - let worker_finished = Arc::clone(&finished); - let supervisor = GatewaySupervisor::spawn(move |cancellation| { - run_supervision( - test_identity(live_file(54_375, "stable-key")), - |current, _| { - worker_probes.fetch_add(1, Ordering::SeqCst); - SupervisionProbe::Replacement(current.clone()) - }, - |_| -> anyhow::Result { panic!("a healthy Gateway does not recover") }, - |_, _| Ok::<(), anyhow::Error>(()), - |delay, cancellation| { - entered.send(()).expect("announce supervision wait"); - cancellation.wait_timeout(delay) - }, - &cancellation, - ); - worker_finished.store(true, Ordering::SeqCst); - }) - .expect("spawn test supervisor"); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the supervision wait blocks deterministically"); - - assert_bounded_supervisor_shutdown(supervisor, &finished); - assert_eq!( - probes.load(Ordering::SeqCst), - 1, - "cancellation prevents every later liveness probe" - ); -} diff --git a/crates/workshop/desktop/src/gateway/tests/shutdown.rs b/crates/workshop/desktop/src/gateway/tests/shutdown.rs index bef87469..bdd6ed02 100644 --- a/crates/workshop/desktop/src/gateway/tests/shutdown.rs +++ b/crates/workshop/desktop/src/gateway/tests/shutdown.rs @@ -4,11 +4,12 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, mpsc}; use std::time::Duration; -use super::validated_gateway; -use crate::gateway::supervisor::{ - GatewaySupervisor, SUPERVISOR_SHUTDOWN_BUDGET, SupervisedGatewayIdentity, SupervisionProbe, - SupervisorShutdown, run_supervision, +use super::{TestIdentity, live_file, test_identity}; +use crate::gateway::{ + GatewaySupervisor, SUPERVISOR_SHUTDOWN_BUDGET, SupervisionProbe, SupervisorShutdown, + run_supervision, }; +use crate::test_support::{validated_gateway, workshop_server}; /// How long a test waits for a teardown that must finish while its worker /// is still parked. Shorter than [`SUPERVISOR_SHUTDOWN_BUDGET`], so a @@ -21,16 +22,6 @@ const _: () = assert!(TEARDOWN_DEADLINE.as_millis() < SUPERVISOR_SHUTDOWN_BUDGET /// waits it out fails instead of passing late. const UNREACHED_BUDGET: Duration = Duration::from_secs(3600); -/// A supervised identity reduced to its process boot. -#[derive(Clone)] -struct Boot(u64); - -impl SupervisedGatewayIdentity for Boot { - fn same_boot(&self, other: &Self) -> bool { - self.0 == other.0 - } -} - /// Runs `teardown` on its own thread while the caller keeps the worker /// parked. A teardown that waits for the worker cannot finish, so it /// reports a timeout instead of hanging the test. @@ -148,7 +139,7 @@ fn a_shut_down_supervisor_launches_nothing_when_its_gateway_later_disappears() { let worker_launches = Arc::clone(&launches); let supervisor = GatewaySupervisor::spawn(move |cancellation| { run_supervision( - Boot(1), + test_identity(live_file(54_375, "stable-key")), |current, _| { if worker_gone.load(Ordering::SeqCst) { SupervisionProbe::Missing @@ -156,9 +147,9 @@ fn a_shut_down_supervisor_launches_nothing_when_its_gateway_later_disappears() { SupervisionProbe::Replacement(current.clone()) } }, - |_| -> anyhow::Result { + |_| -> anyhow::Result { worker_launches.fetch_add(1, Ordering::SeqCst); - Ok(Boot(2)) + Ok(test_identity(live_file(54_376, "replacement-key"))) }, |_, _| Ok::<(), anyhow::Error>(()), |delay, cancellation| { @@ -184,19 +175,7 @@ fn a_shut_down_supervisor_launches_nothing_when_its_gateway_later_disappears() { #[test] fn shutdown_revokes_publication_before_waking_a_late_worker() { - let state_dir = tempfile::TempDir::new().expect("create Workshop state directory"); - let server = workshop_server_api::fixtures::spawn(workshop_server_api::Config { - gateway: workshop_server_api::GatewayConfig { - base_url: "http://127.0.0.1:54375".to_owned(), - api_key: "old-key".to_owned(), - }, - server: workshop_server_api::ServerConfig { - bind: "127.0.0.1:0".to_owned(), - state_dir: state_dir.path().to_owned(), - }, - agents: workshop_server_api::AgentsConfig::default(), - }) - .expect("spawn Workshop"); + let (_state_dir, server) = workshop_server(54_375, "old-key"); let updater = server.gateway_updater(); let worker_updater = updater.clone(); let replacement_gateway = validated_gateway("replacement-key"); diff --git a/crates/workshop/desktop/src/linux_media.rs b/crates/workshop/desktop/src/linux_media.rs index 1cb72ba1..ff525438 100644 --- a/crates/workshop/desktop/src/linux_media.rs +++ b/crates/workshop/desktop/src/linux_media.rs @@ -9,6 +9,7 @@ //! keeps the default deny. use anyhow::Context as _; +use tauri::WebviewWindow; use webkit2gtk::{ PermissionRequestExt as _, SettingsExt as _, UserMediaPermissionRequest, WebViewExt as _, glib::Cast as _, @@ -21,7 +22,7 @@ use webkit2gtk::{ /// Returns an error when the closure cannot be dispatched to the webview's /// thread; the caller logs it and the mic stays unavailable, nothing else /// breaks. -pub(crate) fn grant_media_permissions(window: &tauri::WebviewWindow) -> anyhow::Result<()> { +pub(crate) fn grant_media_permissions(window: &WebviewWindow) -> anyhow::Result<()> { window .with_webview(|webview| { let webview = webview.inner(); diff --git a/crates/workshop/desktop/src/main.rs b/crates/workshop/desktop/src/main.rs index 52bf45db..e7e33090 100644 --- a/crates/workshop/desktop/src/main.rs +++ b/crates/workshop/desktop/src/main.rs @@ -36,22 +36,33 @@ mod drops; mod gateway; #[cfg(target_os = "linux")] mod linux_media; -mod menu; mod navigation; mod quit; +#[cfg(test)] +mod test_support; mod window_state; +use std::env; +use std::error::Error; use std::ffi::OsStr; -use std::process::ExitCode; +use std::process::{self, ExitCode}; use std::sync::{Mutex, PoisonError}; use std::time::Duration; use anyhow::Context as _; +#[cfg(target_os = "macos")] +use tauri::TitleBarStyle; use tauri::ipc::CapabilityBuilder; -use tauri::{Manager as _, WebviewUrl, WebviewWindowBuilder}; +use tauri::{App, AppHandle, Manager as _, RunEvent, WebviewUrl, WebviewWindowBuilder}; +#[cfg(not(target_os = "windows"))] +use tauri::{DragDropEvent, WindowEvent}; use tauri_plugin_dialog::{DialogExt as _, MessageDialogKind}; use tauri_plugin_opener::OpenerExt as _; -use workshop_server_api::ServerHandle; +use url::Url; +use workshop_server_api::{ServerHandle, Termination}; + +use crate::gateway::{GatewaySupervisor, SupervisorShutdown}; +use crate::navigation::Navigation; /// How long the app waits for the in-process server's health endpoint /// before giving up. @@ -63,7 +74,7 @@ const HEALTH_TIMEOUT: Duration = Duration::from_secs(15); type ServerSlot = Mutex>; /// The managed local-sidecar supervisor, absent for an explicit LAN Gateway. -type GatewaySupervisorSlot = Mutex>; +type GatewaySupervisorSlot = Mutex>; /// The permission set the workshop page holds. The grant itself is built /// in setup with the exact bound port: the OS assigns the port at boot, so @@ -86,81 +97,52 @@ const WINDOW_PERMISSIONS: &[&str] = &[ ]; fn main() -> ExitCode { - if std::env::args_os().any(|arg| arg == "--version") { - return print_version(); - } - if std::env::args_os().any(|arg| arg == "--plugins") { - return print_plugins(); - } - match run() { - Ok(()) => ExitCode::SUCCESS, - Err(error) => { - eprintln!("{error:?}"); - ExitCode::FAILURE - } + // `runvil-workshop --version`: print the version and exit, without + // booting the server or opening a window. The release workflows smoke-test + // the installed package with it. The release build is GUI-subsystem on + // Windows, but a piped or inherited stdout still receives the line. + if env::args_os().any(|arg| arg == "--version") { + println!("runvil-workshop {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; } -} - -/// `runvil-workshop --version`: print the version and exit, without -/// booting the server or opening a window. The release workflows smoke-test -/// the installed package with it. The release build is GUI-subsystem on -/// Windows, but a piped or inherited stdout still receives the line. -fn print_version() -> ExitCode { - println!("runvil-workshop {}", env!("CARGO_PKG_VERSION")); - ExitCode::SUCCESS -} - -/// `runvil-workshop --plugins`: print each library Plugin this -/// installation loads, as its name and its version, and exit, without -/// booting the server or opening a window. A library that does not load -/// goes to stderr with the reason. Workshop keeps no log, so this is how -/// a person sees why an agent has no file tools, no shell, or no web -/// tools, and the release workflows check the installed Plugins with it. -fn print_plugins() -> ExitCode { - let directory = match config::load() { - Ok(config) => config.agents.plugins, - Err(error) => { - eprintln!("{error:?}"); + // `runvil-workshop --plugins`: print each library Plugin this + // installation loads, as its name and its version, and exit, without + // booting the server or opening a window. A library that does not load + // goes to stderr with the reason. Workshop keeps no log, so this is how + // a person sees why an agent has no file tools, no shell, or no web + // tools, and the release workflows check the installed Plugins with it. + if env::args_os().any(|arg| arg == "--plugins") { + let directory = match config::load() { + Ok(config) => config.agents.plugins, + Err(error) => { + eprintln!("{error:?}"); + return ExitCode::FAILURE; + } + }; + let Some(directory) = directory else { + eprintln!("this installation names no Plugin directory"); return ExitCode::FAILURE; - } - }; - let Some(directory) = directory else { - eprintln!("this installation names no Plugin directory"); - return ExitCode::FAILURE; - }; - match workshop_server_api::list_plugin_dir(&directory) { - Ok(listing) => { - for line in &listing.loaded { - println!("{line}"); + }; + return match workshop_server_api::list_plugin_dir(&directory) { + Ok(listing) => { + for line in &listing.loaded { + println!("{line}"); + } + for line in &listing.failed { + eprintln!("{line}"); + } + ExitCode::SUCCESS } - for line in &listing.failed { - eprintln!("{line}"); + Err(error) => { + eprintln!( + "cannot read the Plugin directory {}: {error}", + directory.display() + ); + ExitCode::FAILURE } - ExitCode::SUCCESS - } - Err(error) => { - eprintln!( - "cannot read the Plugin directory {}: {error}", - directory.display() - ); - ExitCode::FAILURE - } + }; } -} -fn update_supported(os: &str, appimage: Option<&OsStr>) -> bool { - os != "linux" || appimage.is_some_and(|value| !value.is_empty()) -} - -#[tauri::command] -fn desktop_update_supported() -> bool { - update_supported( - std::env::consts::OS, - std::env::var_os("APPIMAGE").as_deref(), - ) -} - -fn run() -> anyhow::Result<()> { let builder = tauri::Builder::default() // Registered first so a second launch exits inside `build`, before // its own setup could spawn a second in-process server and race @@ -179,94 +161,124 @@ fn run() -> anyhow::Result<()> { desktop_update_supported, quit::quit ]) - .on_menu_event(menu::handle_event) + .on_menu_event(quit::handle_menu_event) .setup(boot_and_open); // Off Windows, OS file drops arrive as Tauri's own drag-drop event and // are dispatched into the same runvil:file-drop grant flow. On - // Windows the drag-drop handler is disabled (see open_window) and drops + // Windows the drag-drop handler is disabled (see boot_and_open) and drops // arrive over the WebView2 web-message bridge instead. #[cfg(not(target_os = "windows"))] let builder = builder.on_window_event(|window, event| { - if let tauri::WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event + if let WindowEvent::DragDrop(DragDropEvent::Drop { paths, .. }) = event && let Some(webview) = window.get_webview_window(window.label()) { drops::dispatch_file_drop(&webview, paths); } }); - let app = builder + let app = match builder .build(tauri::generate_context!()) - .context("build the desktop application")?; + .context("build the desktop application") + { + Ok(app) => app, + Err(error) => { + eprintln!("{error:?}"); + return ExitCode::FAILURE; + } + }; app.run(|handle, event| { - if let tauri::RunEvent::Exit = event { - let supervisor = handle.try_state::().and_then(|slot| { - slot.lock() - .unwrap_or_else(PoisonError::into_inner) - .take() - }); - let supervisor_outcome = supervisor.map(gateway::GatewaySupervisor::shutdown); - let server = handle + if let RunEvent::Exit = event { + stop_supervisor(handle); + if let Some(server) = handle .try_state::() - .map(|slot| slot.lock().unwrap_or_else(PoisonError::into_inner).take()); - continue_teardown(supervisor_outcome, || { - if let Some(Some(server)) = server { - match server.shutdown() { - Ok(workshop_server_api::Termination::Graceful) => {} - Ok(termination) => { - eprintln!("the workshop server was forced down past its drain window: {termination:?}"); - } - Err(error) => { - eprintln!("could not shut the workshop server down cleanly: {error:?}"); - } + .and_then(|slot| slot.lock().unwrap_or_else(PoisonError::into_inner).take()) + { + match server.shutdown() { + Ok(Termination::Graceful) => {} + Ok(termination) => { + eprintln!( + "the workshop server was forced down past its drain window: {termination:?}" + ); + } + Err(error) => { + eprintln!("could not shut the workshop server down cleanly: {error:?}"); } } - }); + } } }); - Ok(()) + ExitCode::SUCCESS +} + +fn update_supported(os: &str, appimage: Option<&OsStr>) -> bool { + os != "linux" || appimage.is_some_and(|value| !value.is_empty()) +} + +#[tauri::command] +fn desktop_update_supported() -> bool { + update_supported(env::consts::OS, env::var_os("APPIMAGE").as_deref()) +} + +/// Takes any managed local-sidecar supervisor, shuts it down within its +/// budget, and reports any non-clean join. +pub(crate) fn stop_supervisor(app: &AppHandle) { + let supervisor = app + .try_state::() + .and_then(|slot| slot.lock().unwrap_or_else(PoisonError::into_inner).take()); + report_supervisor_shutdown(supervisor.map(GatewaySupervisor::shutdown)); } /// Reports a supervisor shutdown that did not join cleanly. `None` means /// there was no supervisor, or quit already stopped it. -fn report_supervisor_shutdown(supervisor: Option) { +fn report_supervisor_shutdown(supervisor: Option) { match supervisor { - Some(gateway::SupervisorShutdown::Joined) | None => {} - Some(gateway::SupervisorShutdown::Panicked) => { + Some(SupervisorShutdown::Joined) | None => {} + Some(SupervisorShutdown::Panicked) => { eprintln!("the gateway supervisor panicked during shutdown"); } - Some(gateway::SupervisorShutdown::Detached) => { + Some(SupervisorShutdown::Detached) => { eprintln!("the gateway supervisor exceeded its shutdown budget and was detached"); } } } -fn continue_teardown( - supervisor: Option, - shutdown_server: impl FnOnce(), -) { - report_supervisor_shutdown(supervisor); - shutdown_server(); -} - /// The setup hook: connects the gateway (attach or launch), boots the /// in-process server, installs the window's exact-port capability and the -/// menu, and opens the window on the server's URL. A boot failure prints -/// its full error chain, shows it in an error dialog, and exits the process -/// directly once the dialog closes: a release build on Windows has no -/// console, and returning `Err` would surface as Tauri's "Failed to setup -/// app" panic, losing the chain and the failure exit code. The hook returns -/// while the dialog is up, because some platforms run dialogs on the event -/// loop. -fn boot_and_open(app: &mut tauri::App) -> Result<(), Box> { - match boot() { - Ok((server, url, attachment, supervisor)) => { - // The capability must exist before the window does: the - // authority resolves a window's grants at creation. - app.add_capability(window_capability(&url))?; - app.manage(GatewaySupervisorSlot::new(supervisor)); - app.manage(ServerSlot::new(Some(server))); - menu::install(app, attachment.sidecar_identity().is_some())?; - open_window(app, &url) +/// menu, and opens the window on the server's URL. A failure after the +/// server spawns shuts the server down before reporting. A boot failure +/// prints its full error chain, shows it in an error dialog, and exits the +/// process directly once the dialog closes: a release build on Windows has +/// no console, and returning `Err` would surface as Tauri's "Failed to +/// setup app" panic, losing the chain and the failure exit code. The hook +/// returns while the dialog is up, because some platforms run dialogs on +/// the event loop. +fn boot_and_open(app: &mut App) -> Result<(), Box> { + let booted = (|| -> anyhow::Result<_> { + let config = config::load().context("load the workshop configuration")?; + let sidecar = gateway::ensure_gateway(&config).context("connect to the gateway")?; + let server = + workshop_server_api::spawn(config).context("start the in-process workshop server")?; + let sidecar = gateway::reconcile_publication(sidecar, server.initial_gateway_identity()); + let ready = (|| -> anyhow::Result<_> { + workshop_server_api::discovery::wait_for_health(server.url(), HEALTH_TIMEOUT) + .context("wait for the in-process workshop server")?; + let url = Url::parse(server.url()).context("parse the workshop URL")?; + let supervisor = gateway::supervise(sidecar.as_ref(), server.gateway_updater()) + .context("supervise the local gateway")?; + Ok((url, supervisor)) + })(); + match ready { + Ok((url, supervisor)) => Ok((server, url, sidecar, supervisor)), + Err(error) => { + if let Err(shutdown_error) = server.shutdown() { + eprintln!("{shutdown_error:?}"); + } + Err(error) + } } + })(); + + let (server, url, sidecar, supervisor) = match booted { + Ok(booted) => booted, Err(error) => { eprintln!("{error:?}"); #[expect( @@ -278,81 +290,26 @@ fn boot_and_open(app: &mut tauri::App) -> Result<(), Box> .message(format!("{error:?}")) .title("Runvil could not start") .kind(MessageDialogKind::Error) - .show(|_| std::process::exit(1)); - Ok(()) + .show(|_| process::exit(1)); + return Ok(()); } - } -} - -/// Connects the gateway (attach to a live gateway discovery file, or -/// launch the sibling `runvil-gateway` detached), then spawns the -/// in-process workshop server - which resolves the same endpoint itself, -/// gateway discovery file first, explicit `workshop.toml` config -/// second - and waits out its -/// health probe. A failure after the spawn shuts the server down before -/// propagating. -fn boot() -> anyhow::Result<( - ServerHandle, - url::Url, - gateway::GatewayAttachment, - Option, -)> { - let config = config::load().context("load the workshop configuration")?; - let attachment = gateway::ensure_gateway(&config).context("connect to the gateway")?; - let server = - workshop_server_api::spawn(config).context("start the in-process workshop server")?; - let attachment = attachment.reconcile_publication(server.initial_gateway_identity().cloned()); - match workshop_server_api::discovery::wait_for_health(server.url(), HEALTH_TIMEOUT) - .context("wait for the in-process workshop server") - { - Ok(()) => { - let url = url::Url::parse(server.url()).context("parse the workshop URL")?; - let supervisor = match gateway::supervise(&attachment, server.gateway_updater()) { - Ok(supervisor) => supervisor, - Err(error) => { - if let Err(shutdown_error) = server.shutdown() { - eprintln!("{shutdown_error:?}"); - } - return Err(error.context("supervise the local gateway")); - } - }; - Ok((server, url, attachment, supervisor)) - } - Err(error) => { - if let Err(shutdown_error) = server.shutdown() { - eprintln!("{shutdown_error:?}"); - } - Err(error) - } - } -} + }; -/// The `main` window's capability: the permission set granted to the -/// exact loopback origin the in-process server bound. Building it in -/// setup is what lets the bind stay an OS-assigned port - a capability -/// file could name only a wildcard port, which would hand the window's -/// Tauri API surface to any other loopback server on the machine. -fn window_capability(url: &url::Url) -> CapabilityBuilder { - let builder = CapabilityBuilder::new("workshop-main") - .local(false) - .remote(url.origin().ascii_serialization()) - .window("main"); - WINDOW_PERMISSIONS - .iter() - .fold(builder, |builder, permission| { - builder.permission(*permission) - }) -} + // The capability must exist before the window does: the + // authority resolves a window's grants at creation. + app.add_capability(window_capability(&url))?; + app.manage(GatewaySupervisorSlot::new(supervisor)); + app.manage(ServerSlot::new(Some(server))); + quit::install_menu(app, sidecar.is_some())?; -/// Creates the workshop window on `url`: hidden while built so the -/// window-state restore never flashes, undecorated on Windows where the -/// custom HTML title bar replaces the native frame, overlay-titled on -/// macOS where the native traffic lights float over the custom bar's left -/// edge (the bar hides its Windows-style control cluster there), decorated -/// on Linux, restored to the open workspace file's saved -/// geometry, then shown. The saver that writes geometry back into the -/// file is installed before the show, so the first layout pass is saved. -fn open_window(app: &mut tauri::App, url: &url::Url) -> Result<(), Box> { + // Creates the workshop window on `url`: hidden while built so the + // window-state restore never flashes, undecorated on Windows where the + // custom HTML title bar replaces the native frame, overlay-titled on + // macOS where the native traffic lights float over the custom bar's left + // edge (the bar hides its Windows-style control cluster there), decorated + // on Linux, restored to the open workspace file's saved geometry, then + // shown. The saver that writes geometry back into the file is installed + // before the show, so the first layout pass is saved. let server_origin = url.origin(); let opener = app.handle().clone(); let builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url.clone())) @@ -361,8 +318,8 @@ fn open_window(app: &mut tauri::App, url: &url::Url) -> Result<(), Box true, - navigation::Navigation::OpenExternally => { + Navigation::Allow => true, + Navigation::OpenExternally => { if let Err(error) = opener.opener().open_url(target.as_str(), None::<&str>) { eprintln!("could not open {target} in the system browser: {error}"); } @@ -382,7 +339,7 @@ fn open_window(app: &mut tauri::App, url: &url::Url) -> Result<(), Box Result<(), Box { - let restored = window_state::restore(&window, &client); - window_state::spawn_saver(&window, client, restored); - } - Err(error) => { - eprintln!("window geometry will not be restored or saved: {error:#}"); - } - } + window_state::attach(&window, url); window.show()?; Ok(()) } +/// The `main` window's capability: the permission set granted to the +/// exact loopback origin the in-process server bound. Building it in +/// setup is what lets the bind stay an OS-assigned port - a capability +/// file could name only a wildcard port, which would hand the window's +/// Tauri API surface to any other loopback server on the machine. +fn window_capability(url: &Url) -> CapabilityBuilder { + let builder = CapabilityBuilder::new("workshop-main") + .local(false) + .remote(url.origin().ascii_serialization()) + .window("main"); + WINDOW_PERMISSIONS + .iter() + .copied() + .fold(builder, CapabilityBuilder::permission) +} + #[cfg(test)] mod tests { - use super::*; - use tauri::ipc::RuntimeCapability as _; use tauri::utils::acl::capability::CapabilityFile; + use super::*; + #[test] fn crate_is_named_workshop() { assert_eq!(env!("CARGO_PKG_NAME"), "workshop"); } + const UPDATE_SUPPORT_CASES: &[(&str, &str, Option<&str>, bool)] = &[ + ("linux no env", "linux", None, false), + ("linux empty env", "linux", Some(""), false), + ( + "linux appimage", + "linux", + Some("/tmp/Runvil.AppImage"), + true, + ), + ("windows", "windows", None, true), + ("macos", "macos", None, true), + ]; + #[test] fn linux_updates_require_an_appimage_runtime() { - assert!(!update_supported("linux", None)); - assert!(!update_supported("linux", Some(OsStr::new("")))); - assert!(update_supported( - "linux", - Some(OsStr::new("/tmp/Runvil.AppImage")) - )); - assert!(update_supported("windows", None)); - assert!(update_supported("macos", None)); + for &(label, os, appimage, expected) in UPDATE_SUPPORT_CASES { + assert_eq!( + update_supported(os, appimage.map(OsStr::new)), + expected, + "{label}" + ); + } } #[test] fn the_window_capability_names_the_exact_bound_origin() { - let url = url::Url::parse("http://127.0.0.1:49152/").expect("the URL parses"); + let url = Url::parse("http://127.0.0.1:49152/").expect("the URL parses"); let CapabilityFile::Capability(capability) = window_capability(&url).build() else { panic!("the builder produces a single capability"); }; @@ -485,18 +462,13 @@ mod tests { } #[test] - fn every_supervisor_outcome_continues_server_teardown() { + fn every_supervisor_outcome_reports_without_stopping_teardown() { for outcome in [ - gateway::SupervisorShutdown::Joined, - gateway::SupervisorShutdown::Panicked, - gateway::SupervisorShutdown::Detached, + SupervisorShutdown::Joined, + SupervisorShutdown::Panicked, + SupervisorShutdown::Detached, ] { - let continued = std::cell::Cell::new(false); - continue_teardown(Some(outcome), || continued.set(true)); - assert!( - continued.get(), - "{outcome:?} cannot prevent application teardown" - ); + report_supervisor_shutdown(Some(outcome)); } } } diff --git a/crates/workshop/desktop/src/menu-tests.rs b/crates/workshop/desktop/src/menu-tests.rs deleted file mode 100644 index 29d00779..00000000 --- a/crates/workshop/desktop/src/menu-tests.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! The quit item's accelerator: `CmdOrCtrl+Q` on macOS, where Cmd+Q is the -//! platform's quit gesture, and none on Windows and Linux, where Ctrl+Q -//! opens View in the SPA. - -use super::quit_accelerator; - -#[test] -fn the_quit_item_keeps_cmd_or_ctrl_q_on_macos() { - assert_eq!(quit_accelerator(true), Some("CmdOrCtrl+Q")); -} - -#[test] -fn the_quit_item_has_no_accelerator_on_windows_and_linux() { - assert_eq!(quit_accelerator(false), None); -} diff --git a/crates/workshop/desktop/src/menu.rs b/crates/workshop/desktop/src/menu.rs deleted file mode 100644 index 0a05b810..00000000 --- a/crates/workshop/desktop/src/menu.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! The window menu: the quit-everything affordance. -//! -//! The desktop app's only menu item quits the app through the shared -//! shutdown-then-exit path in `quit.rs`, which the SPA's File > Exit row -//! (the `quit` command) also runs: when boot attached to or launched a -//! local sidecar gateway, the item first posts the gateway's `/shutdown` -//! through the server's current validated Gateway snapshot, so one -//! gesture stops the window, the in-process server, and the Gateway. -//! Attached to a LAN Gateway through explicit config, the snapshot grants -//! no shutdown authority, so the item stops the desktop app only and says so. - -use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder}; -use tauri::{AppHandle, Wry}; - -/// The quit item's menu id, matched by the event handler. -const QUIT_MENU_ID: &str = "quit-runvil"; - -/// The quit item's accelerator. macOS keeps `CmdOrCtrl+Q`, the platform's -/// quit gesture. Windows and Linux have none: Ctrl+Q opens View in the SPA -/// (the Open View... row), so quitting there goes through the SPA's File > -/// Exit row and the `quit` command. -fn quit_accelerator(macos: bool) -> Option<&'static str> { - macos.then_some("CmdOrCtrl+Q") -} - -/// Builds and installs the app menu. A local sidecar makes the quit item -/// stop both products; a configured LAN Gateway makes it stop only the desktop app. -/// -/// # Errors -/// Returns an error when the menu cannot be built or installed. -pub(crate) fn install(app: &tauri::App, has_sidecar: bool) -> tauri::Result<()> { - let label = if has_sidecar { - "Quit Runvil and Gateway" - } else { - "Quit Runvil" - }; - let mut quit = MenuItemBuilder::with_id(QUIT_MENU_ID, label); - if let Some(accelerator) = quit_accelerator(cfg!(target_os = "macos")) { - quit = quit.accelerator(accelerator); - } - let quit = quit.build(app)?; - // Setting a menu replaces the stock one wholesale, so macOS - // re-declares the default layout (app, File, Edit, View, Window) with - // the stock Quit swapped for the quit-everything item. Windows and - // Linux get the single File submenu; the Windows window is - // undecorated, so the menu bar is hidden there, and with no - // accelerator (Ctrl+Q opens View there) the SPA's File > Exit row is - // the gesture. - #[cfg(target_os = "macos")] - let menu = { - let app_menu = SubmenuBuilder::new(app, "Runvil") - .about(None) - .separator() - .services() - .separator() - .hide() - .hide_others() - .show_all() - .separator() - .item(&quit) - .build()?; - let file = SubmenuBuilder::new(app, "File").close_window().build()?; - let edit = SubmenuBuilder::new(app, "Edit") - .undo() - .redo() - .separator() - .cut() - .copy() - .paste() - .select_all() - .build()?; - let view = SubmenuBuilder::new(app, "View").fullscreen().build()?; - let window = SubmenuBuilder::new(app, "Window") - .minimize() - .maximize() - .separator() - .close_window() - .build()?; - MenuBuilder::new(app) - .items(&[&app_menu, &file, &edit, &view, &window]) - .build()? - }; - #[cfg(not(target_os = "macos"))] - let menu = { - let file = SubmenuBuilder::new(app, "File").item(&quit).build()?; - MenuBuilder::new(app).item(&file).build()? - }; - let _previous = app.set_menu(menu)?; - Ok(()) -} - -/// Handles the quit item by running the shared stop-then-shutdown-then-exit -/// path (`quit::quit_everything`), the same path the SPA's File > Exit row -/// invokes through the `quit` command. -pub(crate) fn handle_event(app: &AppHandle, event: tauri::menu::MenuEvent) { - let tauri::menu::MenuEvent { id } = event; - if id != QUIT_MENU_ID { - return; - } - crate::quit::quit_everything(app); -} - -#[cfg(test)] -#[path = "menu-tests.rs"] -mod tests; diff --git a/crates/workshop/desktop/src/navigation.rs b/crates/workshop/desktop/src/navigation.rs index 72359eae..30eaa811 100644 --- a/crates/workshop/desktop/src/navigation.rs +++ b/crates/workshop/desktop/src/navigation.rs @@ -7,6 +7,8 @@ //! picker, or file-drop bridge. Other schemes (`about:blank`, `data:`) //! and unparseable values are left to the webview. +use url::{Origin, Url}; + /// What the app does with a URL the webview wants to navigate to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Navigation { @@ -20,8 +22,8 @@ pub(crate) enum Navigation { /// same-origin http(s) URL (the in-process server) loads in the webview, /// while any other absolute http(s) URL opens in the system browser. #[must_use] -pub(crate) fn classify_navigation(server: &url::Origin, target: &str) -> Navigation { - let Ok(url) = url::Url::parse(target) else { +pub(crate) fn classify_navigation(server: &Origin, target: &str) -> Navigation { + let Ok(url) = Url::parse(target) else { return Navigation::Allow; }; if !matches!(url.scheme(), "http" | "https") { @@ -36,90 +38,87 @@ pub(crate) fn classify_navigation(server: &url::Origin, target: &str) -> Navigat #[cfg(test)] mod tests { + use url::Url; + + use super::Navigation::{Allow, OpenExternally}; use super::{Navigation, classify_navigation}; - /// The origin of the in-process server the test window was opened on. - fn server_origin(url: &str) -> url::Origin { - match url::Url::parse(url) { - Ok(parsed) => parsed.origin(), - Err(error) => panic!("the test server URL must parse: {error}"), - } - } + const SERVER: &str = "http://127.0.0.1:7910/"; - #[test] - fn same_origin_urls_load_in_the_webview() { - let server = server_origin("http://127.0.0.1:7910/"); - for url in [ - "http://127.0.0.1:7910/", - "http://127.0.0.1:7910/ws", + // `None` server uses `SERVER`. + const CASES: &[(&str, Option<&str>, &str, Navigation)] = &[ + ("same origin root", None, SERVER, Allow), + ("same origin path", None, "http://127.0.0.1:7910/ws", Allow), + ( + "same origin query/hash", + None, "http://127.0.0.1:7910/settings?tab=keys#top", - ] { - assert_eq!( - classify_navigation(&server, url), - Navigation::Allow, - "{url}" - ); - } - } - - #[test] - fn a_default_port_normalizes_into_the_origin() { - let server = server_origin("https://127.0.0.1/"); - assert_eq!( - classify_navigation(&server, "https://127.0.0.1:443/"), - Navigation::Allow - ); - } - - #[test] - fn other_loopback_origins_open_in_the_system_browser() { - let server = server_origin("http://127.0.0.1:7910/"); - for url in [ - // Another loopback server is not the workshop, whatever the - // port, scheme, or loopback spelling. + Allow, + ), + ( + "https default port", + Some("https://127.0.0.1/"), + "https://127.0.0.1:443/", + Allow, + ), + ( + "http default port", + Some("http://127.0.0.1/"), + "http://127.0.0.1:80/", + Allow, + ), + ( + "loopback port", + None, "http://127.0.0.1:4000/", + OpenExternally, + ), + ( + "loopback scheme", + None, "https://127.0.0.1:7910/", + OpenExternally, + ), + ( + "loopback localhost", + None, "http://localhost:7910/", - "http://[::1]:7910/", - ] { - assert_eq!( - classify_navigation(&server, url), - Navigation::OpenExternally, - "{url}" - ); - } - } - - #[test] - fn external_urls_open_in_the_system_browser() { - let server = server_origin("http://127.0.0.1:7910/"); - for url in [ + OpenExternally, + ), + ("loopback ipv6", None, "http://[::1]:7910/", OpenExternally), + ( + "external https", + None, "https://example.com/", + OpenExternally, + ), + ( + "external lan ip", + None, "http://192.168.1.10/", + OpenExternally, + ), + ( + "external lookalike", + None, "https://localhost.evil.example/", - ] { - assert_eq!( - classify_navigation(&server, url), - Navigation::OpenExternally, - "{url}" - ); - } - } + OpenExternally, + ), + ("about blank", None, "about:blank", Allow), + ("data uri", None, "data:text/html,

hi

", Allow), + ("javascript uri", None, "javascript:void(0)", Allow), + ("unparseable", None, "not a url", Allow), + ("relative path", None, "/relative/path", Allow), + ("empty target", None, "", Allow), + ]; #[test] - fn non_http_and_unparseable_targets_are_left_to_the_webview() { - let server = server_origin("http://127.0.0.1:7910/"); - for url in [ - "about:blank", - "data:text/html,

hi

", - "not a url", - "/relative/path", - ] { - assert_eq!( - classify_navigation(&server, url), - Navigation::Allow, - "{url}" - ); + fn navigation_classification_cases() { + for &(label, server_url, target, expected) in CASES { + let server = Url::parse(server_url.unwrap_or(SERVER)) + .unwrap_or_else(|e| panic!("{label}: server URL parses: {e}")) + .origin(); + assert_eq!(classify_navigation(&server, target), expected, "{label}"); } } } diff --git a/crates/workshop/desktop/src/quit-tests.rs b/crates/workshop/desktop/src/quit-tests.rs index bb72b705..e8f005bc 100644 --- a/crates/workshop/desktop/src/quit-tests.rs +++ b/crates/workshop/desktop/src/quit-tests.rs @@ -1,12 +1,12 @@ -//! The quit ordering, and the shutdown-request half of quit against a +//! The quit menu accelerator and the shutdown-request half of quit against a //! stubbed gateway: the sidecar snapshot receives the authenticated //! `/shutdown`, a configured gateway is left running (no shutdown //! authority), and a missing server is a no-op. -use std::cell::RefCell; use std::time::Duration; -use super::{request_gateway_shutdown, stop_supervisor_then_request_shutdown}; +use super::{quit_accelerator, request_gateway_shutdown}; +use crate::test_support::{validated_gateway, workshop_server}; /// How long a test waits for the stubbed gateway to report the shutdown. const SHUTDOWN_OBSERVE_TIMEOUT: Duration = Duration::from_secs(10); @@ -16,62 +16,21 @@ const SHUTDOWN_OBSERVE_TIMEOUT: Duration = Duration::from_secs(10); /// the proof needs a wall-clock window. const NO_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(250); -#[test] -#[ignore = "runs only as a named child process"] -fn validated_gateway_fixture_process() { - workshop_server_api::fixtures::run_validated_gateway_fixture_process(); -} - -/// Starts the shared named-process Gateway stub in this test binary. -fn stubbed_gateway(expected_key: &str) -> workshop_server_api::fixtures::ValidatedGateway { - workshop_server_api::fixtures::ValidatedGateway::spawn_in( - expected_key, - "quit::tests::validated_gateway_fixture_process", - ) -} - -/// Spawns a Workshop fixture server configured against the gateway at -/// `port` - an explicit configuration, which alone grants no shutdown -/// authority. -fn workshop_server( - port: u16, - api_key: &str, -) -> (tempfile::TempDir, workshop_server_api::ServerHandle) { - let state_dir = tempfile::TempDir::new().expect("create Workshop state directory"); - let server = workshop_server_api::fixtures::spawn(workshop_server_api::Config { - gateway: workshop_server_api::GatewayConfig { - base_url: format!("http://127.0.0.1:{port}"), - api_key: api_key.to_owned(), - }, - server: workshop_server_api::ServerConfig { - bind: "127.0.0.1:0".to_owned(), - state_dir: state_dir.path().to_owned(), - }, - agents: workshop_server_api::AgentsConfig::default(), - }) - .expect("spawn Workshop fixture"); - (state_dir, server) -} +const ACCELERATOR_CASES: &[(&str, bool, Option<&str>)] = &[ + ("macOS keeps CmdOrCtrl+Q", true, Some("CmdOrCtrl+Q")), + ("Windows and Linux have no accelerator", false, None), +]; #[test] -fn quit_stops_the_supervisor_before_requesting_the_gateway_shutdown() { - let calls = RefCell::new(Vec::new()); - - stop_supervisor_then_request_shutdown( - || calls.borrow_mut().push("stop the supervisor"), - || calls.borrow_mut().push("request the gateway shutdown"), - ); - - assert_eq!( - calls.into_inner(), - ["stop the supervisor", "request the gateway shutdown"], - "a supervisor still running when the gateway stops would relaunch it" - ); +fn quit_accelerator_matches_platform() { + for &(label, macos, expected) in ACCELERATOR_CASES { + assert_eq!(quit_accelerator(macos), expected, "{label}"); + } } #[test] fn quit_requests_shutdown_from_the_current_sidecar_snapshot() { - let mut gateway = stubbed_gateway("quit-key"); + let mut gateway = validated_gateway("quit-key"); let (_state_dir, server) = workshop_server(gateway.port(), "quit-key"); let updater = server.gateway_updater(); let sidecar = gateway.validate("quit-key", 1_778_000_001, "2026-09-15T18:00:01Z"); @@ -90,7 +49,7 @@ fn quit_requests_shutdown_from_the_current_sidecar_snapshot() { #[test] fn quit_leaves_a_configured_gateway_running() { - let mut gateway = stubbed_gateway("lan-key"); + let mut gateway = validated_gateway("lan-key"); let (_state_dir, server) = workshop_server(gateway.port(), "lan-key"); request_gateway_shutdown(Some(server.gateway_updater())); diff --git a/crates/workshop/desktop/src/quit.rs b/crates/workshop/desktop/src/quit.rs index 14bd3d2e..d1afb8e2 100644 --- a/crates/workshop/desktop/src/quit.rs +++ b/crates/workshop/desktop/src/quit.rs @@ -1,5 +1,5 @@ -//! The quit-everything gesture, shared by the native menu's quit item and -//! the SPA's File > Exit row (the `quit` command): one +//! The window menu and quit-everything gesture, shared by the native menu's +//! quit item and the SPA's File > Exit row (the `quit` command): one //! stop-then-shutdown-then-exit path so the two cannot diverge. The path //! first stops the local-sidecar supervisor, so nothing relaunches the //! gateway this gesture is about to stop. When boot attached to or @@ -12,31 +12,98 @@ use std::sync::PoisonError; -use tauri::{AppHandle, Manager as _, Wry}; -use workshop_server_api::GatewayUpdater; +use tauri::menu::{MenuBuilder, MenuEvent, MenuItemBuilder, SubmenuBuilder}; +use tauri::{App, AppHandle, Manager as _, Wry}; +use workshop_server_api::{GatewayUpdater, ServerHandle}; -use crate::gateway::GatewaySupervisor; -use crate::{GatewaySupervisorSlot, ServerSlot}; +use crate::ServerSlot; -/// The quit ordering: stop the supervisor, then request the gateway's -/// shutdown. The reverse order races: a supervisor still running when the -/// gateway stops sees it missing and launches a replacement. -fn stop_supervisor_then_request_shutdown( - stop_supervisor: impl FnOnce(), - request_shutdown: impl FnOnce(), -) { - stop_supervisor(); - request_shutdown(); +/// The quit item's menu id, matched by the event handler. +const QUIT_MENU_ID: &str = "quit-runvil"; + +/// The quit item's accelerator. macOS keeps `CmdOrCtrl+Q`, the platform's +/// quit gesture. Windows and Linux have none: Ctrl+Q opens View in the SPA +/// (the Open View... row), so quitting there goes through the SPA's File > +/// Exit row and the `quit` command. +fn quit_accelerator(macos: bool) -> Option<&'static str> { + macos.then_some("CmdOrCtrl+Q") +} + +/// Builds and installs the app menu. A local sidecar makes the quit item +/// stop both products; a configured LAN Gateway makes it stop only the desktop app. +/// +/// # Errors +/// Returns an error when the menu cannot be built or installed. +pub(crate) fn install_menu(app: &App, has_sidecar: bool) -> tauri::Result<()> { + let label = if has_sidecar { + "Quit Runvil and Gateway" + } else { + "Quit Runvil" + }; + let mut quit = MenuItemBuilder::with_id(QUIT_MENU_ID, label); + if let Some(accelerator) = quit_accelerator(cfg!(target_os = "macos")) { + quit = quit.accelerator(accelerator); + } + let quit = quit.build(app)?; + // Setting a menu replaces the stock one wholesale, so macOS + // re-declares the default layout (app, File, Edit, View, Window) with + // the stock Quit swapped for the quit-everything item. Windows and + // Linux get the single File submenu; the Windows window is + // undecorated, so the menu bar is hidden there, and with no + // accelerator (Ctrl+Q opens View there) the SPA's File > Exit row is + // the gesture. + #[cfg(target_os = "macos")] + let menu = { + let app_menu = SubmenuBuilder::new(app, "Runvil") + .about(None) + .separator() + .services() + .separator() + .hide() + .hide_others() + .show_all() + .separator() + .item(&quit) + .build()?; + let file = SubmenuBuilder::new(app, "File").close_window().build()?; + let edit = SubmenuBuilder::new(app, "Edit") + .undo() + .redo() + .separator() + .cut() + .copy() + .paste() + .select_all() + .build()?; + let view = SubmenuBuilder::new(app, "View").fullscreen().build()?; + let window = SubmenuBuilder::new(app, "Window") + .minimize() + .maximize() + .separator() + .close_window() + .build()?; + MenuBuilder::new(app) + .items(&[&app_menu, &file, &edit, &view, &window]) + .build()? + }; + #[cfg(not(target_os = "macos"))] + let menu = { + let file = SubmenuBuilder::new(app, "File").item(&quit).build()?; + MenuBuilder::new(app).item(&file).build()? + }; + let _previous = app.set_menu(menu)?; + Ok(()) } -/// The supervisor-stop half: takes the local-sidecar supervisor out of its -/// slot and shuts it down, reporting a worker that panicked or outlived its -/// budget. The `RunEvent::Exit` handler then finds the slot empty. -fn stop_supervisor(app: &AppHandle) { - let supervisor = app - .try_state::() - .and_then(|slot| slot.lock().unwrap_or_else(PoisonError::into_inner).take()); - crate::report_supervisor_shutdown(supervisor.map(GatewaySupervisor::shutdown)); +/// Handles the quit item by running the shared stop-then-shutdown-then-exit +/// path (`quit_everything`), the same path the SPA's File > Exit row +/// invokes through the `quit` command. +pub(crate) fn handle_menu_event(app: &AppHandle, event: MenuEvent) { + let MenuEvent { id } = event; + if id != QUIT_MENU_ID { + return; + } + quit_everything(app); } /// The shutdown-request half: asks the server's current validated local @@ -54,22 +121,20 @@ fn request_gateway_shutdown(gateway: Option) { } } -/// The shared stop-then-shutdown-then-exit path: stop the supervisor, -/// request the local Gateway's shutdown, then exit the desktop app (the -/// `RunEvent::Exit` handler stops the in-process server). -pub(crate) fn quit_everything(app: &AppHandle) { - stop_supervisor_then_request_shutdown( - || stop_supervisor(app), - || { - let gateway = app.try_state::().and_then(|slot| { - slot.lock() - .unwrap_or_else(PoisonError::into_inner) - .as_ref() - .map(workshop_server_api::ServerHandle::gateway_updater) - }); - request_gateway_shutdown(gateway); - }, - ); +/// The shared stop-then-shutdown-then-exit path: stop the supervisor first so +/// nothing relaunches the gateway this gesture is about to stop, request the +/// local Gateway's shutdown, then exit the desktop app (the `RunEvent::Exit` +/// handler stops the in-process server and finds the supervisor slot empty). +fn quit_everything(app: &AppHandle) { + crate::stop_supervisor(app); + + let gateway = app.try_state::().and_then(|slot| { + slot.lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + .map(ServerHandle::gateway_updater) + }); + request_gateway_shutdown(gateway); app.exit(0); } diff --git a/crates/workshop/desktop/src/test_support.rs b/crates/workshop/desktop/src/test_support.rs new file mode 100644 index 00000000..ea48a9d5 --- /dev/null +++ b/crates/workshop/desktop/src/test_support.rs @@ -0,0 +1,38 @@ +#![cfg(test)] + +//! Shared unit-test fixtures for the desktop crate. + +use workshop_server_api::fixtures::ValidatedGateway; +use workshop_server_api::{AgentsConfig, Config, GatewayConfig, ServerConfig, ServerHandle}; + +/// Starts the shared named-process Gateway fixture in this test binary. +pub(crate) fn validated_gateway(expected_key: &str) -> ValidatedGateway { + ValidatedGateway::spawn_in( + expected_key, + "test_support::validated_gateway_fixture_process", + ) +} + +#[test] +#[ignore = "runs only as a named child process"] +fn validated_gateway_fixture_process() { + workshop_server_api::fixtures::run_validated_gateway_fixture_process(); +} + +/// Spawns a Workshop fixture server configured against the gateway at `port`. +pub(crate) fn workshop_server(port: u16, api_key: &str) -> (tempfile::TempDir, ServerHandle) { + let state_dir = tempfile::TempDir::new().expect("create Workshop state directory"); + let server = workshop_server_api::fixtures::spawn(Config { + gateway: GatewayConfig { + base_url: format!("http://127.0.0.1:{port}"), + api_key: api_key.to_owned(), + }, + server: ServerConfig { + bind: "127.0.0.1:0".to_owned(), + state_dir: state_dir.path().to_owned(), + }, + agents: AgentsConfig::default(), + }) + .expect("spawn Workshop fixture"); + (state_dir, server) +} diff --git a/crates/workshop/desktop/src/window_state-tests.rs b/crates/workshop/desktop/src/window_state-tests.rs index 8c52ab09..95da30eb 100644 --- a/crates/workshop/desktop/src/window_state-tests.rs +++ b/crates/workshop/desktop/src/window_state-tests.rs @@ -11,13 +11,10 @@ use tauri::{PhysicalPosition, PhysicalSize}; use super::{CurrentResponse, Debouncer, SavedResponse, WindowState, geometry, merge, usable}; -/// How long a test waits for the debouncer to deliver a coalesced save. const DELIVERY_TIMEOUT: Duration = Duration::from_secs(5); -/// The debounce a test runs with: long enough that a burst pushed in a -/// tight loop lands inside one window, short enough to keep the test fast. const TEST_DEBOUNCE: Duration = Duration::from_millis(150); -fn state(width: u32, height: u32, x: i32, y: i32, maximized: bool) -> WindowState { +const fn state(width: u32, height: u32, x: i32, y: i32, maximized: bool) -> WindowState { WindowState { width, height, @@ -27,75 +24,115 @@ fn state(width: u32, height: u32, x: i32, y: i32, maximized: bool) -> WindowStat } } -#[test] -fn physical_geometry_maps_to_logical_under_the_scale_factor() { - // A 200% display: the OS reports twice the logical pixels in every - // axis, and the file keeps logical pixels so a 100% display restores - // the same apparent size. - let mapped = geometry( - PhysicalSize::new(2560, 1600), - PhysicalPosition::new(200, -100), +type GeometryRow = (&'static str, (u32, u32), (i32, i32), f64, bool, WindowState); + +const GEOMETRY_CASES: &[GeometryRow] = &[ + ( + "200% scale", + (2560, 1600), + (200, -100), 2.0, false, - ); - assert_eq!(mapped, state(1280, 800, 100, -50, false)); - - // At 100% the mapping is the identity. - let identity = geometry( - PhysicalSize::new(1024, 768), - PhysicalPosition::new(40, 60), + state(1280, 800, 100, -50, false), + ), + ( + "100% identity", + (1024, 768), + (40, 60), 1.0, false, - ); - assert_eq!(identity, state(1024, 768, 40, 60, false)); - - // The maximized flag passes through untouched. - let maximized = geometry( - PhysicalSize::new(3840, 2100), - PhysicalPosition::new(-8, -8), + state(1024, 768, 40, 60, false), + ), + ( + "150% maximized", + (3840, 2100), + (-8, -8), 1.5, true, - ); - assert!(maximized.maximized); - assert_eq!((maximized.width, maximized.height), (2560, 1400)); + state(2560, 1400, -5, -5, true), + ), + ( + "125% fractional", + (1250, 1000), + (-125, 250), + 1.25, + false, + state(1000, 800, -100, 200, false), + ), + ( + "100% maximized", + (1920, 1080), + (0, 0), + 1.0, + true, + state(1920, 1080, 0, 0, true), + ), +]; + +const NORMAL: WindowState = state(1280, 800, 100, 50, false); +const MAXIMIZED_SCREEN: WindowState = state(2560, 1400, -8, -8, true); +const MOVED: WindowState = state(1000, 700, 300, 200, false); + +const MERGE_CASES: &[(&str, Option, WindowState, WindowState)] = &[ + ( + "maximize keeps normal", + Some(NORMAL), + MAXIMIZED_SCREEN, + state(1280, 800, 100, 50, true), + ), + ( + "unmaximize takes fresh", + Some(state(1280, 800, 100, 50, true)), + MOVED, + MOVED, + ), + ( + "maximize with no prior", + None, + MAXIMIZED_SCREEN, + MAXIMIZED_SCREEN, + ), + ("normal replaces prior", Some(NORMAL), MOVED, MOVED), + ("normal with no prior", None, NORMAL, NORMAL), +]; + +const USABLE_CASES: &[(&str, WindowState, bool)] = &[ + ("zero width", state(0, 800, 100, 50, false), false), + ("zero height", state(1280, 0, 100, 50, false), false), + ("zero maximized", state(0, 0, 0, 0, true), false), + ( + "nonzero offscreen", + state(1, 1, -32_000, -32_000, false), + true, + ), + ("nonzero maximized", state(1280, 800, 0, 0, true), true), +]; + +#[test] +fn physical_geometry_maps_to_logical_under_the_scale_factor() { + for &(label, (w, h), (x, y), scale, maximized, expected) in GEOMETRY_CASES { + let mapped = geometry( + PhysicalSize::new(w, h), + PhysicalPosition::new(x, y), + scale, + maximized, + ); + assert_eq!(mapped, expected, "{label}"); + } } #[test] fn a_maximized_snapshot_keeps_the_last_normal_rectangle() { - let normal = state(1280, 800, 100, 50, false); - let maximized_rect = state(2560, 1400, -8, -8, true); - - // Maximizing reports the screen rectangle; the file keeps the normal - // one so un-maximizing after a restart lands where the user left it. - assert_eq!( - merge(Some(normal), maximized_rect), - state(1280, 800, 100, 50, true) - ); - // Un-maximizing takes the fresh rectangle again. - let moved = state(1000, 700, 300, 200, false); - assert_eq!(merge(Some(state(1280, 800, 100, 50, true)), moved), moved); - // With nothing remembered, the maximized rectangle is all there is. - assert_eq!(merge(None, maximized_rect), maximized_rect); + for &(label, previous, current, expected) in MERGE_CASES { + assert_eq!(merge(previous, current), expected, "{label}"); + } } #[test] fn a_saved_geometry_with_an_empty_side_is_not_applied() { - assert!( - !usable(state(0, 800, 100, 50, false)), - "a zero width is empty" - ); - assert!( - !usable(state(1280, 0, 100, 50, false)), - "a zero height is empty" - ); - assert!( - !usable(state(0, 0, 0, 0, true)), - "a zero size is empty even when maximized" - ); - assert!( - usable(state(1, 1, -32_000, -32_000, false)), - "any nonzero size is usable; the position is checked against the monitors separately" - ); + for &(label, candidate, expected) in USABLE_CASES { + assert_eq!(usable(candidate), expected, "{label}"); + } } #[test] @@ -105,33 +142,24 @@ fn a_burst_of_geometry_events_coalesces_into_one_save() { sink.send(value).expect("the test holds the receiver"); }); - // A drag: many events inside the debounce window. for x in 0..50 { debouncer.push(state(1280, 800, x, 0, false)); } - let first = saved - .recv_timeout(DELIVERY_TIMEOUT) - .expect("the burst produces one save"); + let first = saved.recv_timeout(DELIVERY_TIMEOUT).expect("one save"); assert_eq!(first, state(1280, 800, 49, 0, false), "the last value wins"); assert!( saved.recv_timeout(TEST_DEBOUNCE * 3).is_err(), "no intermediate value reaches the sink" ); - // A second, separate gesture saves again. debouncer.push(state(1000, 700, 5, 5, true)); - let second = saved - .recv_timeout(DELIVERY_TIMEOUT) - .expect("a later gesture produces its own save"); + let second = saved.recv_timeout(DELIVERY_TIMEOUT).expect("later save"); assert_eq!(second, state(1000, 700, 5, 5, true)); } #[test] fn the_wire_shape_matches_the_server_fixture() { - // Copied from the server's `WindowState` (the kv 'window' value and - // the `PUT /workspace/file/window-state` body) and the - // `GET /workspace/file/current` answer. let request = serde_json::to_value(state(1280, 800, 100, -50, false)) .expect("a five-field struct of plain values serializes"); assert_eq!( diff --git a/crates/workshop/desktop/src/window_state.rs b/crates/workshop/desktop/src/window_state.rs index 7c60dca9..0513488c 100644 --- a/crates/workshop/desktop/src/window_state.rs +++ b/crates/workshop/desktop/src/window_state.rs @@ -16,6 +16,7 @@ use std::fmt; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; use std::sync::{Arc, Mutex, PoisonError}; +use std::thread; use std::time::Duration; use anyhow::Context as _; @@ -24,6 +25,7 @@ use tauri::{ Listener as _, LogicalPosition, LogicalSize, Manager as _, PhysicalPosition, PhysicalSize, WebviewWindow, WindowEvent, }; +use url::Url; /// How long a burst of resize and move events must go quiet before the /// geometry is written. A drag fires dozens of events a second; one save @@ -45,7 +47,7 @@ const VISIBILITY_INSET: i32 = 16; /// The window geometry as the workspace file keeps it: the server's /// `WindowState` mirrored field for field, in logical pixels. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub(crate) struct WindowState { +struct WindowState { /// Logical width. width: u32, /// Logical height. @@ -79,27 +81,15 @@ struct SavedResponse { /// routes. The server admits it as a native client: no `Origin`, a /// loopback `Host`, and `application/json` on the body it sends. #[derive(Debug, Clone)] -pub(crate) struct ServerClient { +struct ServerClient { /// The server's bound URL, the same one the window loads. - base_url: url::Url, + base_url: Url, /// The HTTP client, bounded by [`REQUEST_TIMEOUT`] per request. http: reqwest::Client, } impl ServerClient { - /// Builds a client against the server at `base_url`. - pub(crate) fn new(base_url: &url::Url) -> anyhow::Result { - let http = reqwest::Client::builder() - .timeout(REQUEST_TIMEOUT) - .build() - .context("build the window-state HTTP client")?; - Ok(Self { - base_url: base_url.clone(), - http, - }) - } - - fn endpoint(&self, path: &str) -> anyhow::Result { + fn endpoint(&self, path: &str) -> anyhow::Result { self.base_url .join(path) .with_context(|| format!("resolve {path} against {}", self.base_url)) @@ -123,32 +113,6 @@ impl ServerClient { .context("parse the current workspace file")?; Ok(body.window_state) } - - /// Saves `state` into the open workspace file within `timeout`. - /// Returns whether the server wrote it (`false` for an ephemeral - /// workspace). - async fn put_window_state( - &self, - state: WindowState, - timeout: Duration, - ) -> anyhow::Result { - let url = self.endpoint("workspace/file/window-state")?; - let response = self - .http - .put(url) - .timeout(timeout) - .json(&state) - .send() - .await - .context("send the window state")? - .error_for_status() - .context("the window-state save was refused")?; - let body: SavedResponse = response - .json() - .await - .context("parse the window-state answer")?; - Ok(body.saved) - } } /// The window's geometry in logical pixels, as the file keeps it. The OS @@ -194,7 +158,7 @@ struct Debouncer { } impl fmt::Debug for Debouncer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Debouncer").finish_non_exhaustive() } } @@ -203,9 +167,9 @@ impl Debouncer { /// Starts the worker. If the thread cannot be spawned the debouncer /// still exists and silently drops every value: geometry saves are /// best effort. - pub(crate) fn spawn(delay: Duration, mut sink: impl FnMut(T) + Send + 'static) -> Self { + fn spawn(delay: Duration, mut sink: impl FnMut(T) + Send + 'static) -> Self { let (events, receiver) = mpsc::channel::(); - let spawned = std::thread::Builder::new() + let spawned = thread::Builder::new() .name("window-state-saver".to_owned()) .spawn(move || { while let Ok(mut latest) = receiver.recv() { @@ -243,34 +207,36 @@ impl Debouncer { /// maximized snapshot can keep the normal rectangle. type LastGeometry = Arc>>; -/// Restores the open workspace's saved geometry onto `window` - meant to -/// run after the server is healthy and before `show()`, so the restore -/// never flashes. Returns what was applied, for the saver to remember. -/// A missing or unusable geometry leaves the window at its defaults. -pub(crate) fn restore(window: &WebviewWindow, client: &ServerClient) -> Option { - let state = match tauri::async_runtime::block_on(client.current()) { - Ok(Some(state)) => state, - Ok(None) => return None, +/// Restores the open workspace's saved geometry onto `window` (meant to run +/// after the server is healthy and before `show()`, so the restore never +/// flashes) and installs the debounced resize/move saver, close save, and +/// workspace-switch listener. Failures are reported and leave the window at +/// its defaults. +pub(crate) fn attach(window: &WebviewWindow, base_url: Url) { + let http = match reqwest::Client::builder() + .timeout(REQUEST_TIMEOUT) + .build() + .context("build the window-state HTTP client") + { + Ok(http) => http, + Err(error) => { + eprintln!("window geometry will not be restored or saved: {error:#}"); + return; + } + }; + let client = ServerClient { base_url, http }; + + let restored = match tauri::async_runtime::block_on(client.current()) { + Ok(Some(state)) => apply(window, state), + Ok(None) => None, Err(error) => { eprintln!( "could not read the saved window state; using the default geometry: {error:#}" ); - return None; + None } }; - apply(window, state) -} -/// Installs the save paths on `window`: a debounced save behind -/// [`SAVE_DEBOUNCE`] on resize and move, one best-effort save bounded by -/// [`CLOSE_SAVE_TIMEOUT`] when the window is asked to close, and a -/// listener that reapplies the geometry when the SPA switches workspace -/// files. `restored` is what [`restore`] applied, if anything. -pub(crate) fn spawn_saver( - window: &WebviewWindow, - client: ServerClient, - restored: Option, -) { let last: LastGeometry = Arc::new(Mutex::new(restored)); let saver = { let client = client.clone(); @@ -338,16 +304,6 @@ pub(crate) fn spawn_saver( /// remembers the result. `None` while minimized (the OS reports a /// nonsense position) or when the window cannot be read. fn remember(window: &WebviewWindow, last: &LastGeometry) -> Option { - let current = snapshot(window)?; - let mut last = last.lock().unwrap_or_else(PoisonError::into_inner); - let merged = merge(*last, current); - *last = Some(merged); - Some(merged) -} - -/// Reads the window's geometry in logical pixels. Runs on the event-loop -/// thread inside a window event, where the getters answer directly. -fn snapshot(window: &WebviewWindow) -> Option { let read = || -> tauri::Result> { if window.is_minimized()? { return Ok(None); @@ -359,19 +315,42 @@ fn snapshot(window: &WebviewWindow) -> Option { window.is_maximized()?, ))) }; - match read() { - Ok(state) => state, + let current = match read() { + Ok(state) => state?, Err(error) => { eprintln!("could not read the window geometry; skipping this save: {error}"); - None + return None; } - } + }; + let mut last = last.lock().unwrap_or_else(PoisonError::into_inner); + let merged = merge(*last, current); + *last = Some(merged); + Some(merged) } /// Writes `state` to the server within `timeout`, reporting a refusal /// and shrugging off an ephemeral workspace's `saved: false`. fn save(client: &ServerClient, state: WindowState, timeout: Duration) { - if let Err(error) = tauri::async_runtime::block_on(client.put_window_state(state, timeout)) { + let result = tauri::async_runtime::block_on(async { + let url = client.endpoint("workspace/file/window-state")?; + let response = client + .http + .put(url) + .timeout(timeout) + .json(&state) + .send() + .await + .context("send the window state")? + .error_for_status() + .context("the window-state save was refused")?; + let body: SavedResponse = response + .json() + .await + .context("parse the window-state answer")?; + let _ = body.saved; + Ok::<(), anyhow::Error>(()) + }); + if let Err(error) = result { eprintln!("could not save the window state: {error:#}"); } } @@ -403,7 +382,15 @@ fn apply(window: &WebviewWindow, state: WindowState) -> Option { let outcome = || -> tauri::Result { let mut applied = state; window.set_size(LogicalSize::new(state.width, state.height))?; - if corner_is_visible(window, state)? { + let probe: PhysicalPosition = LogicalPosition::new( + state.x.saturating_add(VISIBILITY_INSET), + state.y.saturating_add(VISIBILITY_INSET), + ) + .to_physical(window.scale_factor()?); + if window + .monitor_from_point(f64::from(probe.x), f64::from(probe.y))? + .is_some() + { window.set_position(LogicalPosition::new(state.x, state.y))?; } else { eprintln!( @@ -429,20 +416,6 @@ fn apply(window: &WebviewWindow, state: WindowState) -> Option { } } -/// Whether the saved top-left corner, inset a little so the title bar's -/// first pixels count, lands on a connected monitor. A monitor that was -/// unplugged since the save would otherwise swallow the window. -fn corner_is_visible(window: &WebviewWindow, state: WindowState) -> tauri::Result { - let probe: PhysicalPosition = LogicalPosition::new( - state.x.saturating_add(VISIBILITY_INSET), - state.y.saturating_add(VISIBILITY_INSET), - ) - .to_physical(window.scale_factor()?); - Ok(window - .monitor_from_point(f64::from(probe.x), f64::from(probe.y))? - .is_some()) -} - #[cfg(test)] #[path = "window_state-tests.rs"] mod tests; diff --git a/crates/workshop/gateway-discovery/src/cancellation.rs b/crates/workshop/gateway-discovery/src/cancellation.rs index 17268c38..8fc47c36 100644 --- a/crates/workshop/gateway-discovery/src/cancellation.rs +++ b/crates/workshop/gateway-discovery/src/cancellation.rs @@ -107,12 +107,12 @@ impl CancellationToken { #[cfg(test)] mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc; use std::time::Instant; + use super::*; + #[test] fn cancellation_wakes_an_operation_inside_the_effect_gate() { let cancellation = CancellationToken::new(); diff --git a/crates/workshop/gateway-discovery/src/file-tests.rs b/crates/workshop/gateway-discovery/src/file-tests.rs index e58efa52..6a5eb9f4 100644 --- a/crates/workshop/gateway-discovery/src/file-tests.rs +++ b/crates/workshop/gateway-discovery/src/file-tests.rs @@ -119,22 +119,55 @@ fn the_field_names_and_types_are_the_contract() { #[test] fn validation_rejects_the_three_attach_fields() { - let mut file = valid_file(); - assert_eq!(file.validation_error(), None); - file.port = 0; - assert_eq!(file.validation_error(), Some("port must not be 0")); - file = valid_file(); - file.api_key.clear(); - assert_eq!(file.validation_error(), Some("api_key must not be empty")); - file = valid_file(); - file.api_key = "key\r\ninjected: value".to_owned(); - assert_eq!( - file.validation_error(), - Some("api_key must not contain line breaks") - ); - file = valid_file(); - file.pid = 0; - assert_eq!(file.validation_error(), Some("pid must not be 0")); + const CASES: &[(&str, u16, &str, u32, Option<&str>)] = &[ + ( + "valid", + 8081, + "0e1f8f0d8f8c4e0f9a1c2b3d4e5f6a7b", + 4242, + None, + ), + ("zero port", 0, "key", 4242, Some("port must not be 0")), + ( + "empty api_key", + 8081, + "", + 4242, + Some("api_key must not be empty"), + ), + ( + "crlf in api_key", + 8081, + "key\r\ninjected: value", + 4242, + Some("api_key must not contain line breaks"), + ), + ( + "lf in api_key", + 8081, + "key\ninjected", + 4242, + Some("api_key must not contain line breaks"), + ), + ( + "cr in api_key", + 8081, + "key\rinjected", + 4242, + Some("api_key must not contain line breaks"), + ), + ("zero pid", 8081, "key", 0, Some("pid must not be 0")), + ]; + + for &(label, port, api_key, pid, expected) in CASES { + let file = GatewayDiscoveryFile { + port, + api_key: api_key.to_owned(), + pid, + ..valid_file() + }; + assert_eq!(file.validation_error(), expected, "{label}"); + } } #[test] diff --git a/crates/workshop/gateway-discovery/src/file.rs b/crates/workshop/gateway-discovery/src/file.rs index 309a8baf..473eb283 100644 --- a/crates/workshop/gateway-discovery/src/file.rs +++ b/crates/workshop/gateway-discovery/src/file.rs @@ -8,6 +8,8 @@ use std::path::Path; use serde::{Deserialize, Serialize}; +#[cfg(feature = "test-fixtures")] +use crate::atomic::write_atomic_owner_only; use crate::error::SidecarError; use crate::paths::gateway_discovery_file_path; @@ -93,11 +95,10 @@ impl GatewayDiscoveryFile { }); } }; - let file: GatewayDiscoveryFile = - serde_json::from_str(&raw).map_err(|source| SidecarError::Parse { - path: path.clone(), - source, - })?; + let file: GatewayDiscoveryFile = match serde_json::from_str(&raw) { + Ok(file) => file, + Err(source) => return Err(SidecarError::Parse { path, source }), + }; if let Some(reason) = file.validation_error() { return Err(SidecarError::Invalid { path, @@ -137,7 +138,7 @@ impl GatewayDiscoveryFile { })?; let bytes = serde_json::to_vec_pretty(self).map_err(|source| SidecarError::Serialize { source })?; - crate::atomic::write_atomic_owner_only(&path, &bytes) + write_atomic_owner_only(&path, &bytes) .map_err(|source| SidecarError::Write { path, source }) } } diff --git a/crates/workshop/gateway-discovery/src/health.rs b/crates/workshop/gateway-discovery/src/health.rs index 0b34aaed..093a57dd 100644 --- a/crates/workshop/gateway-discovery/src/health.rs +++ b/crates/workshop/gateway-discovery/src/health.rs @@ -5,18 +5,12 @@ //! The `Host` header is the bound loopback address, matching the gateway's //! loopback `Host` allowlist. -use std::io::{Read, Write as _}; +use std::io::{self, Read, Write as _}; use std::net::{SocketAddr, TcpStream}; use std::time::{Duration, Instant}; use crate::CancellationToken; -mod connection; - -#[cfg(test)] -use connection::probe_connection; -pub(crate) use connection::{probe_connection_cancellable, probe_connection_until}; - /// Delay between probes while the server comes up. const RETRY_INTERVAL: Duration = Duration::from_millis(25); @@ -70,7 +64,7 @@ pub enum ProbeError { operation: &'static str, /// The underlying I/O error. #[source] - source: std::io::Error, + source: io::Error, }, /// The status line was not a 200. @@ -81,18 +75,6 @@ pub enum ProbeError { }, } -/// The outcome of one bearer-key probe. -#[cfg(test)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum KeyProbe { - /// A 2xx answer: the key is accepted. - Accepted, - /// A non-2xx answer: the key is rejected (or the route is gone). - Rejected, - /// The server could not be queried at all. - Unreachable, -} - /// The combined readiness and authority proof for one connection. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum ConnectionProbe { @@ -106,6 +88,15 @@ pub(crate) enum ConnectionProbe { KeyRejected, } +/// One coherent proof attempt over one TCP connection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ConnectionAttempt { + Accepted, + HealthFailed, + KeyRejected, + ProofIncomplete, +} + /// Connects within the one absolute attempt deadline. fn connect_until(address: &SocketAddr, deadline: Instant) -> Result { let timeout = remaining(deadline)?; @@ -138,7 +129,7 @@ fn remaining(deadline: Instant) -> Result { .filter(|remaining| !remaining.is_zero()) .ok_or_else(|| ProbeError::Io { operation: "validation deadline elapsed", - source: std::io::Error::from(std::io::ErrorKind::TimedOut), + source: io::Error::from(io::ErrorKind::TimedOut), }) } @@ -239,11 +230,7 @@ fn wait_for_health_cancellable_with_start( fn probe_health_until(address: &str, deadline: Instant) -> Result<(), ProbeError> { let head = request_head_until(address, "GET", "/health", None, deadline)?; - let status_ok = head - .split_whitespace() - .nth(1) - .is_some_and(|code| code == "200"); - if status_ok { + if response_status(&head) == Some(200) { return Ok(()); } Err(ProbeError::UnexpectedStatus { @@ -251,27 +238,6 @@ fn probe_health_until(address: &str, deadline: Instant) -> Result<(), ProbeError }) } -/// Issues one `GET {path}` presenting `api_key` as the bearer token and -/// classifies the answer. -#[cfg(test)] -fn probe_bearer(address: &str, path: &str, api_key: &str) -> KeyProbe { - match request_head(address, "GET", path, Some(api_key)) { - Ok(head) => { - let accepted = head - .split_whitespace() - .nth(1) - .and_then(|code| code.parse::().ok()) - .is_some_and(|code| (200..300).contains(&code)); - if accepted { - KeyProbe::Accepted - } else { - KeyProbe::Rejected - } - } - Err(_) => KeyProbe::Unreachable, - } -} - /// One HTTP/1.0 request returning the response head. The `Host` header /// is set to the bound address, never `localhost`: the gateway's loopback /// `Host` allowlist refuses anything else. @@ -281,17 +247,13 @@ pub(crate) fn request_head( path: &str, bearer: Option<&str>, ) -> Result { - request_head_with_timeout(address, method, path, bearer, ATTEMPT_TIMEOUT) -} - -fn request_head_with_timeout( - address: &str, - method: &str, - path: &str, - bearer: Option<&str>, - timeout: Duration, -) -> Result { - request_head_until(address, method, path, bearer, Instant::now() + timeout) + request_head_until( + address, + method, + path, + bearer, + Instant::now() + ATTEMPT_TIMEOUT, + ) } pub(crate) fn request_head_until( @@ -305,30 +267,235 @@ pub(crate) fn request_head_until( .parse::() .map_err(|source| ProbeError::Io { operation: "parse the loopback address", - source: std::io::Error::new(std::io::ErrorKind::InvalidInput, source), + source: io::Error::new(io::ErrorKind::InvalidInput, source), })?; let mut stream = connect_until(&socket, deadline)?; - let mut request = format!("{method} {path} HTTP/1.0\r\nHost: {address}\r\n"); + write_http_request( + &mut stream, + format!("{method} {path} HTTP/1.0\r\nHost: {address}\r\n"), + bearer, + "write the request", + deadline, + )?; + let mut buffer = [0u8; 256]; + configure_stream(&stream, deadline)?; + let read = stream.read(&mut buffer).map_err(|source| ProbeError::Io { + operation: "read the status line", + source, + })?; + Ok(String::from_utf8_lossy(&buffer[..read]).into_owned()) +} + +/// Proves one connection within the caller's absolute deadline. +pub(crate) fn probe_connection_until( + address: &str, + bearer_path: &str, + bearer: &str, + deadline: Instant, +) -> ConnectionProbe { + probe_connection_with_probe( + address, + bearer_path, + bearer, + deadline, + &CancellationToken::new(), + ATTEMPT_TIMEOUT, + probe_connection_once, + ) +} + +/// Proves one connection while observing supervisor cancellation. +pub(crate) fn probe_connection_cancellable( + address: &str, + bearer_path: &str, + bearer: &str, + health_budget: Duration, + cancellation: &CancellationToken, +) -> ConnectionProbe { + probe_connection_with_probe( + address, + bearer_path, + bearer, + Instant::now() + health_budget, + cancellation, + CANCELLABLE_ATTEMPT_TIMEOUT, + probe_connection_once, + ) +} + +fn probe_connection_with_probe( + address: &str, + bearer_path: &str, + bearer: &str, + deadline: Instant, + cancellation: &CancellationToken, + attempt_timeout: Duration, + mut probe: impl FnMut(&str, &str, &str, Instant) -> ConnectionAttempt, +) -> ConnectionProbe { + loop { + let attempt_deadline = (Instant::now() + attempt_timeout).min(deadline); + let Some(attempt) = + cancellation.run_if_active(|| probe(address, bearer_path, bearer, attempt_deadline)) + else { + return ConnectionProbe::Canceled; + }; + match attempt { + ConnectionAttempt::Accepted => return ConnectionProbe::Accepted, + ConnectionAttempt::KeyRejected => return ConnectionProbe::KeyRejected, + ConnectionAttempt::ProofIncomplete => return ConnectionProbe::HealthFailed, + ConnectionAttempt::HealthFailed if Instant::now() >= deadline => { + return ConnectionProbe::HealthFailed; + } + ConnectionAttempt::HealthFailed if cancellation.wait_timeout(RETRY_INTERVAL) => { + return ConnectionProbe::Canceled; + } + ConnectionAttempt::HealthFailed => {} + } + } +} + +/// Checks health and bearer acceptance over one socket. Once health has +/// succeeded, any socket loss fails the proof instead of reconnecting to a +/// potentially different endpoint. +fn probe_connection_once( + address: &str, + bearer_path: &str, + bearer: &str, + deadline: Instant, +) -> ConnectionAttempt { + let Ok(socket) = address.parse::() else { + return ConnectionAttempt::HealthFailed; + }; + let Ok(mut stream) = connect_until(&socket, deadline) else { + return ConnectionAttempt::HealthFailed; + }; + if write_request(&mut stream, address, "/health", None, false, deadline).is_err() { + return ConnectionAttempt::HealthFailed; + } + let Some(health_head) = read_framed_response_head(&mut stream, deadline) else { + return ConnectionAttempt::HealthFailed; + }; + if response_status(&health_head) != Some(200) { + return ConnectionAttempt::HealthFailed; + } + if write_request( + &mut stream, + address, + bearer_path, + Some(bearer), + true, + deadline, + ) + .is_err() + { + return ConnectionAttempt::ProofIncomplete; + } + let Some(bearer_head) = read_framed_response_head(&mut stream, deadline) else { + return ConnectionAttempt::ProofIncomplete; + }; + if response_status(&bearer_head).is_some_and(|code| (200..300).contains(&code)) { + ConnectionAttempt::Accepted + } else { + ConnectionAttempt::KeyRejected + } +} + +/// Writes one GET request, retaining or closing the connection as directed. +fn write_request( + stream: &mut TcpStream, + address: &str, + path: &str, + bearer: Option<&str>, + close: bool, + deadline: Instant, +) -> Result<(), ProbeError> { + let connection = if close { "close" } else { "keep-alive" }; + write_http_request( + stream, + format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: {connection}\r\n"), + bearer, + "write the validation request", + deadline, + ) +} + +/// Appends optional bearer authorization and the terminating blank line, +/// then writes the request within `deadline`. +fn write_http_request( + stream: &mut TcpStream, + mut request: String, + bearer: Option<&str>, + operation: &'static str, + deadline: Instant, +) -> Result<(), ProbeError> { if let Some(key) = bearer { request.push_str("Authorization: Bearer "); request.push_str(key); request.push_str("\r\n"); } request.push_str("\r\n"); - configure_stream(&stream, deadline)?; + configure_stream(stream, deadline)?; stream .write_all(request.as_bytes()) - .map_err(|source| ProbeError::Io { - operation: "write the request", - source, - })?; - let mut buffer = [0u8; 256]; - configure_stream(&stream, deadline)?; - let read = stream.read(&mut buffer).map_err(|source| ProbeError::Io { - operation: "read the status line", - source, + .map_err(|source| ProbeError::Io { operation, source }) +} + +/// Reads one response head and drains its fixed-length body so the next +/// response starts at a framing boundary on the same socket. +fn read_framed_response_head(stream: &mut TcpStream, deadline: Instant) -> Option { + let mut response = Vec::with_capacity(512); + let header_end = loop { + if let Some(end) = response.windows(4).position(|bytes| bytes == b"\r\n\r\n") { + break end + 4; + } + if response.len() >= RESPONSE_HEAD_LIMIT { + return None; + } + let mut buffer = [0_u8; 512]; + let available = RESPONSE_HEAD_LIMIT - response.len(); + let chunk = available.min(buffer.len()); + configure_stream(stream, deadline).ok()?; + let read = stream.read(&mut buffer[..chunk]).ok()?; + if read == 0 { + return None; + } + response.extend_from_slice(&buffer[..read]); + }; + let head = String::from_utf8_lossy(&response[..header_end]); + let content_length: usize = head.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().ok()) + .flatten() })?; - Ok(String::from_utf8_lossy(&buffer[..read]).into_owned()) + if content_length > RESPONSE_BODY_LIMIT { + return None; + } + let body_already_read = response.len() - header_end; + if body_already_read > content_length { + return None; + } + if body_already_read < content_length { + let mut remaining = content_length - body_already_read; + let mut buffer = [0_u8; 512]; + while remaining > 0 { + let chunk_len = remaining.min(buffer.len()); + configure_stream(stream, deadline).ok()?; + let read = stream.read(&mut buffer[..chunk_len]).ok()?; + if read == 0 { + return None; + } + remaining -= read; + } + } + Some(head.into_owned()) +} + +/// Parses the three-digit response status. +pub(crate) fn response_status(head: &str) -> Option { + head.split_whitespace() + .nth(1) + .and_then(|code| code.parse::().ok()) } #[cfg(test)] diff --git a/crates/workshop/gateway-discovery/src/health/connection.rs b/crates/workshop/gateway-discovery/src/health/connection.rs deleted file mode 100644 index 51439221..00000000 --- a/crates/workshop/gateway-discovery/src/health/connection.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! The one-connection health and bearer proof. - -use std::io::{Read, Write as _}; -use std::net::{SocketAddr, TcpStream}; -use std::time::{Duration, Instant}; - -use super::{ - ATTEMPT_TIMEOUT, CANCELLABLE_ATTEMPT_TIMEOUT, ConnectionProbe, ProbeError, RESPONSE_BODY_LIMIT, - RESPONSE_HEAD_LIMIT, RETRY_INTERVAL, configure_stream, connect_until, -}; -use crate::CancellationToken; - -/// Proves that one address is healthy and accepts the presented bearer. -/// Both requests use one TCP connection, so authority cannot come from a -/// listener that replaced the endpoint after the health response. -#[cfg(test)] -pub(super) fn probe_connection( - address: &str, - bearer_path: &str, - bearer: &str, - health_budget: Duration, -) -> ConnectionProbe { - probe_connection_until(address, bearer_path, bearer, Instant::now() + health_budget) -} - -/// Proves one connection within the caller's absolute deadline. -pub(crate) fn probe_connection_until( - address: &str, - bearer_path: &str, - bearer: &str, - deadline: Instant, -) -> ConnectionProbe { - probe_connection_with( - address, - bearer_path, - bearer, - deadline, - &CancellationToken::new(), - ATTEMPT_TIMEOUT, - ) -} - -/// Proves one connection while observing supervisor cancellation. -pub(crate) fn probe_connection_cancellable( - address: &str, - bearer_path: &str, - bearer: &str, - health_budget: Duration, - cancellation: &CancellationToken, -) -> ConnectionProbe { - probe_connection_with( - address, - bearer_path, - bearer, - Instant::now() + health_budget, - cancellation, - CANCELLABLE_ATTEMPT_TIMEOUT, - ) -} - -fn probe_connection_with( - address: &str, - bearer_path: &str, - bearer: &str, - deadline: Instant, - cancellation: &CancellationToken, - attempt_timeout: Duration, -) -> ConnectionProbe { - probe_connection_with_probe( - address, - bearer_path, - bearer, - deadline, - cancellation, - attempt_timeout, - probe_connection_once, - ) -} - -pub(super) fn probe_connection_with_probe( - address: &str, - bearer_path: &str, - bearer: &str, - deadline: Instant, - cancellation: &CancellationToken, - attempt_timeout: Duration, - mut probe: impl FnMut(&str, &str, &str, Instant) -> ConnectionAttempt, -) -> ConnectionProbe { - loop { - let attempt_deadline = (Instant::now() + attempt_timeout).min(deadline); - let Some(attempt) = - cancellation.run_if_active(|| probe(address, bearer_path, bearer, attempt_deadline)) - else { - return ConnectionProbe::Canceled; - }; - match attempt { - ConnectionAttempt::Accepted => return ConnectionProbe::Accepted, - ConnectionAttempt::KeyRejected => return ConnectionProbe::KeyRejected, - ConnectionAttempt::ProofIncomplete => return ConnectionProbe::HealthFailed, - ConnectionAttempt::HealthFailed if Instant::now() >= deadline => { - return ConnectionProbe::HealthFailed; - } - ConnectionAttempt::HealthFailed if cancellation.wait_timeout(RETRY_INTERVAL) => { - return ConnectionProbe::Canceled; - } - ConnectionAttempt::HealthFailed => {} - } - } -} - -/// One coherent proof attempt over one TCP connection. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum ConnectionAttempt { - Accepted, - HealthFailed, - KeyRejected, - ProofIncomplete, -} - -/// Checks health and bearer acceptance over one socket. Once health has -/// succeeded, any socket loss fails the proof instead of reconnecting to a -/// potentially different endpoint. -pub(super) fn probe_connection_once( - address: &str, - bearer_path: &str, - bearer: &str, - deadline: Instant, -) -> ConnectionAttempt { - let Ok(socket) = address.parse::() else { - return ConnectionAttempt::HealthFailed; - }; - let Ok(mut stream) = connect_until(&socket, deadline) else { - return ConnectionAttempt::HealthFailed; - }; - if write_request(&mut stream, address, "/health", None, false, deadline).is_err() { - return ConnectionAttempt::HealthFailed; - } - let Ok(health_head) = read_framed_response_head(&mut stream, deadline) else { - return ConnectionAttempt::HealthFailed; - }; - if response_status(&health_head) != Some(200) { - return ConnectionAttempt::HealthFailed; - } - if write_request( - &mut stream, - address, - bearer_path, - Some(bearer), - true, - deadline, - ) - .is_err() - { - return ConnectionAttempt::ProofIncomplete; - } - let Ok(bearer_head) = read_framed_response_head(&mut stream, deadline) else { - return ConnectionAttempt::ProofIncomplete; - }; - if response_status(&bearer_head).is_some_and(|code| (200..300).contains(&code)) { - ConnectionAttempt::Accepted - } else { - ConnectionAttempt::KeyRejected - } -} - -/// Writes one GET request, retaining or closing the connection as directed. -fn write_request( - stream: &mut TcpStream, - address: &str, - path: &str, - bearer: Option<&str>, - close: bool, - deadline: Instant, -) -> Result<(), ProbeError> { - let connection = if close { "close" } else { "keep-alive" }; - let mut request = - format!("GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: {connection}\r\n"); - if let Some(key) = bearer { - request.push_str("Authorization: Bearer "); - request.push_str(key); - request.push_str("\r\n"); - } - request.push_str("\r\n"); - configure_stream(stream, deadline)?; - stream - .write_all(request.as_bytes()) - .map_err(|source| ProbeError::Io { - operation: "write the validation request", - source, - }) -} - -/// Reads one response head and drains its fixed-length body so the next -/// response starts at a framing boundary on the same socket. -fn read_framed_response_head( - stream: &mut TcpStream, - deadline: Instant, -) -> Result { - let mut response = Vec::with_capacity(512); - let header_end = loop { - if let Some(end) = response.windows(4).position(|bytes| bytes == b"\r\n\r\n") { - break end + 4; - } - if response.len() >= RESPONSE_HEAD_LIMIT { - return Err(ProbeError::UnexpectedStatus { - status_line: "".to_owned(), - }); - } - let mut buffer = [0_u8; 512]; - let available = RESPONSE_HEAD_LIMIT - response.len(); - let chunk = available.min(buffer.len()); - configure_stream(stream, deadline)?; - let read = stream - .read(&mut buffer[..chunk]) - .map_err(|source| ProbeError::Io { - operation: "read the validation response", - source, - })?; - if read == 0 { - return Err(ProbeError::Io { - operation: "read the validation response", - source: std::io::Error::from(std::io::ErrorKind::UnexpectedEof), - }); - } - response.extend_from_slice(&buffer[..read]); - }; - let head = String::from_utf8_lossy(&response[..header_end]).into_owned(); - let content_length = - response_content_length(&head).ok_or_else(|| ProbeError::UnexpectedStatus { - status_line: "".to_owned(), - })?; - if content_length > RESPONSE_BODY_LIMIT { - return Err(ProbeError::UnexpectedStatus { - status_line: "".to_owned(), - }); - } - let body_already_read = response.len() - header_end; - if body_already_read > content_length { - return Err(ProbeError::UnexpectedStatus { - status_line: "".to_owned(), - }); - } - if body_already_read < content_length { - let mut remaining = content_length - body_already_read; - let mut buffer = [0_u8; 512]; - while remaining > 0 { - let chunk_len = remaining.min(buffer.len()); - configure_stream(stream, deadline)?; - let read = stream - .read(&mut buffer[..chunk_len]) - .map_err(|source| ProbeError::Io { - operation: "read the validation response body", - source, - })?; - if read == 0 { - return Err(ProbeError::Io { - operation: "read the validation response body", - source: std::io::Error::from(std::io::ErrorKind::UnexpectedEof), - }); - } - remaining -= read; - } - } - Ok(head) -} - -/// Parses a decimal Content-Length from a response head. -fn response_content_length(head: &str) -> Option { - head.lines().find_map(|line| { - let (name, value) = line.split_once(':')?; - name.eq_ignore_ascii_case("content-length") - .then(|| value.trim().parse().ok()) - .flatten() - }) -} - -/// Parses the three-digit response status. -fn response_status(head: &str) -> Option { - head.split_whitespace() - .nth(1) - .and_then(|code| code.parse::().ok()) -} diff --git a/crates/workshop/gateway-discovery/src/health/tests-connection.rs b/crates/workshop/gateway-discovery/src/health/tests-connection.rs index 711c394c..c77b5132 100644 --- a/crates/workshop/gateway-discovery/src/health/tests-connection.rs +++ b/crates/workshop/gateway-discovery/src/health/tests-connection.rs @@ -1,35 +1,22 @@ //! Unit tests for the one-connection health and bearer proof. use super::*; - -use super::super::connection::{ - ConnectionAttempt, probe_connection_once, probe_connection_with_probe, -}; +use crate::test_support::spawn_tcp_fixture; #[test] fn connection_proof_cannot_mix_health_and_bearer_across_endpoints() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind replacement fixture"); - let address = listener - .local_addr() - .expect("replacement fixture address") - .to_string(); let (accepted, received) = mpsc::channel(); - std::thread::spawn(move || { + let address = spawn_tcp_fixture(move |listener| { let (mut health, _) = listener.accept().expect("accept health probe"); let mut buffer = [0_u8; 1024]; let read = health.read(&mut buffer).expect("read health probe"); - assert!( - String::from_utf8_lossy(&buffer[..read]).starts_with("GET /health "), - "the first endpoint receives health" - ); + assert!(String::from_utf8_lossy(&buffer[..read]).starts_with("GET /health ")); health .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") .expect("answer health"); drop(health); - listener - .set_nonblocking(true) - .expect("make replacement observation bounded"); + listener.set_nonblocking(true).expect("nonblocking"); let deadline = Instant::now() + Duration::from_millis(500); let mut connection_count = 1; while Instant::now() < deadline { @@ -39,12 +26,9 @@ fn connection_proof_cannot_mix_health_and_bearer_across_endpoints() { let read = bearer.read(&mut buffer).expect("read bearer probe"); assert!( String::from_utf8_lossy(&buffer[..read]) - .contains("Authorization: Bearer accepted\r\n"), - "the replacement endpoint accepts the bearer" + .contains("Authorization: Bearer accepted\r\n") ); - bearer - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") - .expect("answer bearer"); + let _ = bearer.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"); break; } Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { @@ -53,10 +37,9 @@ fn connection_proof_cannot_mix_health_and_bearer_across_endpoints() { Err(error) => panic!("observe replacement connection: {error}"), } } - accepted - .send(connection_count) - .expect("report accepted connections"); - }); + accepted.send(connection_count).expect("report connections"); + }) + .to_string(); assert_eq!( probe_connection( @@ -65,166 +48,134 @@ fn connection_proof_cannot_mix_health_and_bearer_across_endpoints() { "accepted", Duration::from_millis(250) ), - ConnectionProbe::HealthFailed, - "one capability cannot combine health from one socket with authority from another" + ConnectionProbe::HealthFailed ); assert_eq!( received .recv_timeout(Duration::from_secs(2)) - .expect("fixture reports its connection count"), - 1, - "validation never reconnects after health succeeds" + .expect("count"), + 1 ); } #[test] -fn a_real_connect_attempt_obeys_one_absolute_deadline() { - let started = Instant::now(); - let result = probe_connection_once( - "192.0.2.1:9", - "/v1/models", - "key", - Instant::now() + Duration::from_millis(100), - ); - - assert_eq!(result, ConnectionAttempt::HealthFailed); - assert!( - started.elapsed() < Duration::from_millis(500), - "connect_timeout bounds a stalled or unreachable route" - ); -} - -#[test] -fn slow_drip_response_head_cannot_refresh_the_attempt_budget() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow-head fixture"); - let address = listener - .local_addr() - .expect("slow-head address") - .to_string(); - std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept slow-head probe"); - let mut request = [0_u8; 1024]; - let _ = stream.read(&mut request); - for byte in b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}" { - if stream.write_all(&[*byte]).is_err() { - return; - } - std::thread::sleep(Duration::from_millis(20)); - } - }); - - let started = Instant::now(); - let result = probe_connection_once( - &address, - "/v1/models", - "key", - Instant::now() + CANCELLABLE_ATTEMPT_TIMEOUT, - ); - - assert_eq!(result, ConnectionAttempt::HealthFailed); - assert!( - started.elapsed() < Duration::from_millis(500), - "one absolute deadline bounds a slow-drip response head" - ); -} - -#[test] -fn slow_drip_response_body_cannot_refresh_the_attempt_budget() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow-body fixture"); - let address = listener - .local_addr() - .expect("slow-body address") - .to_string(); - std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept slow-body probe"); - let mut request = [0_u8; 1024]; - let _ = stream.read(&mut request); - if stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 16\r\n\r\n") - .is_err() - { - return; - } - for byte in b"0123456789abcdef" { - if stream.write_all(&[*byte]).is_err() { - return; - } - std::thread::sleep(Duration::from_millis(20)); - } - }); - - let started = Instant::now(); - let result = probe_connection_once( - &address, - "/v1/models", - "key", - Instant::now() + CANCELLABLE_ATTEMPT_TIMEOUT, - ); - - assert_eq!(result, ConnectionAttempt::HealthFailed); - assert!( - started.elapsed() < Duration::from_millis(500), - "one absolute deadline bounds a slow-drip response body" - ); -} - -#[test] -fn an_unbounded_declared_body_is_rejected_without_draining() { - let response = format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", - RESPONSE_BODY_LIMIT + 1 - ); - let listener = TcpListener::bind("127.0.0.1:0").expect("bind oversized-body fixture"); - let address = listener - .local_addr() - .expect("oversized-body address") - .to_string(); - std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept oversized-body probe"); - let mut request = [0_u8; 1024]; - let _ = stream.read(&mut request); - let _ = stream.write_all(response.as_bytes()); - std::thread::sleep(Duration::from_secs(1)); - }); - - let started = Instant::now(); - let result = probe_connection_once( - &address, - "/v1/models", - "key", - Instant::now() + CANCELLABLE_ATTEMPT_TIMEOUT, - ); +fn unhealthy_and_bounded_responses_fail_within_deadline() { + #[derive(Clone, Copy)] + enum Scenario { + UnreachableRoute, + SlowDripHead, + SlowDripBody, + OversizedDeclaredBody, + OversizedHead, + TruncatedBodyEof, + Non2xxHealth, + } + const CASES: &[(&str, Scenario, u64)] = &[ + ("stalled connect", Scenario::UnreachableRoute, 500), + ("slow-drip head", Scenario::SlowDripHead, 500), + ("slow-drip body", Scenario::SlowDripBody, 500), + ( + "oversized declared body", + Scenario::OversizedDeclaredBody, + 250, + ), + ("oversized response head", Scenario::OversizedHead, 250), + ("truncated declared body", Scenario::TruncatedBodyEof, 250), + ("non-2xx health response", Scenario::Non2xxHealth, 250), + ]; + + for &(label, scenario, max_ms) in CASES { + let address = match scenario { + Scenario::UnreachableRoute => "192.0.2.1:9".to_owned(), + _ => spawn_tcp_fixture(move |listener| { + let (mut stream, _) = listener.accept().expect("accept probe"); + let mut request = [0_u8; 1024]; + let _ = stream.read(&mut request); + match scenario { + Scenario::UnreachableRoute => unreachable!(), + Scenario::SlowDripHead => { + for byte in b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}" { + if stream.write_all(&[*byte]).is_err() { + return; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + Scenario::SlowDripBody => { + if stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 16\r\n\r\n") + .is_err() + { + return; + } + for byte in b"0123456789abcdef" { + if stream.write_all(&[*byte]).is_err() { + return; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + Scenario::OversizedDeclaredBody => { + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", + RESPONSE_BODY_LIMIT + 1 + ); + let _ = stream.write_all(resp.as_bytes()); + std::thread::sleep(Duration::from_secs(1)); + } + Scenario::OversizedHead => { + let _ = stream.write_all(&vec![b'X'; RESPONSE_HEAD_LIMIT + 1]); + std::thread::sleep(Duration::from_secs(1)); + } + Scenario::TruncatedBodyEof => { + let _ = + stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 16\r\n\r\nshort"); + } + Scenario::Non2xxHealth => { + let _ = stream.write_all( + b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n", + ); + } + } + }) + .to_string(), + }; - assert_eq!(result, ConnectionAttempt::HealthFailed); - assert!( - started.elapsed() < Duration::from_millis(250), - "an oversized declared body is rejected before its bytes arrive" - ); + let started = Instant::now(); + let result = probe_connection_once( + &address, + "/v1/models", + "key", + Instant::now() + CANCELLABLE_ATTEMPT_TIMEOUT, + ); + assert_eq!(result, ConnectionAttempt::HealthFailed, "{label}"); + assert!( + started.elapsed() < Duration::from_millis(max_ms), + "{label}: elapsed {:?} exceeded {max_ms}ms", + started.elapsed() + ); + } } #[test] fn cancellation_joins_a_real_slow_drip_probe_without_retrying() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind canceled-drip fixture"); - let address = listener - .local_addr() - .expect("canceled-drip address") - .to_string(); let connections = Arc::new(AtomicUsize::new(0)); let server_connections = Arc::clone(&connections); let (entered, blocked) = mpsc::channel(); - std::thread::spawn(move || { + let address = spawn_tcp_fixture(move |listener| { let (mut stream, _) = listener.accept().expect("accept canceled-drip probe"); server_connections.fetch_add(1, Ordering::SeqCst); let mut request = [0_u8; 1024]; let _ = stream.read(&mut request); - entered.send(()).expect("announce real slow-drip probe"); + entered.send(()).expect("announce slow-drip probe"); for byte in b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}" { if stream.write_all(&[*byte]).is_err() { return; } std::thread::sleep(Duration::from_millis(20)); } - }); + }) + .to_string(); let cancellation = CancellationToken::new(); let worker_cancellation = cancellation.clone(); let worker = std::thread::spawn(move || { @@ -238,22 +189,16 @@ fn cancellation_joins_a_real_slow_drip_probe_without_retrying() { }); blocked .recv_timeout(Duration::from_secs(1)) - .expect("the real probe begins its slow response"); + .expect("probe started"); let started = Instant::now(); cancellation.cancel(); - let result = worker.join().expect("the real probe worker joins"); - - assert_eq!(result, ConnectionProbe::Canceled); - assert!( - started.elapsed() < Duration::from_millis(500), - "the attempt deadline bounds joined cancellation during real I/O" - ); assert_eq!( - connections.load(Ordering::SeqCst), - 1, - "cancellation starts no later network probe" + worker.join().expect("worker joins"), + ConnectionProbe::Canceled ); + assert!(started.elapsed() < Duration::from_millis(500)); + assert_eq!(connections.load(Ordering::SeqCst), 1); } #[test] @@ -273,9 +218,7 @@ fn cancellation_at_validation_probe_start_prevents_the_probe() { &worker_cancellation, CANCELLABLE_ATTEMPT_TIMEOUT, |_, _, _, _| { - entered - .send(()) - .expect("announce validation probe boundary"); + entered.send(()).expect("announce probe boundary"); if probe_cancellation.wait_timeout(Duration::from_secs(30)) { ConnectionAttempt::HealthFailed } else { @@ -287,15 +230,12 @@ fn cancellation_at_validation_probe_start_prevents_the_probe() { }); blocked .recv_timeout(Duration::from_secs(1)) - .expect("validation pauses immediately before probe admission"); + .expect("paused"); cancellation.cancel(); - let result = worker.join().expect("validation worker joins"); - - assert_eq!(result, ConnectionProbe::Canceled); assert_eq!( - probes.load(Ordering::SeqCst), - 0, - "no validation probe starts after cancellation returns" + worker.join().expect("worker joins"), + ConnectionProbe::Canceled ); + assert_eq!(probes.load(Ordering::SeqCst), 0); } diff --git a/crates/workshop/gateway-discovery/src/health/tests.rs b/crates/workshop/gateway-discovery/src/health/tests.rs index 3928c23e..4d3cacc4 100644 --- a/crates/workshop/gateway-discovery/src/health/tests.rs +++ b/crates/workshop/gateway-discovery/src/health/tests.rs @@ -1,94 +1,55 @@ //! Unit tests for the health wait and the bearer probe. -use super::*; - -use std::net::TcpListener; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, mpsc}; +use super::*; +use crate::test_support::{canned_gateway, spawn_tcp_fixture}; + #[path = "tests-connection.rs"] mod connection; -/// Answers every connection with a canned response until the test -/// stops it. -fn spawn_stub_server(response: &'static [u8]) -> String { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind stub server"); - let address = listener.local_addr().expect("stub server address"); - std::thread::spawn(move || { - while let Ok((mut stream, _)) = listener.accept() { - let _ = stream.write_all(response); - } - }); - format!("http://{address}") -} - -#[test] -fn a_200_answer_satisfies_the_probe() { - let base_url = spawn_stub_server(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"); - wait_for_health(&base_url, Duration::from_secs(5)).expect("the stub answers 200"); -} - -#[test] -fn a_non_200_answer_is_retried_until_timeout() { - let base_url = - spawn_stub_server(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n"); - let error = wait_for_health(&base_url, Duration::from_millis(150)) - .expect_err("a 503 never satisfies the probe"); - assert!( - matches!(error, HealthError::Timeout { .. }), - "a 503 past the budget is a timeout" - ); - let message = error.to_string(); - assert!( - message.contains("did not answer"), - "the error names the timeout: {message}" - ); +/// The outcome of one bearer-key probe. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum KeyProbe { + /// A 2xx answer: the key is accepted. + Accepted, + /// A non-2xx answer: the key is rejected (or the route is gone). + Rejected, + /// The server could not be queried at all. + Unreachable, } -#[test] -fn a_dead_port_times_out() { - // Port 1 is never listening, so every connect fails fast. - let error = wait_for_health("http://127.0.0.1:1", Duration::from_millis(150)) - .expect_err("a dead port never satisfies the probe"); - assert!( - matches!(error, HealthError::Timeout { .. }), - "a dead port past the budget is a timeout" - ); - let message = error.to_string(); - assert!( - message.contains("did not answer"), - "the error names the timeout: {message}" - ); +/// Issues one `GET {path}` presenting `api_key` as the bearer token and +/// classifies the answer. +fn probe_bearer(address: &str, path: &str, api_key: &str) -> KeyProbe { + match request_head(address, "GET", path, Some(api_key)) { + Ok(head) => { + if response_status(&head).is_some_and(|code| (200..300).contains(&code)) { + KeyProbe::Accepted + } else { + KeyProbe::Rejected + } + } + Err(_) => KeyProbe::Unreachable, + } } -#[test] -fn a_non_http_url_is_rejected() { - let error = wait_for_health("ftp://127.0.0.1:7910", Duration::from_millis(10)) - .expect_err("a non-http URL must fail"); - assert!( - matches!(error, HealthError::NotHttp { .. }), - "a non-http URL is rejected before any probe" - ); - assert!( - error.to_string().contains("http://"), - "the error names the scheme requirement: {error}" - ); +/// Proves that one address is healthy and accepts the presented bearer. +/// Both requests use one TCP connection, so authority cannot come from a +/// listener that replaced the endpoint after the health response. +fn probe_connection( + address: &str, + bearer_path: &str, + bearer: &str, + health_budget: Duration, +) -> ConnectionProbe { + probe_connection_until(address, bearer_path, bearer, Instant::now() + health_budget) } #[test] -fn the_probe_sends_the_bound_address_as_host() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind recording server"); - let address = listener.local_addr().expect("recording server address"); - let (requests, received) = mpsc::channel(); - std::thread::spawn(move || { - if let Ok((mut stream, _)) = listener.accept() { - let mut buffer = [0u8; 1024]; - if let Ok(read) = stream.read(&mut buffer) { - let _ = requests.send(String::from_utf8_lossy(&buffer[..read]).into_owned()); - } - let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"); - } - }); +fn a_200_answer_satisfies_the_probe_and_sends_bound_address_as_host() { + let (address, received) = canned_gateway(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"); wait_for_health(&format!("http://{address}"), Duration::from_secs(5)) .expect("the stub answers 200"); let request = received @@ -101,39 +62,125 @@ fn the_probe_sends_the_bound_address_as_host() { } #[test] -fn a_bearer_probe_accepts_a_2xx_and_rejects_a_401() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind key fixture"); - let address = listener - .local_addr() - .expect("key fixture address") - .to_string(); - std::thread::spawn(move || { +fn wait_for_health_rejects_bad_schemes_and_times_out_unhealthy_endpoints() { + enum Target { + Canned(&'static [u8]), + Url(&'static str), + } + enum Expected { + Timeout, + NotHttp, + } + const CASES: &[(&str, Target, Expected, &str)] = &[ + ( + "503 response times out", + Target::Canned(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n"), + Expected::Timeout, + "did not answer", + ), + ( + "dead port times out", + Target::Url("http://127.0.0.1:1"), + Expected::Timeout, + "did not answer", + ), + ( + "ftp scheme rejected", + Target::Url("ftp://127.0.0.1:7910"), + Expected::NotHttp, + "http://", + ), + ( + "https scheme rejected", + Target::Url("https://127.0.0.1:7910"), + Expected::NotHttp, + "http://", + ), + ( + "bare host without scheme rejected", + Target::Url("127.0.0.1:7910"), + Expected::NotHttp, + "http://", + ), + ]; + + for &(label, ref target, ref expected, expected_substring) in CASES { + let url = match target { + Target::Canned(response) => format!("http://{}", canned_gateway(response).0), + Target::Url(url) => (*url).to_owned(), + }; + let budget = match expected { + Expected::Timeout => Duration::from_millis(150), + Expected::NotHttp => Duration::from_millis(10), + }; + let error = + wait_for_health(&url, budget).expect_err("unhealthy or invalid health URL must fail"); + match expected { + Expected::Timeout => assert!( + matches!(error, HealthError::Timeout { .. }), + "{label}: expected Timeout, got {error:?}" + ), + Expected::NotHttp => assert!( + matches!(error, HealthError::NotHttp { .. }), + "{label}: expected NotHttp, got {error:?}" + ), + } + assert!( + error.to_string().contains(expected_substring), + "{label}: error message `{error}` missing `{expected_substring}`" + ); + } +} + +#[test] +fn a_bearer_probe_accepts_a_2xx_and_rejects_non_2xx() { + let address = spawn_tcp_fixture(|listener| { while let Ok((mut stream, _)) = listener.accept() { - let mut buffer = [0u8; 1024]; + let mut buffer = [0_u8; 1024]; let Ok(read) = stream.read(&mut buffer) else { continue; }; let request = String::from_utf8_lossy(&buffer[..read]); let response = if request.contains("Authorization: Bearer right\r\n") { &b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"[..] + } else if request.contains("Authorization: Bearer error\r\n") { + &b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"[..] } else { &b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"[..] }; let _ = stream.write_all(response); } - }); - assert_eq!( - probe_bearer(&address, "/v1/models", "right"), - KeyProbe::Accepted - ); - assert_eq!( - probe_bearer(&address, "/v1/models", "wrong"), - KeyProbe::Rejected - ); - assert_eq!( - probe_bearer("127.0.0.1:1", "/v1/models", "right"), - KeyProbe::Unreachable - ); + }) + .to_string(); + + for (label, target, key, expected) in [ + ( + "accepted bearer", + address.as_str(), + "right", + KeyProbe::Accepted, + ), + ( + "401 rejected bearer", + address.as_str(), + "wrong", + KeyProbe::Rejected, + ), + ( + "500 server error", + address.as_str(), + "error", + KeyProbe::Rejected, + ), + ( + "dead port unreachable", + "127.0.0.1:1", + "right", + KeyProbe::Unreachable, + ), + ] { + assert_eq!(probe_bearer(target, "/v1/models", key), expected, "{label}"); + } } #[test] @@ -178,7 +225,7 @@ fn cancellation_at_health_probe_start_prevents_the_probe() { #[test] fn cancellation_joins_a_blocked_health_wait_without_another_probe() { - let cancellation = crate::CancellationToken::new(); + let cancellation = CancellationToken::new(); let worker_cancellation = cancellation.clone(); let probes = Arc::new(AtomicUsize::new(0)); let worker_probes = Arc::clone(&probes); diff --git a/crates/workshop/gateway-discovery/src/lib.rs b/crates/workshop/gateway-discovery/src/lib.rs index 762ba3b9..41dd177f 100644 --- a/crates/workshop/gateway-discovery/src/lib.rs +++ b/crates/workshop/gateway-discovery/src/lib.rs @@ -72,6 +72,8 @@ mod peer; mod shutdown; mod stale; mod sys; +#[cfg(test)] +mod test_support; mod validated; pub use crate::cancellation::CancellationToken; diff --git a/crates/workshop/gateway-discovery/src/lock-tests.rs b/crates/workshop/gateway-discovery/src/lock-tests.rs index 94f88e4b..2801854b 100644 --- a/crates/workshop/gateway-discovery/src/lock-tests.rs +++ b/crates/workshop/gateway-discovery/src/lock-tests.rs @@ -1,57 +1,9 @@ //! Unit tests for the launch-race lock and the Gateway instance lease. -use super::*; - -use std::io::{Read, Write as _}; -use std::net::TcpListener; use std::sync::mpsc; -/// The test process's own image name, so the pid and image checks -/// pass and the loser reaches the probe path. -fn own_image_name() -> String { - std::env::current_exe() - .expect("current exe") - .file_name() - .expect("the exe has a file name") - .to_string_lossy() - .into_owned() -} - -/// A fixture gateway answering health and the presented key with 200. -fn fixture_gateway() -> u16 { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); - let port = listener.local_addr().expect("fixture address").port(); - std::thread::spawn(move || { - while let Ok((mut stream, _)) = listener.accept() { - for _ in 0..2 { - let mut buffer = [0u8; 1024]; - if stream.read(&mut buffer).is_err() { - break; - } - if stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") - .is_err() - { - break; - } - } - } - }); - port -} - -/// A live gateway discovery file on the fixture gateway, owned by the test -/// process. -fn live_file(port: u16) -> GatewayDiscoveryFile { - GatewayDiscoveryFile { - port, - api_key: "key".to_owned(), - pid: std::process::id(), - epoch: 1_757_000_000, - version: "0.2.0".to_owned(), - started_at: "2026-09-03T12:00:00Z".to_owned(), - } -} +use super::*; +use crate::test_support::{fixture_gateway, live_file, own_image_name}; #[test] fn an_empty_run_dir_elects_a_launcher() { @@ -98,7 +50,7 @@ fn process_ownership_is_separate_from_parent_launch_election() { #[test] fn a_live_file_attaches_without_contesting_the_lock() { let dir = tempfile::TempDir::new().expect("tempdir"); - let file = live_file(fixture_gateway()); + let file = live_file(fixture_gateway("key"), "key"); file.write_to(dir.path()).expect("write"); let decision = launch_or_attach_named(dir.path(), &own_image_name(), Duration::from_secs(5)) @@ -128,7 +80,7 @@ fn the_race_loser_attaches_to_the_winners_file() { .expect("the loser's race settles") }); std::thread::sleep(Duration::from_millis(100)); - let file = live_file(fixture_gateway()); + let file = live_file(fixture_gateway("key"), "key"); file.write_to(dir.path()).expect("the winner writes"); match loser.join().expect("the loser thread ran") { diff --git a/crates/workshop/gateway-discovery/src/lock.rs b/crates/workshop/gateway-discovery/src/lock.rs index 0b82e0c3..b3729d81 100644 --- a/crates/workshop/gateway-discovery/src/lock.rs +++ b/crates/workshop/gateway-discovery/src/lock.rs @@ -10,11 +10,14 @@ //! `OpenOptions` create plus a `std::fs::File` advisory lock, released by //! dropping the handle. -use std::fs::{File, OpenOptions, TryLockError}; +use std::fs::{self, File, OpenOptions, TryLockError}; use std::path::Path; +use std::thread; use std::time::{Duration, Instant}; use crate::error::SidecarError; +#[cfg(feature = "test-fixtures")] +use crate::paths::instance_lock_file_path; use crate::paths::lock_file_path; use crate::stale::{self, GATEWAY_IMAGE_NAME, Resolution}; use crate::{CancellationToken, GatewayDiscoveryFile}; @@ -54,21 +57,26 @@ impl GatewayInstanceLease { /// created, or [`SidecarError::Lock`] when the lease file cannot be opened /// or an unexpected operating-system lock error occurs. pub fn try_acquire(run_dir: &Path) -> Result, SidecarError> { - std::fs::create_dir_all(run_dir).map_err(|source| SidecarError::CreateDir { + fs::create_dir_all(run_dir).map_err(|source| SidecarError::CreateDir { path: run_dir.to_owned(), source, })?; - let lock_path = crate::paths::instance_lock_file_path(run_dir); - let file = OpenOptions::new() + let lock_path = instance_lock_file_path(run_dir); + let file = match OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .open(&lock_path) - .map_err(|source| SidecarError::Lock { - path: lock_path.clone(), - source, - })?; + { + Ok(file) => file, + Err(source) => { + return Err(SidecarError::Lock { + path: lock_path, + source, + }); + } + }; match file.try_lock() { Ok(()) => Ok(Some(Self { _file: file })), Err(TryLockError::WouldBlock) => Ok(None), @@ -120,7 +128,13 @@ pub fn launch_or_attach_cancellable( timeout: Duration, cancellation: &CancellationToken, ) -> Result { - launch_or_attach_named_cancellable(run_dir, GATEWAY_IMAGE_NAME, timeout, cancellation) + launch_or_attach_named_cancellable_with( + run_dir, + GATEWAY_IMAGE_NAME, + timeout, + cancellation, + |delay| cancellation.wait_timeout(delay), + ) } /// [`launch_or_attach`] against a caller-named process image, so tests @@ -131,107 +145,70 @@ fn launch_or_attach_named( image_name: &str, timeout: Duration, ) -> Result { - std::fs::create_dir_all(run_dir).map_err(|source| SidecarError::CreateDir { - path: run_dir.to_owned(), - source, - })?; - let lock_path = lock_file_path(run_dir); - let lock = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(&lock_path) - .map_err(|source| SidecarError::Lock { - path: lock_path.clone(), - source, - })?; - let deadline = Instant::now() + timeout; - loop { - match lock.try_lock() { - Ok(()) => { - // The lock is held; a previous winner may have written a - // live file before releasing, so re-validate before - // launching. As the holder, cleanup is ours. - return Ok(match stale::resolve_named(run_dir, image_name)? { - Resolution::Attach(file) => LaunchDecision::Attach(file), - Resolution::Absent | Resolution::Stale(_) => { - LaunchDecision::Launch(LaunchLock { _file: lock }) - } - }); - } - Err(TryLockError::WouldBlock) => { - // Another process holds the lock and is mid-launch. Attach - // as soon as its file goes live; never delete here. - if let Ok(Some(file)) = GatewayDiscoveryFile::read(run_dir) - && stale::is_live(&file, image_name) - { - return Ok(LaunchDecision::Attach(file)); - } - if Instant::now() >= deadline { - return Err(SidecarError::LaunchTimeout { timeout }); - } - std::thread::sleep(RETRY_INTERVAL); - } - Err(TryLockError::Error(source)) => { - return Err(SidecarError::Lock { - path: lock_path.clone(), - source, - }); - } - } - } + launch_or_attach_core(run_dir, image_name, timeout, None, |delay| { + thread::sleep(delay); + false + }) } -fn launch_or_attach_named_cancellable( +fn launch_or_attach_named_cancellable_with( run_dir: &Path, image_name: &str, timeout: Duration, cancellation: &CancellationToken, + wait: impl FnMut(Duration) -> bool, ) -> Result { - launch_or_attach_named_cancellable_with(run_dir, image_name, timeout, cancellation, |delay| { - cancellation.wait_timeout(delay) - }) + launch_or_attach_core(run_dir, image_name, timeout, Some(cancellation), wait) } -fn launch_or_attach_named_cancellable_with( +fn launch_or_attach_core( run_dir: &Path, image_name: &str, timeout: Duration, - cancellation: &CancellationToken, + cancellation: Option<&CancellationToken>, mut wait: impl FnMut(Duration) -> bool, ) -> Result { - if cancellation.is_canceled() { + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(SidecarError::Canceled); } - std::fs::create_dir_all(run_dir).map_err(|source| SidecarError::CreateDir { + fs::create_dir_all(run_dir).map_err(|source| SidecarError::CreateDir { path: run_dir.to_owned(), source, })?; - if cancellation.is_canceled() { + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(SidecarError::Canceled); } let lock_path = lock_file_path(run_dir); - let lock = OpenOptions::new() + let lock = match OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .open(&lock_path) - .map_err(|source| SidecarError::Lock { - path: lock_path.clone(), - source, - })?; + { + Ok(lock) => lock, + Err(source) => { + return Err(SidecarError::Lock { + path: lock_path, + source, + }); + } + }; let deadline = Instant::now() + timeout; loop { - if cancellation.is_canceled() { + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(SidecarError::Canceled); } match lock.try_lock() { Ok(()) => { - let resolution = - stale::resolve_named_cancellable(run_dir, image_name, cancellation)?; - if cancellation.is_canceled() { + // The lock is held; a previous winner may have written a + // live file before releasing, so re-validate before + // launching. As the holder, cleanup is ours. + let resolution = match cancellation { + Some(token) => stale::resolve_named_cancellable(run_dir, image_name, token)?, + None => stale::resolve_named(run_dir, image_name)?, + }; + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(SidecarError::Canceled); } return Ok(match resolution { @@ -242,16 +219,22 @@ fn launch_or_attach_named_cancellable_with( }); } Err(TryLockError::WouldBlock) => { - if cancellation.is_canceled() { + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(SidecarError::Canceled); } - if let Ok(Some(file)) = GatewayDiscoveryFile::read(run_dir) - && stale::is_live_cancellable(&file, image_name, cancellation)? - { - if cancellation.is_canceled() { - return Err(SidecarError::Canceled); + // Another process holds the lock and is mid-launch. Attach + // as soon as its file goes live; never delete here. + if let Ok(Some(file)) = GatewayDiscoveryFile::read(run_dir) { + let live = match cancellation { + Some(token) => stale::is_live_cancellable(file, image_name, token)?, + None => stale::is_live(file, image_name), + }; + if let Some(file) = live { + if cancellation.is_some_and(CancellationToken::is_canceled) { + return Err(SidecarError::Canceled); + } + return Ok(LaunchDecision::Attach(file)); } - return Ok(LaunchDecision::Attach(file)); } if Instant::now() >= deadline { return Err(SidecarError::LaunchTimeout { timeout }); @@ -262,7 +245,7 @@ fn launch_or_attach_named_cancellable_with( } Err(TryLockError::Error(source)) => { return Err(SidecarError::Lock { - path: lock_path.clone(), + path: lock_path, source, }); } diff --git a/crates/workshop/gateway-discovery/src/peer-tests.rs b/crates/workshop/gateway-discovery/src/peer-tests.rs index adc63843..c2a203b8 100644 --- a/crates/workshop/gateway-discovery/src/peer-tests.rs +++ b/crates/workshop/gateway-discovery/src/peer-tests.rs @@ -7,18 +7,15 @@ use super::{ installed_plugin_dir, plugin_dir, running_appimage, }; -/// Plants an empty executable file at `root/relative`, creating its -/// directories. fn plant(root: &Path, relative: &Path) -> PathBuf { let path = root.join(relative); - std::fs::create_dir_all(path.parent().expect("a planted file has a parent")) - .expect("create fixture directories"); - std::fs::write(&path, b"").expect("plant fixture file"); + std::fs::create_dir_all(path.parent().expect("parent")).expect("create dirs"); + std::fs::write(&path, b"").expect("plant file"); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt as _; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) - .expect("mark fixture executable"); + .expect("mark executable"); } path } @@ -28,144 +25,197 @@ fn gateway_for(layout: Layout, workshop_exe: &Path, appimage: Option<&Path>) -> } #[test] -fn windows_peers_sit_beside_each_other() { - let root = tempfile::TempDir::new().expect("tempdir"); - let workshop = plant(root.path(), Path::new("runvil-workshop.exe")); - let gateway = plant(root.path(), Path::new("runvil-gateway.exe")); - - assert_eq!(gateway_for(Layout::Windows, &workshop, None), Some(gateway)); -} - -#[test] -fn a_development_tree_finds_the_gateway_beside_workshop() { - let root = tempfile::TempDir::new().expect("tempdir"); - let debug = Path::new("target").join("debug"); - let workshop = plant(root.path(), &debug.join("runvil-workshop")); - let gateway = plant(root.path(), &debug.join("runvil-gateway")); +fn gateway_peer_lookup_follows_each_platform_layout() { + type Case = ( + &'static str, + Layout, + &'static [&'static str], + &'static str, + Option<&'static str>, + Option<&'static str>, + ); + const CASES: &[Case] = &[ + ( + "windows sibling", + Layout::Windows, + &["runvil-workshop.exe", "runvil-gateway.exe"], + "runvil-workshop.exe", + None, + Some("runvil-gateway.exe"), + ), + ( + "macos dev tree", + Layout::MacOs, + &[ + "target/debug/runvil-workshop", + "target/debug/runvil-gateway", + ], + "target/debug/runvil-workshop", + None, + Some("target/debug/runvil-gateway"), + ), + ( + "linux dev tree", + Layout::Linux, + &[ + "target/debug/runvil-workshop", + "target/debug/runvil-gateway", + ], + "target/debug/runvil-workshop", + None, + Some("target/debug/runvil-gateway"), + ), + ( + "macos sibling bundles", + Layout::MacOs, + &[ + "Runvil Workshop.app/Contents/MacOS/runvil-workshop", + "Runvil Gateway.app/Contents/MacOS/runvil-gateway", + ], + "Runvil Workshop.app/Contents/MacOS/runvil-workshop", + None, + Some("Runvil Gateway.app/Contents/MacOS/runvil-gateway"), + ), + ( + "macos loose exe ignores bundle", + Layout::MacOs, + &["Runvil Gateway.app/Contents/MacOS/runvil-gateway"], + "Contents/MacOS/runvil-workshop", + None, + None, + ), + ( + "linux beside appimage", + Layout::Linux, + &["Runvil/Runvil-Workshop.AppImage", "Runvil/runvil-gateway"], + "mount/usr/bin/runvil-workshop", + Some("Runvil/Runvil-Workshop.AppImage"), + Some("Runvil/runvil-gateway"), + ), + ( + "linux prefers appimage sibling over mount", + Layout::Linux, + &[ + "Runvil/Runvil-Workshop.AppImage", + "Runvil/runvil-gateway", + "mount/usr/bin/runvil-workshop", + "mount/usr/bin/runvil-gateway", + ], + "mount/usr/bin/runvil-workshop", + Some("Runvil/Runvil-Workshop.AppImage"), + Some("Runvil/runvil-gateway"), + ), + ( + "windows missing peer", + Layout::Windows, + &["runvil-workshop.exe", "elsewhere/runvil-gateway.exe"], + "runvil-workshop.exe", + None, + None, + ), + ( + "macos missing peer", + Layout::MacOs, + &["runvil-workshop", "elsewhere/runvil-gateway"], + "runvil-workshop", + None, + None, + ), + ( + "linux missing peer", + Layout::Linux, + &["runvil-workshop", "elsewhere/runvil-gateway"], + "runvil-workshop", + None, + None, + ), + ]; - for layout in [Layout::MacOs, Layout::Linux] { + for &(label, layout, planted, workshop, appimage, expected) in CASES { + let root = tempfile::TempDir::new().expect("tempdir"); + for relative in planted { + plant(root.path(), Path::new(relative)); + } + let workshop = root.path().join(workshop); + let appimage = appimage.map(|rel| root.path().join(rel)); + let expected = expected.map(|rel| root.path().join(rel)); assert_eq!( - gateway_for(layout, &workshop, None), - Some(gateway.clone()), - "{layout:?}" + gateway_for(layout, &workshop, appimage.as_deref()), + expected, + "{label}" ); } -} - -#[test] -fn macos_peers_are_sibling_bundles() { - let root = tempfile::TempDir::new().expect("tempdir"); - let workshop = plant( - root.path(), - &bundle_exe(Path::new(""), WORKSHOP_BUNDLE_NAME, "runvil-workshop"), - ); - let gateway = plant( - root.path(), - &bundle_exe(Path::new(""), GATEWAY_BUNDLE_NAME, "runvil-gateway"), - ); - assert_eq!(gateway_for(Layout::MacOs, &workshop, None), Some(gateway)); -} - -#[test] -fn macos_bundle_lookup_needs_the_bundle_structure() { let root = tempfile::TempDir::new().expect("tempdir"); - plant( - root.path(), - &bundle_exe(Path::new(""), GATEWAY_BUNDLE_NAME, "runvil-gateway"), - ); - let loose = root - .path() - .join("Contents") - .join("MacOS") - .join("runvil-workshop"); - assert_eq!( - gateway_for(Layout::MacOs, &loose, None), + installed_gateway(&root.path().join("absent").join("runvil-gateway"), None), None, - "an executable outside a .app bundle has no bundle siblings" + "absent install dir" ); + assert_eq!(GATEWAY_BUNDLE_NAME, "Runvil Gateway.app"); } #[test] -fn linux_workshop_finds_the_gateway_beside_its_appimage() { - let root = tempfile::TempDir::new().expect("tempdir"); - let install = root.path().join("Runvil"); - let appimage = plant(&install, Path::new(WORKSHOP_APPIMAGE_NAME)); - let gateway = plant(&install, Path::new("runvil-gateway")); - let mount = root - .path() - .join("mount") - .join("usr") - .join("bin") - .join("runvil-workshop"); +fn running_appimage_requires_matching_absolute_appimage_and_mount() { + type Case<'a> = (&'static str, Option<&'a OsStr>, Option<&'a OsStr>, bool); - assert_eq!( - gateway_for(Layout::Linux, &mount, Some(appimage.as_path())), - Some(gateway) - ); -} - -#[test] -fn linux_workshop_prefers_the_gateway_beside_its_appimage_to_one_in_its_mount() { - let root = tempfile::TempDir::new().expect("tempdir"); - let install = root.path().join("Runvil"); - let appimage = plant(&install, Path::new(WORKSHOP_APPIMAGE_NAME)); - let installed = plant(&install, Path::new("runvil-gateway")); - let bin = root.path().join("mount").join("usr").join("bin"); - let workshop = plant(&bin, Path::new("runvil-workshop")); - plant(&bin, Path::new("runvil-gateway")); - - assert_eq!( - gateway_for(Layout::Linux, &workshop, Some(appimage.as_path())), - Some(installed) - ); -} - -#[test] -fn an_appimage_counts_only_when_workshop_runs_from_its_mount() { let root = tempfile::TempDir::new().expect("tempdir"); let mount = root.path().join(".mount_PromptXYZ"); let workshop = mount.join("usr").join("bin").join("runvil-workshop"); let appimage = root.path().join("Runvil").join(WORKSHOP_APPIMAGE_NAME); let other_mount = root.path().join(".mount_CodeXYZ"); + let prefix_mount = root.path().join(".mount_Prompt"); let other_appimage = root.path().join("Apps").join("Code.AppImage"); - let found = |appimage: &OsStr, appdir: &OsStr| { - running_appimage(&workshop, Some(appimage), Some(appdir)) - }; - assert_eq!( - found(appimage.as_os_str(), mount.as_os_str()), - Some(appimage.clone()) - ); - assert_eq!( - found(other_appimage.as_os_str(), other_mount.as_os_str()), - None, - "an $APPIMAGE inherited from another AppImage is ignored" - ); - assert_eq!( - found(OsStr::new(WORKSHOP_APPIMAGE_NAME), mount.as_os_str()), - None, - "a relative $APPIMAGE is ignored" - ); - assert_eq!( - found(OsStr::new(""), mount.as_os_str()), - None, - "empty $APPIMAGE" - ); - assert_eq!( - found(appimage.as_os_str(), OsStr::new("")), - None, - "empty $APPDIR" - ); - assert_eq!( - running_appimage(&workshop, Some(appimage.as_os_str()), None), - None - ); - assert_eq!( - running_appimage(&workshop, None, Some(mount.as_os_str())), - None - ); + let cases: &[Case<'_>] = &[ + ( + "matching mount and appimage", + Some(appimage.as_os_str()), + Some(mount.as_os_str()), + true, + ), + ( + "inherited foreign appimage", + Some(other_appimage.as_os_str()), + Some(other_mount.as_os_str()), + false, + ), + ( + "prefix-only appdir", + Some(appimage.as_os_str()), + Some(prefix_mount.as_os_str()), + false, + ), + ( + "relative appimage", + Some(OsStr::new(WORKSHOP_APPIMAGE_NAME)), + Some(mount.as_os_str()), + false, + ), + ( + "empty appimage", + Some(OsStr::new("")), + Some(mount.as_os_str()), + false, + ), + ( + "empty appdir", + Some(appimage.as_os_str()), + Some(OsStr::new("")), + false, + ), + ("missing appdir", Some(appimage.as_os_str()), None, false), + ("missing appimage", None, Some(mount.as_os_str()), false), + ]; + + for &(label, image, appdir, expect_found) in cases { + let expected = expect_found.then(|| appimage.clone()); + assert_eq!( + running_appimage(&workshop, image, appdir), + expected, + "{label}" + ); + } } #[cfg(unix)] @@ -178,9 +228,7 @@ fn an_appimage_counts_when_appdir_reaches_the_mount_through_a_symlink() { std::os::unix::fs::symlink(&mount, &link).expect("link to the mount"); let workshop = std::fs::canonicalize(&mount) .expect("resolve the mount") - .join("usr") - .join("bin") - .join("runvil-workshop"); + .join("usr/bin/runvil-workshop"); let appimage = root.path().join("Runvil").join(WORKSHOP_APPIMAGE_NAME); assert_eq!( @@ -204,142 +252,142 @@ fn a_peer_without_an_execute_bit_is_not_found() { gateway_for(Layout::Linux, &workshop, None), Some(gateway.clone()) ); - std::fs::set_permissions(&gateway, std::fs::Permissions::from_mode(0o644)) - .expect("clear the execute bits"); - + std::fs::set_permissions(&gateway, std::fs::Permissions::from_mode(0o644)).expect("chmod"); assert_eq!(gateway_for(Layout::Linux, &workshop, None), None); } #[test] -fn the_bundle_walks_up_from_contents_macos_to_the_app() { - let exe = Path::new("/Applications/Runvil.app/Contents/MacOS/runvil-gateway"); - assert_eq!(app_bundle(exe), Some(Path::new("/Applications/Runvil.app"))); -} - -#[test] -fn the_bundle_probe_rejects_unbundled_and_partial_paths() { - assert_eq!(app_bundle(Path::new("/usr/local/bin/runvil-gateway")), None); - assert_eq!( - app_bundle(Path::new("/Applications/Runvil.app/Contents/MacOS")), - None, - "the exe itself must sit below MacOS" - ); - assert_eq!( - app_bundle(Path::new("/opt/x/Contents/MacOS/runvil-gateway")), - None, - "the parent two levels up must be a .app" - ); - assert_eq!(app_bundle(Path::new("runvil-gateway")), None); -} +fn app_bundle_detects_only_valid_macos_bundle_executables() { + const CASES: &[(&str, &str, Option<&str>)] = &[ + ( + "valid macos app bundle", + "/Applications/Runvil.app/Contents/MacOS/runvil-gateway", + Some("/Applications/Runvil.app"), + ), + ( + "unbundled usr local bin", + "/usr/local/bin/runvil-gateway", + None, + ), + ( + "partial path at MacOS", + "/Applications/Runvil.app/Contents/MacOS", + None, + ), + ( + "non-app parent", + "/opt/x/Contents/MacOS/runvil-gateway", + None, + ), + ( + "wrong Contents subdir", + "/Applications/Runvil.app/Contents/Resources/runvil-gateway", + None, + ), + ("bare executable name", "runvil-gateway", None), + ]; -#[test] -fn a_missing_peer_is_none_in_every_layout() { - for layout in [Layout::Windows, Layout::MacOs, Layout::Linux] { - let root = tempfile::TempDir::new().expect("tempdir"); - let exe = if matches!(layout, Layout::Windows) { - "runvil-workshop.exe" - } else { - "runvil-workshop" - }; - let workshop = plant(root.path(), Path::new(exe)); - plant( - &root.path().join("elsewhere"), - Path::new(layout.gateway_exe()), + for &(label, exe, expected) in CASES { + assert_eq!( + app_bundle(Path::new(exe)), + expected.map(Path::new), + "{label}" ); - - assert_eq!(gateway_for(layout, &workshop, None), None, "{layout:?}"); } } #[test] -fn a_missing_install_directory_is_none() { - let root = tempfile::TempDir::new().expect("tempdir"); - let absent = root.path().join("absent").join("runvil-gateway"); - assert_eq!(installed_gateway(&absent, None), None); -} +fn plugin_dir_follows_layout_bundle_and_appimage_rules() { + type Case<'a> = (&'static str, Layout, &'a Path, Option<&'a Path>, PathBuf); -#[test] -fn the_plugin_directory_sits_beside_an_unbundled_workshop_in_every_layout() { let install = Path::new("install"); - for layout in [Layout::Windows, Layout::MacOs, Layout::Linux] { - assert_eq!( - plugin_dir(layout, &install.join("runvil-workshop"), None), - Some(install.join(PLUGIN_DIR_NAME)), - "{layout:?}" - ); - } -} + let unbundled = install.join("runvil-workshop"); + let apps = Path::new("Applications").join("Runvil"); + let bundled = bundle_exe(&apps, WORKSHOP_BUNDLE_NAME, "runvil-workshop"); + let appimage = Path::new("opt").join("Runvil").join(WORKSHOP_APPIMAGE_NAME); + let mounted = Path::new("mount/usr/bin/runvil-workshop"); + let beside_mount = Path::new("mount/usr/bin").join(PLUGIN_DIR_NAME); -#[test] -fn the_macos_plugin_directory_sits_inside_the_workshop_bundle() { - let install = Path::new("Applications").join("Runvil"); - let workshop = bundle_exe(&install, WORKSHOP_BUNDLE_NAME, "runvil-workshop"); - assert_eq!( - plugin_dir(Layout::MacOs, &workshop, None), - Some( - install - .join(WORKSHOP_BUNDLE_NAME) - .join("Contents") - .join("Resources") - .join(PLUGIN_DIR_NAME) + let cases: &[Case<'_>] = &[ + ( + "windows unbundled", + Layout::Windows, + &unbundled, + None, + install.join(PLUGIN_DIR_NAME), ), - "the updater replaces the bundle, so the Plugins go with it" - ); - assert_eq!( - plugin_dir(Layout::Windows, &workshop, None), - Some( - install - .join(WORKSHOP_BUNDLE_NAME) - .join("Contents") - .join("MacOS") - .join(PLUGIN_DIR_NAME) + ( + "macos unbundled", + Layout::MacOs, + &unbundled, + None, + install.join(PLUGIN_DIR_NAME), ), - "only the macOS layout reads the bundle structure" - ); -} - -#[test] -fn the_linux_plugin_directory_sits_inside_the_appimage_s_mount() { - let install = Path::new("opt").join("Runvil"); - let appimage = install.join(WORKSHOP_APPIMAGE_NAME); - let workshop = Path::new("mount") - .join("usr") - .join("bin") - .join("runvil-workshop"); - assert_eq!( - plugin_dir(Layout::Linux, &workshop, Some(appimage.as_path())), - Some( - Path::new("mount") - .join("usr") - .join("lib") - .join("runvil") - .join(PLUGIN_DIR_NAME) + ( + "linux unbundled", + Layout::Linux, + &unbundled, + None, + install.join(PLUGIN_DIR_NAME), ), - "the updater replaces the AppImage, so the Plugins go with it" - ); - assert_eq!( - plugin_dir(Layout::Linux, &workshop, None), - Some( - Path::new("mount") - .join("usr") - .join("bin") - .join(PLUGIN_DIR_NAME) + ( + "macos bundle uses Resources", + Layout::MacOs, + &bundled, + None, + apps.join(WORKSHOP_BUNDLE_NAME) + .join("Contents/Resources") + .join(PLUGIN_DIR_NAME), ), - "outside an AppImage the directory sits beside the executable" - ); - assert_eq!( - plugin_dir(Layout::Windows, &workshop, Some(appimage.as_path())), - Some( - Path::new("mount") - .join("usr") - .join("bin") - .join(PLUGIN_DIR_NAME) + ( + "windows ignores macos bundle", + Layout::Windows, + &bundled, + None, + apps.join(WORKSHOP_BUNDLE_NAME) + .join("Contents/MacOS") + .join(PLUGIN_DIR_NAME), ), - "only the Linux layout reads the AppImage" - ); -} + ( + "linux appimage uses usr/lib/runvil", + Layout::Linux, + mounted, + Some(&appimage), + Path::new("mount/usr/lib/runvil").join(PLUGIN_DIR_NAME), + ), + ( + "linux without appimage sits beside exe", + Layout::Linux, + mounted, + None, + beside_mount.clone(), + ), + ( + "windows ignores appimage", + Layout::Windows, + mounted, + Some(&appimage), + beside_mount.clone(), + ), + ( + "macos ignores appimage", + Layout::MacOs, + mounted, + Some(&appimage), + beside_mount, + ), + ]; -#[test] -fn an_executable_without_a_directory_has_no_plugin_directory() { - assert_eq!(installed_plugin_dir(Path::new(""), None), None); + for &(label, layout, workshop, appimage_path, ref expected) in cases { + assert_eq!( + plugin_dir(layout, workshop, appimage_path), + Some(expected.clone()), + "{label}" + ); + } + assert_eq!( + installed_plugin_dir(Path::new(""), None), + None, + "empty path has no plugin dir" + ); } diff --git a/crates/workshop/gateway-discovery/src/peer.rs b/crates/workshop/gateway-discovery/src/peer.rs index 92d0cf98..948c8537 100644 --- a/crates/workshop/gateway-discovery/src/peer.rs +++ b/crates/workshop/gateway-discovery/src/peer.rs @@ -20,6 +20,7 @@ //! the updater replaces only that bundle or that file. use std::ffi::OsStr; +use std::fs; use std::path::{Path, PathBuf}; // The installers, built in `cppalliance/runvil`, lay the payload out under @@ -100,7 +101,7 @@ pub fn running_appimage( let under = |dir: &Path| workshop_exe.starts_with(dir); let inside = appimage.is_absolute() && appdir.is_absolute() - && (under(appdir) || std::fs::canonicalize(appdir).is_ok_and(|dir| under(&dir))); + && (under(appdir) || fs::canonicalize(appdir).is_ok_and(|dir| under(&dir))); inside.then(|| appimage.to_path_buf()) } @@ -121,7 +122,7 @@ fn first_file(candidates: Vec) -> Option { /// needs an execute bit: a downloaded AppImage starts without one, and /// launching it would fail. fn runnable(path: &Path) -> bool { - let Ok(metadata) = std::fs::metadata(path) else { + let Ok(metadata) = fs::metadata(path) else { return false; }; #[cfg(unix)] @@ -150,7 +151,7 @@ fn gateway_candidates( candidates.push(dir.join(layout.gateway_exe())); } if matches!(layout, Layout::MacOs) - && let Some(dir) = bundle_dir(workshop_exe) + && let Some(dir) = app_bundle(workshop_exe).and_then(Path::parent) { candidates.push(bundle_exe(dir, GATEWAY_BUNDLE_NAME, layout.gateway_exe())); } @@ -181,11 +182,13 @@ fn plugin_dir(layout: Layout, workshop_exe: &Path, appimage: Option<&Path>) -> O .and_then(|_| beside.parent()?.parent()) .map(|mount| mount.join(APPIMAGE_PLUGIN_PARENT)), }; - Some( - inside - .unwrap_or_else(|| beside.to_path_buf()) - .join(PLUGIN_DIR_NAME), - ) + Some(match inside { + Some(mut dir) => { + dir.push(PLUGIN_DIR_NAME); + dir + } + None => beside.join(PLUGIN_DIR_NAME), + }) } /// The `.app` bundle `exe` runs from, when `exe` sits at @@ -202,11 +205,6 @@ fn app_bundle(exe: &Path) -> Option<&Path> { is_bundle.then_some(bundle) } -/// The directory holding the `.app` bundle `exe` runs from. -fn bundle_dir(exe: &Path) -> Option<&Path> { - app_bundle(exe)?.parent() -} - fn bundle_exe(dir: &Path, bundle: &str, exe: &str) -> PathBuf { dir.join(bundle).join("Contents").join("MacOS").join(exe) } diff --git a/crates/workshop/gateway-discovery/src/shutdown.rs b/crates/workshop/gateway-discovery/src/shutdown.rs index 877192e3..3177f8d0 100644 --- a/crates/workshop/gateway-discovery/src/shutdown.rs +++ b/crates/workshop/gateway-discovery/src/shutdown.rs @@ -6,9 +6,10 @@ //! `TcpStream` like the health probe, matching the crate's dependency diet - //! no HTTP client. +use std::time::Instant; + use crate::health::{self, ProbeError}; use crate::{GatewayDiscoveryFile, ValidatedConnection}; -use std::time::Instant; /// The shutdown route's path on the gateway. const SHUTDOWN_PATH: &str = "/shutdown"; @@ -91,10 +92,7 @@ fn request_shutdown_file_before( } fn accepted(head: &str) -> Result<(), ShutdownError> { - let status = head - .split_whitespace() - .nth(1) - .and_then(|code| code.parse::().ok()); + let status = health::response_status(head); if status.is_some_and(|code| (200..300).contains(&code)) { return Ok(()); } @@ -105,48 +103,18 @@ fn accepted(head: &str) -> Result<(), ShutdownError> { #[cfg(test)] mod tests { - use super::*; - - use std::io::{Read, Write as _}; - use std::net::TcpListener; - use std::sync::mpsc; + use std::io::Read; use std::time::Duration; - /// A gateway discovery file naming the fixture gateway's port. - fn file(port: u16) -> GatewayDiscoveryFile { - GatewayDiscoveryFile { - port, - api_key: "key".to_owned(), - pid: 4242, - epoch: 1_757_000_000, - version: "0.2.0".to_owned(), - started_at: "2026-09-03T12:00:00Z".to_owned(), - } - } - - /// A fixture gateway recording each request and answering with the - /// canned response. - fn fixture_gateway(response: &'static [u8]) -> (u16, mpsc::Receiver) { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); - let port = listener.local_addr().expect("fixture address").port(); - let (requests, received) = mpsc::channel(); - std::thread::spawn(move || { - while let Ok((mut stream, _)) = listener.accept() { - let mut buffer = [0u8; 1024]; - if let Ok(read) = stream.read(&mut buffer) { - let _ = requests.send(String::from_utf8_lossy(&buffer[..read]).into_owned()); - } - let _ = stream.write_all(response); - } - }); - (port, received) - } + use super::*; + use crate::test_support::{canned_gateway, live_file, spawn_tcp_fixture}; #[test] fn an_accepted_shutdown_posts_the_route_with_the_files_key() { - let (port, received) = - fixture_gateway(b"HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\n\r\n"); - request_shutdown_file(&file(port)).expect("the gateway accepted"); + let (addr, received) = + canned_gateway(b"HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\n\r\n"); + let port = addr.port(); + request_shutdown_file(&live_file(port, "key")).expect("the gateway accepted"); let request = received .recv_timeout(Duration::from_secs(5)) .expect("the request arrived"); @@ -165,36 +133,50 @@ mod tests { } #[test] - fn a_refused_shutdown_is_rejected() { - let (port, _received) = - fixture_gateway(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"); - let error = request_shutdown_file(&file(port)).expect_err("a 401 is a refusal"); - assert!( - matches!(error, ShutdownError::Rejected { .. }), - "a non-2xx answer is a rejection: {error}" - ); - } - - #[test] - fn a_reflected_bearer_is_absent_from_shutdown_errors() { - let secret = "capability-secret"; - let response = format!("HTTP/1.1 401 rejected-{secret}\r\nContent-Length: 0\r\n\r\n"); - let response: &'static [u8] = Box::leak(response.into_bytes().into_boxed_slice()); - let (port, _received) = fixture_gateway(response); - let mut connection = file(port); - connection.api_key = secret.to_owned(); - - let error = request_shutdown_file(&connection).expect_err("a 401 is a refusal"); - assert!( - !format!("{error:?} {error}").contains(secret), - "bearer values never enter error diagnostics" - ); + fn rejected_and_malformed_shutdown_answers_redact_the_bearer() { + const SECRET: &str = "capability-secret"; + const CASES: &[(&str, &[u8], &str)] = &[ + ( + "401 unauthorized", + b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n", + "401", + ), + ( + "500 server error", + b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "500", + ), + ( + "401 reflecting bearer", + b"HTTP/1.1 401 rejected-capability-secret\r\nContent-Length: 0\r\n\r\n", + "401", + ), + ( + "malformed status line reflecting bearer", + b"HTTP/1.1 capability-secret\r\nContent-Length: 0\r\n\r\n", + "", + ), + ]; + + for &(label, response, expected_status) in CASES { + let (addr, _received) = canned_gateway(response); + let error = request_shutdown_file(&live_file(addr.port(), SECRET)) + .expect_err("non-2xx or malformed response is refused"); + let ShutdownError::Rejected { status_line } = &error else { + panic!("{label}: expected Rejected, got {error:?}"); + }; + assert_eq!(status_line, expected_status, "{label}"); + assert!( + !format!("{error:?} {error}").contains(SECRET), + "{label}: bearer values never enter error diagnostics" + ); + } } #[test] fn a_dead_gateway_is_an_io_error() { // Port 1 is never listening, so the connect fails fast. - let error = request_shutdown_file(&file(1)).expect_err("a dead port cannot answer"); + let error = request_shutdown_file(&live_file(1, "key")).expect_err("a dead port fails"); assert!( matches!(error, ShutdownError::Io { .. }), "an undelivered request is an I/O error: {error}" @@ -203,18 +185,20 @@ mod tests { #[test] fn an_absolute_deadline_bounds_an_unresponsive_shutdown_target() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow shutdown fixture"); - let port = listener.local_addr().expect("fixture address").port(); - std::thread::spawn(move || { + let port = spawn_tcp_fixture(|listener| { let (mut stream, _) = listener.accept().expect("accept shutdown"); let mut request = [0_u8; 1024]; let _ = stream.read(&mut request); std::thread::sleep(Duration::from_secs(1)); - }); - let started = std::time::Instant::now(); - - let error = request_shutdown_file_before(&file(port), started + Duration::from_millis(100)) - .expect_err("an unresponsive child exceeds the cleanup deadline"); + }) + .port(); + let started = Instant::now(); + + let error = request_shutdown_file_before( + &live_file(port, "key"), + started + Duration::from_millis(100), + ) + .expect_err("an unresponsive child exceeds the cleanup deadline"); assert!(matches!(error, ShutdownError::Io { .. })); assert!( diff --git a/crates/workshop/gateway-discovery/src/stale-tests.rs b/crates/workshop/gateway-discovery/src/stale-tests.rs index 18888d89..73a28417 100644 --- a/crates/workshop/gateway-discovery/src/stale-tests.rs +++ b/crates/workshop/gateway-discovery/src/stale-tests.rs @@ -1,136 +1,114 @@ //! Unit tests for stale detection and stale-file cleanup. -use super::*; - use std::io::{Read, Write as _}; -use std::net::TcpListener; -use std::sync::mpsc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, mpsc}; +use std::time::{Duration, Instant}; +use super::*; use crate::paths::gateway_discovery_file_path; - -/// The test process's own image name, so the pid and image checks -/// pass and the test reaches the probe under test. -fn own_image_name() -> String { - std::env::current_exe() - .expect("current exe") - .file_name() - .expect("the exe has a file name") - .to_string_lossy() - .into_owned() -} - -/// A gateway discovery file pointing at the test process itself. -fn live_file(port: u16, api_key: &str) -> GatewayDiscoveryFile { - GatewayDiscoveryFile { - port, - api_key: api_key.to_owned(), - pid: std::process::id(), - epoch: 1_757_000_000, - version: "0.2.0".to_owned(), - started_at: "2026-09-03T12:00:00Z".to_owned(), - } -} - -/// A pid guaranteed dead: a short-lived child, reaped and dropped so -/// no handle keeps the process object alive. -fn dead_pid() -> u32 { - let mut child = std::process::Command::new(std::env::current_exe().expect("current exe")) - .arg("--list") - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - .expect("spawn a short-lived child"); - let pid = child.id(); - child.wait().expect("the child exits"); - drop(child); - pid +use crate::test_support::{ + dead_pid, fixture_gateway, live_file, own_image_name, spawn_tcp_fixture, +}; + +enum Fixture { + DeadPid, + ForeignImage, + SilentHealth, + RejectedKey, + ZeroEpoch, + BlankStartedAt, + Raw(&'static [u8]), } -/// A fixture gateway: answers `GET /health` with 200 and the key -/// probe with 200 only when the bearer matches `expected_key`. -fn fixture_gateway(expected_key: &'static str) -> u16 { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); - let port = listener.local_addr().expect("fixture address").port(); - std::thread::spawn(move || { - while let Ok((mut stream, _)) = listener.accept() { - for _ in 0..2 { - let mut buffer = [0u8; 1024]; - let Ok(read) = stream.read(&mut buffer) else { - break; - }; - let request = String::from_utf8_lossy(&buffer[..read]); - let accepted = request.starts_with("GET /health ") - || request.contains(&format!("Authorization: Bearer {expected_key}\r\n")); - let response = if accepted { - &b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"[..] - } else { - &b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"[..] - }; - if stream.write_all(response).is_err() { - break; - } - } - } - }); - port -} +const ZERO_PORT_JSON: &[u8] = + br#"{"port":0,"api_key":"k","pid":1,"epoch":1,"version":"0.2.0","started_at":"2026-09-03T12:00:00Z"}"#; +const EMPTY_KEY_JSON: &[u8] = + br#"{"port":8081,"api_key":"","pid":1,"epoch":1,"version":"0.2.0","started_at":"2026-09-03T12:00:00Z"}"#; #[test] -fn a_dead_pid_is_stale_and_cleaned() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let file = live_file(1, "key"); - let file = GatewayDiscoveryFile { - pid: dead_pid(), - ..file - }; - file.write_to(dir.path()).expect("write"); - - let resolution = resolve(dir.path()).expect("resolve"); - assert_eq!(resolution, Resolution::Stale(StaleReason::ProcessDead)); - assert!( - !gateway_discovery_file_path(dir.path()).exists(), - "the stale file was deleted" +fn stale_and_invalid_files_are_classified_and_deleted() { + use Fixture as F; + use StaleReason as S; + + const CASES: &[(&str, Fixture, bool, StaleReason)] = &[ + ("dead pid", F::DeadPid, false, S::ProcessDead), + ("foreign image", F::ForeignImage, false, S::ImageMismatch), + ("silent health", F::SilentHealth, true, S::HealthFailed), + ("rejected key", F::RejectedKey, true, S::KeyRejected), + ("zero epoch", F::ZeroEpoch, true, S::BootIdentityInvalid), + ( + "blank started_at", + F::BlankStartedAt, + true, + S::BootIdentityInvalid, + ), + ("corrupt json", F::Raw(b"not json"), true, S::Invalid), + ("zero port json", F::Raw(ZERO_PORT_JSON), true, S::Invalid), + ("empty key json", F::Raw(EMPTY_KEY_JSON), true, S::Invalid), + ]; + + let image = own_image_name(); + let absent_dir = tempfile::TempDir::new().expect("tempdir"); + assert_eq!( + resolve_named(absent_dir.path(), &image).expect("resolve absent"), + Resolution::Absent, + "absent discovery file" ); -} - -#[test] -fn an_alive_pid_with_a_foreign_image_is_stale() { - let dir = tempfile::TempDir::new().expect("tempdir"); - // The test binary is never named runvil-gateway, so the real - // image name must reject the test process's own pid. - live_file(1, "key").write_to(dir.path()).expect("write"); - let resolution = resolve(dir.path()).expect("resolve"); - assert_eq!(resolution, Resolution::Stale(StaleReason::ImageMismatch)); - assert!( - !gateway_discovery_file_path(dir.path()).exists(), - "the stale file was deleted" - ); -} + for &(label, ref fixture, use_own_image, expected) in CASES { + let dir = tempfile::TempDir::new().expect("tempdir"); + match fixture { + F::DeadPid => GatewayDiscoveryFile { + pid: dead_pid(), + ..live_file(1, "key") + } + .write_to(dir.path()) + .expect("write"), + F::ForeignImage | F::SilentHealth => { + live_file(1, "key").write_to(dir.path()).expect("write"); + } + F::RejectedKey => { + live_file(fixture_gateway("right"), "wrong") + .write_to(dir.path()) + .expect("write"); + } + F::ZeroEpoch => GatewayDiscoveryFile { + epoch: 0, + ..live_file(1, "key") + } + .write_to(dir.path()) + .expect("write"), + F::BlankStartedAt => GatewayDiscoveryFile { + started_at: " ".to_owned(), + ..live_file(1, "key") + } + .write_to(dir.path()) + .expect("write"), + F::Raw(bytes) => { + fs::write(gateway_discovery_file_path(dir.path()), bytes).expect("write raw"); + } + } -#[test] -fn a_silent_health_endpoint_is_stale() { - let dir = tempfile::TempDir::new().expect("tempdir"); - // Port 1 never listens, so every probe is refused until the - // liveness budget elapses. - live_file(1, "key").write_to(dir.path()).expect("write"); + let resolution = if use_own_image { + resolve_named(dir.path(), &image) + } else { + resolve(dir.path()) + } + .unwrap_or_else(|error| panic!("{label}: resolve failed: {error}")); - let resolution = resolve_named(dir.path(), &own_image_name()).expect("resolve"); - assert_eq!(resolution, Resolution::Stale(StaleReason::HealthFailed)); - assert!( - !gateway_discovery_file_path(dir.path()).exists(), - "the stale file was deleted" - ); + assert_eq!(resolution, Resolution::Stale(expected), "{label}"); + assert!( + !gateway_discovery_file_path(dir.path()).exists(), + "{label}: stale file was deleted" + ); + } } #[test] fn a_transiently_silent_health_endpoint_is_not_stale() { let dir = tempfile::TempDir::new().expect("tempdir"); - // The first probe connection is hung up without a response; only - // a retried probe learns the gateway is live. - let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); - let port = listener.local_addr().expect("fixture address").port(); - std::thread::spawn(move || { + let port = spawn_tcp_fixture(|listener| { let mut first = true; while let Ok((mut stream, _)) = listener.accept() { if std::mem::take(&mut first) { @@ -138,63 +116,39 @@ fn a_transiently_silent_health_endpoint_is_not_stale() { continue; } for _ in 0..2 { - let mut buffer = [0u8; 1024]; - if stream.read(&mut buffer).is_err() { - break; - } - if stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") - .is_err() + let mut buffer = [0_u8; 1024]; + if stream.read(&mut buffer).is_err() + || stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") + .is_err() { break; } } } - }); + }) + .port(); let file = live_file(port, "key"); file.write_to(dir.path()).expect("write"); - let resolution = resolve_named(dir.path(), &own_image_name()).expect("resolve"); assert_eq!( - resolution, - Resolution::Attach(file), - "one dropped probe must not reject a live gateway" - ); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "a live file is left in place" - ); -} - -#[test] -fn a_rejected_key_is_stale_and_cleaned() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let port = fixture_gateway("right"); - live_file(port, "wrong") - .write_to(dir.path()) - .expect("write"); - - let resolution = resolve_named(dir.path(), &own_image_name()).expect("resolve"); - assert_eq!(resolution, Resolution::Stale(StaleReason::KeyRejected)); - assert!( - !gateway_discovery_file_path(dir.path()).exists(), - "the stale file was deleted" + resolve_named(dir.path(), &own_image_name()).expect("resolve"), + Resolution::Attach(file) ); + assert!(gateway_discovery_file_path(dir.path()).exists()); } #[test] fn a_fully_live_file_attaches() { let dir = tempfile::TempDir::new().expect("tempdir"); - let port = fixture_gateway("right"); - let file = live_file(port, "right"); + let file = live_file(fixture_gateway("right"), "right"); file.write_to(dir.path()).expect("write"); - let resolution = resolve_named(dir.path(), &own_image_name()).expect("resolve"); - assert_eq!(resolution, Resolution::Attach(file)); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "a live file is left in place" + assert_eq!( + resolve_named(dir.path(), &own_image_name()).expect("resolve"), + Resolution::Attach(file) ); + assert!(gateway_discovery_file_path(dir.path()).exists()); } #[test] @@ -213,177 +167,131 @@ fn cancellation_during_resolve_leaves_the_gateway_discovery_file_untouched() { &worker_cancellation, |_, _, cancellation| { entered.send(()).expect("announce blocked resolve"); - let _ = cancellation.wait_timeout(std::time::Duration::from_secs(30)); + let _ = cancellation.wait_timeout(Duration::from_secs(30)); Err(crate::ValidationError::Canceled) }, ) }); blocked - .recv_timeout(std::time::Duration::from_secs(1)) - .expect("the resolve phase blocks deterministically"); + .recv_timeout(Duration::from_secs(1)) + .expect("blocked"); - let started = std::time::Instant::now(); + let started = Instant::now(); cancellation.cancel(); - let result = worker.join().expect("the resolve worker joins"); + let result = worker.join().expect("worker joins"); - assert!( - started.elapsed() < std::time::Duration::from_millis(250), - "cancellation bounds the blocked resolve" - ); + assert!(started.elapsed() < Duration::from_millis(250)); assert!(matches!(result, Err(SidecarError::Canceled))); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "cancellation never classifies or deletes the gateway discovery file" - ); + assert!(gateway_discovery_file_path(dir.path()).exists()); } #[test] -fn cancellation_immediately_before_invalid_file_removal_preserves_the_file() { - let dir = tempfile::TempDir::new().expect("tempdir"); - fs::write(gateway_discovery_file_path(dir.path()), b"not json").expect("write invalid fixture"); - let cancellation = crate::CancellationToken::new(); - let worker_cancellation = cancellation.clone(); - let run_dir = dir.path().to_owned(); - let (entered, blocked) = mpsc::channel(); - let (release, released) = mpsc::channel(); - let removals = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let worker_removals = std::sync::Arc::clone(&removals); - let worker = std::thread::spawn(move || { - resolve_named_cancellable_with_effects( - &run_dir, - "unused", - &worker_cancellation, - |_, _, _| -> Result { - panic!("an invalid file never reaches validation") - }, - || { - entered.send(()).expect("announce invalid-file removal"); - released.recv().expect("release invalid-file removal"); - }, - |run_dir| { - worker_removals.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - remove_stale(run_dir) - }, - ) - }); - blocked - .recv_timeout(std::time::Duration::from_secs(1)) - .expect("resolution pauses immediately before invalid-file removal"); - - cancellation.cancel(); - release.send(()).expect("release invalid-file removal"); - let result = worker.join().expect("resolve worker joins"); - - assert!(matches!(result, Err(SidecarError::Canceled))); - assert_eq!( - removals.load(std::sync::atomic::Ordering::SeqCst), - 0, - "invalid-file cleanup cannot begin after cancellation returns" - ); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "the canceled invalid file remains untouched" - ); -} - -#[test] -fn cancellation_immediately_before_failed_validation_removal_preserves_the_file() { - let dir = tempfile::TempDir::new().expect("tempdir"); - live_file(1, "key").write_to(dir.path()).expect("write"); - let cancellation = crate::CancellationToken::new(); - let worker_cancellation = cancellation.clone(); - let run_dir = dir.path().to_owned(); - let (entered, blocked) = mpsc::channel(); - let (release, released) = mpsc::channel(); - let removals = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let worker_removals = std::sync::Arc::clone(&removals); - let worker = std::thread::spawn(move || { - resolve_named_cancellable_with_effects( - &run_dir, - "unused", - &worker_cancellation, - |_, _, _| Err(ValidationError::Stale(StaleReason::HealthFailed)), - || { - entered.send(()).expect("announce stale-file removal"); - released.recv().expect("release stale-file removal"); - }, - |run_dir| { - worker_removals.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - remove_stale(run_dir) - }, - ) - }); - blocked - .recv_timeout(std::time::Duration::from_secs(1)) - .expect("resolution pauses immediately before stale-file removal"); - - cancellation.cancel(); - release.send(()).expect("release stale-file removal"); - let result = worker.join().expect("resolve worker joins"); - - assert!(matches!(result, Err(SidecarError::Canceled))); - assert_eq!( - removals.load(std::sync::atomic::Ordering::SeqCst), - 0, - "failed-validation cleanup cannot begin after cancellation returns" - ); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "the canceled stale file remains untouched" - ); -} - -#[test] -fn is_running_reports_a_live_gateway_without_touching_the_file() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let port = fixture_gateway("right"); - live_file(port, "right") - .write_to(dir.path()) - .expect("write"); - - assert!( - is_running_named(dir.path(), &own_image_name()), - "a fully live file reads as running" - ); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "the read-only check never deletes" - ); +fn cancellation_immediately_before_removal_preserves_the_file() { + const CASES: &[(&str, Option)] = &[ + ("invalid json", None), + ("failed validation health", Some(StaleReason::HealthFailed)), + ("failed validation key", Some(StaleReason::KeyRejected)), + ]; + + for &(label, stale_reason) in CASES { + let dir = tempfile::TempDir::new().expect("tempdir"); + if stale_reason.is_none() { + fs::write(gateway_discovery_file_path(dir.path()), b"not json").expect("write raw"); + } else { + live_file(1, "key").write_to(dir.path()).expect("write"); + } + let cancellation = crate::CancellationToken::new(); + let worker_cancellation = cancellation.clone(); + let run_dir = dir.path().to_owned(); + let (entered, blocked) = mpsc::channel(); + let (release, released) = mpsc::channel(); + let removals = Arc::new(AtomicUsize::new(0)); + let worker_removals = Arc::clone(&removals); + let worker = std::thread::spawn(move || { + resolve_named_cancellable_with_effects( + &run_dir, + "unused", + &worker_cancellation, + |_, _, _| match stale_reason { + Some(reason) => Err(ValidationError::Stale(reason)), + None => panic!("{label}: invalid file never reaches validation"), + }, + || { + entered.send(()).expect("announce removal boundary"); + released.recv().expect("release removal boundary"); + }, + |run_dir| { + worker_removals.fetch_add(1, Ordering::SeqCst); + remove_stale(run_dir) + }, + ) + }); + blocked + .recv_timeout(Duration::from_secs(1)) + .unwrap_or_else(|error| panic!("{label}: did not pause before removal: {error}")); + + cancellation.cancel(); + release.send(()).expect("release removal boundary"); + let result = worker.join().expect("resolve worker joins"); + + assert!(matches!(result, Err(SidecarError::Canceled)), "{label}"); + assert_eq!(removals.load(Ordering::SeqCst), 0, "{label}"); + assert!(gateway_discovery_file_path(dir.path()).exists(), "{label}"); + } } #[test] -fn is_running_leaves_a_stale_file_in_place() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let file = GatewayDiscoveryFile { - pid: dead_pid(), - ..live_file(1, "key") - }; - file.write_to(dir.path()).expect("write"); - - assert!( - !is_running_named(dir.path(), &own_image_name()), - "a dead pid reads as not-running" - ); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "stale-file deletion is the prospective owner's privilege" - ); -} +fn is_running_classifies_files_without_deleting_them() { + enum Case { + Absent, + Corrupt, + DeadPid, + WrongKey, + Live, + } + const CASES: &[(&str, Case, bool, bool)] = &[ + ("absent", Case::Absent, false, false), + ("corrupt json", Case::Corrupt, false, true), + ("dead pid", Case::DeadPid, false, true), + ("wrong key", Case::WrongKey, false, true), + ("live gateway", Case::Live, true, true), + ]; + + let image = own_image_name(); + for &(label, ref kind, expected_running, expect_file_exists) in CASES { + let dir = tempfile::TempDir::new().expect("tempdir"); + match kind { + Case::Absent => {} + Case::Corrupt => { + fs::write(gateway_discovery_file_path(dir.path()), b"not json").expect("write"); + } + Case::DeadPid => GatewayDiscoveryFile { + pid: dead_pid(), + ..live_file(1, "key") + } + .write_to(dir.path()) + .expect("write"), + Case::WrongKey => { + live_file(fixture_gateway("right"), "wrong") + .write_to(dir.path()) + .expect("write"); + } + Case::Live => { + live_file(fixture_gateway("right"), "right") + .write_to(dir.path()) + .expect("write"); + } + } -#[test] -fn is_running_reads_absent_and_corrupt_files_as_not_running() { - let dir = tempfile::TempDir::new().expect("tempdir"); - assert!( - !is_running_named(dir.path(), &own_image_name()), - "no gateway discovery file reads as not-running" - ); - fs::write(gateway_discovery_file_path(dir.path()), b"not json").expect("write fixture"); - assert!( - !is_running_named(dir.path(), &own_image_name()), - "a corrupt file reads as not-running and is left alone" - ); - assert!( - gateway_discovery_file_path(dir.path()).exists(), - "the corrupt file was not deleted" - ); + assert_eq!( + is_running_named(dir.path(), &image), + expected_running, + "{label}" + ); + assert_eq!( + gateway_discovery_file_path(dir.path()).exists(), + expect_file_exists, + "{label}: is_running never deletes files" + ); + } } diff --git a/crates/workshop/gateway-discovery/src/stale.rs b/crates/workshop/gateway-discovery/src/stale.rs index 761674b5..bda0b43a 100644 --- a/crates/workshop/gateway-discovery/src/stale.rs +++ b/crates/workshop/gateway-discovery/src/stale.rs @@ -103,22 +103,14 @@ pub fn resolve_for_test(run_dir: &Path, image_name: &str) -> Result Result { - let file = match GatewayDiscoveryFile::read(run_dir) { - Ok(Some(file)) => file, - Ok(None) => return Ok(Resolution::Absent), - Err(SidecarError::Parse { .. } | SidecarError::Invalid { .. }) => { - remove_stale(run_dir)?; - return Ok(Resolution::Stale(StaleReason::Invalid)); - } - Err(error) => return Err(error), - }; - match ValidatedConnection::validate_named(file, image_name) { - Ok(validated) => Ok(Resolution::Attach(validated.into_gateway_discovery_file())), - Err(reason) => { - remove_stale(run_dir)?; - Ok(Resolution::Stale(reason)) - } - } + resolve_named_cancellable_with( + run_dir, + image_name, + &CancellationToken::new(), + |file, image_name, _| { + ValidatedConnection::validate_named(file, image_name).map_err(ValidationError::Stale) + }, + ) } pub(crate) fn resolve_named_cancellable( @@ -169,36 +161,24 @@ fn resolve_named_cancellable_with_effects( if cancellation.is_canceled() { return Err(SidecarError::Canceled); } - let file = match GatewayDiscoveryFile::read(run_dir) { - Ok(Some(file)) => file, + let stale_reason = match GatewayDiscoveryFile::read(run_dir) { + Ok(Some(file)) => match validate(file, image_name, cancellation) { + Ok(validated) => { + return Ok(Resolution::Attach(validated.into_gateway_discovery_file())); + } + Err(ValidationError::Canceled) => return Err(SidecarError::Canceled), + Err(ValidationError::Stale(reason)) => reason, + }, Ok(None) if cancellation.is_canceled() => return Err(SidecarError::Canceled), Ok(None) => return Ok(Resolution::Absent), - Err(SidecarError::Parse { .. } | SidecarError::Invalid { .. }) => { - before_remove(); - remove_stale_if_active(run_dir, cancellation, &mut remove)?; - return Ok(Resolution::Stale(StaleReason::Invalid)); - } + Err(SidecarError::Parse { .. } | SidecarError::Invalid { .. }) => StaleReason::Invalid, Err(error) => return Err(error), }; - match validate(file, image_name, cancellation) { - Ok(validated) => Ok(Resolution::Attach(validated.into_gateway_discovery_file())), - Err(ValidationError::Canceled) => Err(SidecarError::Canceled), - Err(ValidationError::Stale(reason)) => { - before_remove(); - remove_stale_if_active(run_dir, cancellation, &mut remove)?; - Ok(Resolution::Stale(reason)) - } - } -} - -fn remove_stale_if_active( - run_dir: &Path, - cancellation: &CancellationToken, - remove: &mut impl FnMut(&Path) -> Result<(), SidecarError>, -) -> Result<(), SidecarError> { + before_remove(); cancellation .run_if_active(|| remove(run_dir)) - .unwrap_or(Err(SidecarError::Canceled)) + .unwrap_or(Err(SidecarError::Canceled))?; + Ok(Resolution::Stale(stale_reason)) } /// Whether the gateway discovery file in `run_dir` names a live gateway right @@ -215,7 +195,7 @@ pub fn is_running(run_dir: &Path) -> bool { /// never named `runvil-gateway` - can run the full liveness gauntlet. fn is_running_named(run_dir: &Path, image_name: &str) -> bool { match GatewayDiscoveryFile::read(run_dir) { - Ok(Some(file)) => is_live(&file, image_name), + Ok(Some(file)) => is_live(file, image_name).is_some(), // A missing, unreadable, or invalid file reads as not-running. Ok(None) | Err(_) => false, } @@ -224,18 +204,23 @@ fn is_running_named(run_dir: &Path, image_name: &str) -> bool { /// Whether the file's gateway is live right now, with no cleanup: the /// check a launch-race loser runs, since deleting is the lock holder's /// privilege. -pub(crate) fn is_live(file: &GatewayDiscoveryFile, image_name: &str) -> bool { - ValidatedConnection::validate_named(file.clone(), image_name).is_ok() +pub(crate) fn is_live( + file: GatewayDiscoveryFile, + image_name: &str, +) -> Option { + ValidatedConnection::validate_named(file, image_name) + .ok() + .map(ValidatedConnection::into_gateway_discovery_file) } pub(crate) fn is_live_cancellable( - file: &GatewayDiscoveryFile, + file: GatewayDiscoveryFile, image_name: &str, cancellation: &CancellationToken, -) -> Result { - match ValidatedConnection::validate_named_cancellable(file.clone(), image_name, cancellation) { - Ok(_) => Ok(true), - Err(ValidationError::Stale(_)) => Ok(false), +) -> Result, SidecarError> { + match ValidatedConnection::validate_named_cancellable(file, image_name, cancellation) { + Ok(validated) => Ok(Some(validated.into_gateway_discovery_file())), + Err(ValidationError::Stale(_)) => Ok(None), Err(ValidationError::Canceled) => Err(SidecarError::Canceled), } } diff --git a/crates/workshop/gateway-discovery/src/sys.rs b/crates/workshop/gateway-discovery/src/sys.rs index 046f28b9..e9572c41 100644 --- a/crates/workshop/gateway-discovery/src/sys.rs +++ b/crates/workshop/gateway-discovery/src/sys.rs @@ -19,12 +19,6 @@ impl ProcessIdentity { pub(crate) const fn new(image: PathBuf, started: u128) -> Self { Self { image, started } } - - /// Assembles a deterministic identity for validation regressions. - #[cfg(test)] - pub(crate) const fn for_test(image: PathBuf, started: u128) -> Self { - Self::new(image, started) - } } #[cfg(target_os = "linux")] diff --git a/crates/workshop/gateway-discovery/src/sys/linux.rs b/crates/workshop/gateway-discovery/src/sys/linux.rs index 7b06f1c4..332db9b0 100644 --- a/crates/workshop/gateway-discovery/src/sys/linux.rs +++ b/crates/workshop/gateway-discovery/src/sys/linux.rs @@ -1,13 +1,15 @@ //! Linux process identity lookup: `/proc//exe` supplies the image and //! field 22 of `/proc//stat` supplies the kernel start tick. +use std::fs; + use super::ProcessIdentity; /// The image and start tick for process `pid`, or `None` when the process /// disappears, changes identity during observation, or `/proc` is unreadable. pub(crate) fn process_identity(pid: u32) -> Option { let first_start = process_start(pid)?; - let image = std::fs::read_link(format!("/proc/{pid}/exe")).ok()?; + let image = fs::read_link(format!("/proc/{pid}/exe")).ok()?; let second_start = process_start(pid)?; (first_start == second_start).then(|| ProcessIdentity::new(image, u128::from(first_start))) } @@ -16,7 +18,7 @@ pub(crate) fn process_identity(pid: u32) -> Option { /// in parentheses and may itself contain spaces or closing parentheses, /// so fields are counted only after its final delimiter. fn process_start(pid: u32) -> Option { - let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; let after_command = stat.get(stat.rfind(')')? + 1..)?; after_command.split_whitespace().nth(19)?.parse().ok() } diff --git a/crates/workshop/gateway-discovery/src/sys/macos.rs b/crates/workshop/gateway-discovery/src/sys/macos.rs index 598c294d..5061b802 100644 --- a/crates/workshop/gateway-discovery/src/sys/macos.rs +++ b/crates/workshop/gateway-discovery/src/sys/macos.rs @@ -46,27 +46,27 @@ struct ProcBsdInfo { /// either query. pub(crate) fn process_identity(pid: u32) -> Option { let first_start = process_start(pid)?; - let image = process_image_path(pid)?; - let second_start = process_start(pid)?; - (first_start == second_start).then(|| ProcessIdentity::new(image, first_start)) -} - -/// Reads the kernel's path for one live process. -fn process_image_path(pid: u32) -> Option { - let pid = i32::try_from(pid).ok()?; + let raw_pid = i32::try_from(pid).ok()?; let mut buffer = vec![0u8; PROC_PIDPATHINFO_MAXSIZE as usize]; // SAFETY: `buffer` is a live allocation of exactly // PROC_PIDPATHINFO_MAXSIZE bytes and the size handed over matches it; // proc_pidpath writes at most that many bytes and returns the count // written, or a value <= 0 on error. - let written = - unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), PROC_PIDPATHINFO_MAXSIZE) }; + let written = unsafe { + libc::proc_pidpath( + raw_pid, + buffer.as_mut_ptr().cast(), + PROC_PIDPATHINFO_MAXSIZE, + ) + }; if written <= 0 { return None; } let written = usize::try_from(written).ok()?; buffer.truncate(written); - Some(PathBuf::from(OsString::from_vec(buffer))) + let image = PathBuf::from(OsString::from_vec(buffer)); + let second_start = process_start(pid)?; + (first_start == second_start).then(|| ProcessIdentity::new(image, first_start)) } /// Reads the process start timeval through `PROC_PIDTBSDINFO`. diff --git a/crates/workshop/gateway-discovery/src/sys/windows.rs b/crates/workshop/gateway-discovery/src/sys/windows.rs index 58731f16..efb6b41a 100644 --- a/crates/workshop/gateway-discovery/src/sys/windows.rs +++ b/crates/workshop/gateway-discovery/src/sys/windows.rs @@ -33,7 +33,21 @@ pub(crate) fn process_identity(pid: u32) -> Option { /// Reads one coherent image and creation time from an open process handle. fn query_identity(handle: HANDLE) -> Option { - let image = query_image_path(handle)?; + // The long-path ceiling: QueryFullProcessImageNameW fails rather than + // truncates when the buffer is too small, so one max-sized buffer + // needs no grow loop. + const BUFFER_LEN: u32 = 32768; + let mut buffer = vec![0u16; BUFFER_LEN as usize]; + let mut size = BUFFER_LEN; + // SAFETY: `buffer` is valid for `size` UTF-16 code units and `size` + // starts at its length; on success the call writes the path length + // back into `size`, never exceeding the buffer. + let ok = unsafe { QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &raw mut size) }; + if ok == 0 { + return None; + } + let length = usize::try_from(size).ok()?; + let image = PathBuf::from(OsString::from_wide(buffer.get(..length)?)); let mut creation = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0, @@ -58,22 +72,3 @@ fn query_identity(handle: HANDLE) -> Option { let started = u128::from(creation.dwHighDateTime) << 32 | u128::from(creation.dwLowDateTime); Some(ProcessIdentity::new(image, started)) } - -/// Reads the image path from an open process handle. -fn query_image_path(handle: HANDLE) -> Option { - // The long-path ceiling: QueryFullProcessImageNameW fails rather than - // truncates when the buffer is too small, so one max-sized buffer - // needs no grow loop. - const BUFFER_LEN: u32 = 32768; - let mut buffer = vec![0u16; BUFFER_LEN as usize]; - let mut size = BUFFER_LEN; - // SAFETY: `buffer` is valid for `size` UTF-16 code units and `size` - // starts at its length; on success the call writes the path length - // back into `size`, never exceeding the buffer. - let ok = unsafe { QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &raw mut size) }; - if ok == 0 { - return None; - } - let length = usize::try_from(size).ok()?; - Some(PathBuf::from(OsString::from_wide(buffer.get(..length)?))) -} diff --git a/crates/workshop/gateway-discovery/src/test_support.rs b/crates/workshop/gateway-discovery/src/test_support.rs new file mode 100644 index 00000000..30d49da1 --- /dev/null +++ b/crates/workshop/gateway-discovery/src/test_support.rs @@ -0,0 +1,97 @@ +#![cfg(test)] +//! Shared test fixtures for `workshop-gateway-discovery` unit tests. + +use std::io::{Read, Write as _}; +use std::net::{SocketAddr, TcpListener}; +use std::sync::mpsc; + +use crate::GatewayDiscoveryFile; + +/// The test process's own image name, so the pid and image checks +/// pass and the test reaches the probe under test. +pub(crate) fn own_image_name() -> String { + std::env::current_exe() + .expect("current exe") + .file_name() + .expect("the exe has a file name") + .to_string_lossy() + .into_owned() +} + +/// A gateway discovery file pointing at the test process itself. +pub(crate) fn live_file(port: u16, api_key: &str) -> GatewayDiscoveryFile { + GatewayDiscoveryFile { + port, + api_key: api_key.to_owned(), + pid: std::process::id(), + epoch: 1_757_000_000, + version: "0.2.0".to_owned(), + started_at: "2026-09-03T12:00:00Z".to_owned(), + } +} + +/// A pid guaranteed dead: a short-lived child, reaped and dropped so +/// no handle keeps the process object alive. +pub(crate) fn dead_pid() -> u32 { + let mut child = std::process::Command::new(std::env::current_exe().expect("current exe")) + .arg("--list") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .expect("spawn a short-lived child"); + let pid = child.id(); + child.wait().expect("the child exits"); + drop(child); + pid +} + +/// Binds a loopback listener on an ephemeral port and runs `serve` on a +/// background thread. +pub(crate) fn spawn_tcp_fixture(serve: impl FnOnce(TcpListener) + Send + 'static) -> SocketAddr { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); + let addr = listener.local_addr().expect("fixture address"); + std::thread::spawn(move || serve(listener)); + addr +} + +/// A fixture gateway: answers `GET /health` with 200 and the key +/// probe with 200 only when the bearer matches `expected_key`. +pub(crate) fn fixture_gateway(expected_key: &'static str) -> u16 { + spawn_tcp_fixture(move |listener| { + while let Ok((mut stream, _)) = listener.accept() { + for _ in 0..2 { + let mut buffer = [0_u8; 1024]; + let Ok(read) = stream.read(&mut buffer) else { + break; + }; + let request = String::from_utf8_lossy(&buffer[..read]); + let accepted = request.starts_with("GET /health ") + || request.contains(&format!("Authorization: Bearer {expected_key}\r\n")); + let response = if accepted { + &b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"[..] + } else { + &b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"[..] + }; + if stream.write_all(response).is_err() { + break; + } + } + } + }) + .port() +} + +/// A fixture gateway recording each request and answering with `response`. +pub(crate) fn canned_gateway(response: &'static [u8]) -> (SocketAddr, mpsc::Receiver) { + let (requests, received) = mpsc::channel(); + let addr = spawn_tcp_fixture(move |listener| { + while let Ok((mut stream, _)) = listener.accept() { + let mut buffer = [0_u8; 1024]; + if let Ok(read) = stream.read(&mut buffer) { + let _ = requests.send(String::from_utf8_lossy(&buffer[..read]).into_owned()); + } + let _ = stream.write_all(response); + } + }); + (addr, received) +} diff --git a/crates/workshop/gateway-discovery/src/validated-tests.rs b/crates/workshop/gateway-discovery/src/validated-tests.rs index 071da1a2..4aed0ddb 100644 --- a/crates/workshop/gateway-discovery/src/validated-tests.rs +++ b/crates/workshop/gateway-discovery/src/validated-tests.rs @@ -1,190 +1,121 @@ //! Unit tests for building a validated Gateway connection. -use super::*; - -use std::io::{Read, Write as _}; -use std::net::TcpListener; +use std::io::Read; +use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, mpsc}; +use super::*; use crate::GatewayDiscoveryFile; - -fn own_image_name() -> String { - std::env::current_exe() - .expect("current exe") - .file_name() - .expect("the exe has a file name") - .to_string_lossy() - .into_owned() -} - -fn connection(port: u16, api_key: &str) -> GatewayDiscoveryFile { - GatewayDiscoveryFile { - port, - api_key: api_key.to_owned(), - pid: std::process::id(), - epoch: 1_778_000_000, - version: "0.2.0".to_owned(), - started_at: "2026-05-05T12:00:00Z".to_owned(), - } +use crate::test_support::{ + dead_pid, fixture_gateway, live_file, own_image_name, spawn_tcp_fixture, +}; + +#[derive(Clone, Copy)] +enum Rejection { + WrongImage, + DeadPid, + ZeroEpoch, + EmptyStartedAt, + BlankStartedAt, + ZeroPort, + EmptyApiKey, + NewlineApiKey, + ZeroPid, + SilentHealth, + RejectedBearer, } -fn dead_pid() -> u32 { - let mut child = std::process::Command::new(std::env::current_exe().expect("current exe")) - .arg("--list") - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - .expect("spawn a short-lived child"); - let pid = child.id(); - child.wait().expect("the child exits"); - pid -} - -fn fixture_gateway(expected_key: &'static str) -> u16 { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); - let port = listener.local_addr().expect("fixture address").port(); - std::thread::spawn(move || { - while let Ok((mut stream, _)) = listener.accept() { - for _ in 0..2 { - let mut buffer = [0_u8; 1024]; - let Ok(read) = stream.read(&mut buffer) else { - break; - }; - let request = String::from_utf8_lossy(&buffer[..read]); - let accepted = request.starts_with("GET /health ") - || request.contains(&format!("Authorization: Bearer {expected_key}\r\n")); - let response = if accepted { - &b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"[..] - } else { - &b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"[..] - }; - if stream.write_all(response).is_err() { - break; - } +#[test] +fn invalid_and_stale_inputs_cannot_create_a_capability() { + use Rejection as R; + use StaleReason as S; + + const CASES: &[(&str, Rejection, StaleReason)] = &[ + ("wrong image", R::WrongImage, S::ImageMismatch), + ("dead pid", R::DeadPid, S::ProcessDead), + ("zero epoch", R::ZeroEpoch, S::BootIdentityInvalid), + ( + "empty started_at", + R::EmptyStartedAt, + S::BootIdentityInvalid, + ), + ( + "blank started_at", + R::BlankStartedAt, + S::BootIdentityInvalid, + ), + ("zero port", R::ZeroPort, S::Invalid), + ("empty api_key", R::EmptyApiKey, S::Invalid), + ("newline api_key", R::NewlineApiKey, S::Invalid), + ("zero pid", R::ZeroPid, S::Invalid), + ("silent health", R::SilentHealth, S::HealthFailed), + ("rejected bearer", R::RejectedBearer, S::KeyRejected), + ]; + + let own_image = own_image_name(); + for &(label, fixture, expected) in CASES { + let mut file = live_file(1, "key"); + let mut image = own_image.as_str(); + match fixture { + R::WrongImage => image = "not-the-test-binary", + R::DeadPid => file.pid = dead_pid(), + R::ZeroEpoch => file.epoch = 0, + R::EmptyStartedAt => file.started_at.clear(), + R::BlankStartedAt => file.started_at = " \t ".to_owned(), + R::ZeroPort => file.port = 0, + R::EmptyApiKey => file.api_key.clear(), + R::NewlineApiKey => file.api_key = "bad\nkey".to_owned(), + R::ZeroPid => file.pid = 0, + R::SilentHealth => {} + R::RejectedBearer => { + file.port = fixture_gateway("accepted"); + file.api_key = "rejected".to_owned(); } } - }); - port -} - -#[test] -fn a_wrong_process_image_cannot_create_a_capability() { - let file = connection(1, "key"); - - assert_eq!( - ValidatedConnection::validate_named(file, "not-the-test-binary"), - Err(StaleReason::ImageMismatch) - ); -} - -#[test] -fn a_dead_process_cannot_create_a_capability() { - let file = GatewayDiscoveryFile { - pid: dead_pid(), - ..connection(1, "key") - }; - - assert_eq!( - ValidatedConnection::validate_named(file, &own_image_name()), - Err(StaleReason::ProcessDead) - ); -} - -#[test] -fn a_stale_boot_identity_cannot_create_a_capability() { - let missing_epoch = GatewayDiscoveryFile { - epoch: 0, - ..connection(1, "key") - }; - assert_eq!( - ValidatedConnection::validate_named(missing_epoch, &own_image_name()), - Err(StaleReason::BootIdentityInvalid) - ); - - let missing_start = GatewayDiscoveryFile { - started_at: String::new(), - ..connection(1, "key") - }; - assert_eq!( - ValidatedConnection::validate_named(missing_start, &own_image_name()), - Err(StaleReason::BootIdentityInvalid) - ); -} - -#[test] -fn an_invalid_raw_connection_cannot_create_a_capability() { - let file = GatewayDiscoveryFile { - port: 0, - ..connection(1, "key") - }; - - assert_eq!( - ValidatedConnection::validate_named(file, &own_image_name()), - Err(StaleReason::Invalid) - ); -} - -#[test] -fn failed_health_cannot_create_a_capability() { - let file = connection(1, "key"); - - assert_eq!( - ValidatedConnection::validate_named(file, &own_image_name()), - Err(StaleReason::HealthFailed) - ); + assert_eq!( + ValidatedConnection::validate_named(file, image), + Err(expected), + "{label}" + ); + } } #[test] fn an_absolute_validation_deadline_bounds_a_slow_owner() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow owner"); - let port = listener.local_addr().expect("slow owner address").port(); - std::thread::spawn(move || { + let port = spawn_tcp_fixture(|listener| { let (mut stream, _) = listener.accept().expect("accept validation"); let mut request = [0_u8; 1024]; let _ = stream.read(&mut request); std::thread::sleep(Duration::from_secs(1)); - }); - let timeout = Duration::from_millis(100); + }) + .port(); let started = Instant::now(); let result = ValidatedConnection::validate_named_before( - connection(port, "key"), + live_file(port, "key"), &own_image_name(), - started + timeout, + started + Duration::from_millis(100), ); - assert_eq!(result, Err(StaleReason::HealthFailed)); - assert!( - started.elapsed() < Duration::from_millis(500), - "the caller's deadline caps the real network proof" - ); -} - -#[test] -fn a_rejected_bearer_cannot_create_a_capability() { - let port = fixture_gateway("accepted"); - let file = connection(port, "rejected"); - - assert_eq!( - ValidatedConnection::validate_named(file, &own_image_name()), - Err(StaleReason::KeyRejected) - ); + assert!(started.elapsed() < Duration::from_millis(500)); } #[test] fn a_new_boot_with_the_same_port_and_key_creates_a_distinct_capability() { let port = fixture_gateway("stable-key"); let original = - ValidatedConnection::validate_named(connection(port, "stable-key"), &own_image_name()) - .expect("the original connection validates"); - let replacement_file = GatewayDiscoveryFile { - epoch: original.epoch() + 1, - started_at: "2026-05-05T12:00:01Z".to_owned(), - ..connection(port, "stable-key") - }; - let replacement = ValidatedConnection::validate_named(replacement_file, &own_image_name()) - .expect("the replacement connection validates"); + ValidatedConnection::validate_named(live_file(port, "stable-key"), &own_image_name()) + .expect("original validates"); + let replacement = ValidatedConnection::validate_named( + GatewayDiscoveryFile { + epoch: original.epoch() + 1, + started_at: "2026-05-05T12:00:01Z".to_owned(), + ..live_file(port, "stable-key") + }, + &own_image_name(), + ) + .expect("replacement validates"); assert_eq!(replacement.port(), original.port()); assert_eq!(replacement.api_key(), original.api_key()); @@ -195,31 +126,29 @@ fn a_new_boot_with_the_same_port_and_key_creates_a_distinct_capability() { fn debug_output_never_contains_the_bearer() { let secret = "capability-secret"; let port = fixture_gateway(secret); - let mut raw = connection(port, secret); + let mut raw = live_file(port, secret); raw.version = format!("version-{secret}\r\n"); raw.started_at = format!("started-{secret}\t"); - let validated = ValidatedConnection::validate_named(raw, &own_image_name()) - .expect("the connection validates"); + let validated = ValidatedConnection::validate_named(raw, &own_image_name()).expect("validates"); let debug = format!("{validated:?}"); - assert!(!debug.contains(secret), "debug output redacts the bearer"); - assert!( - !debug.contains(['\r', '\n', '\t']), - "untrusted metadata cannot inject debug output" - ); - assert!(debug.contains(&port.to_string()), "the endpoint is visible"); + assert!(!debug.contains(secret)); + assert!(!debug.contains(['\r', '\n', '\t'])); + assert!(debug.contains(&port.to_string())); } #[test] fn a_process_boot_change_during_the_network_proof_is_rejected() { - let image = std::path::PathBuf::from(own_image_name()); - let before = ProcessIdentity::for_test(image.clone(), 41); - let after = ProcessIdentity::for_test(image, 42); - let mut observations = [Some(before), Some(after)].into_iter(); + let image = PathBuf::from(own_image_name()); + let mut observations = [ + Some(ProcessIdentity::new(image.clone(), 41)), + Some(ProcessIdentity::new(image, 42)), + ] + .into_iter(); assert_eq!( validate_with( - connection(8081, "key"), + live_file(8081, "key"), &own_image_name(), |_| observations.next().flatten(), |_, _, _| ConnectionProbe::Accepted, @@ -230,129 +159,112 @@ fn a_process_boot_change_during_the_network_proof_is_rejected() { } #[test] -fn cancellation_inside_the_first_identity_probe_prevents_observation() { - let cancellation = crate::CancellationToken::new(); - let worker_cancellation = cancellation.clone(); - let image_name = own_image_name(); - let identity = ProcessIdentity::for_test(std::path::PathBuf::from(&image_name), 41); - let observations = Arc::new(AtomicUsize::new(0)); - let worker_observations = Arc::clone(&observations); - let (entered, blocked) = mpsc::channel(); - let worker = std::thread::spawn(move || { - validate_cancellable_with( - connection(8081, "key"), - &image_name, - &worker_cancellation, - |_| { - entered.send(()).expect("announce identity probe"); - if !worker_cancellation.wait_timeout(Duration::from_secs(30)) { - worker_observations.fetch_add(1, Ordering::SeqCst); - } - Some(identity.clone()) - }, - |_, _, _, _| ConnectionProbe::Accepted, - ) - }); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the first process identity probe blocks deterministically"); - - let started = std::time::Instant::now(); - cancellation.cancel(); - let result = worker.join().expect("the validation worker joins"); - - assert!( - started.elapsed() < Duration::from_millis(250), - "cancellation wakes the in-progress process identity probe" - ); - assert!(matches!(result, Err(ValidationError::Canceled))); - assert_eq!( - observations.load(Ordering::SeqCst), - 0, - "no process observation occurs after cancellation" - ); -} - -#[test] -fn cancellation_during_validation_prevents_the_second_identity_observation() { - let cancellation = crate::CancellationToken::new(); - let worker_cancellation = cancellation.clone(); - let image_name = own_image_name(); - let identity = ProcessIdentity::for_test(std::path::PathBuf::from(&image_name), 41); - let observations = Arc::new(AtomicUsize::new(0)); - let worker_observations = Arc::clone(&observations); - let (entered, blocked) = mpsc::channel(); - let worker = std::thread::spawn(move || { - validate_cancellable_with( - connection(8081, "key"), - &image_name, - &worker_cancellation, - |_| { - worker_observations.fetch_add(1, Ordering::SeqCst); - Some(identity.clone()) - }, - |_, _, _, cancellation| { - entered.send(()).expect("announce blocked validation"); - let _ = cancellation.wait_timeout(Duration::from_secs(30)); - ConnectionProbe::Accepted - }, - ) - }); - blocked - .recv_timeout(Duration::from_secs(1)) - .expect("the validation phase blocks deterministically"); - - let started = std::time::Instant::now(); - cancellation.cancel(); - let result = worker.join().expect("the validation worker joins"); +fn cancellation_bounds_and_halts_validation_phases() { + #[derive(Clone, Copy)] + enum Phase { + BeforeStart, + FirstIdentityProbe, + NetworkProbe, + } + const CASES: &[(&str, Phase, usize)] = &[ + ("pre-canceled token", Phase::BeforeStart, 0), + ("inside first identity probe", Phase::FirstIdentityProbe, 0), + ("during network probe", Phase::NetworkProbe, 1), + ]; + + for &(label, phase, expected_observations) in CASES { + let cancellation = crate::CancellationToken::new(); + let worker_cancellation = cancellation.clone(); + let image_name = own_image_name(); + let identity = ProcessIdentity::new(PathBuf::from(&image_name), 41); + let observations = Arc::new(AtomicUsize::new(0)); + let worker_observations = Arc::clone(&observations); + let (entered, blocked) = mpsc::channel(); + if matches!(phase, Phase::BeforeStart) { + cancellation.cancel(); + } - assert!( - started.elapsed() < Duration::from_millis(250), - "cancellation bounds the blocked validation" - ); - assert!(matches!(result, Err(ValidationError::Canceled))); - assert_eq!( - observations.load(Ordering::SeqCst), - 1, - "validation performs no post-cancel process probe" - ); + let worker = std::thread::spawn(move || { + validate_cancellable_with( + live_file(8081, "key"), + &image_name, + &worker_cancellation, + |_| match phase { + Phase::FirstIdentityProbe => { + entered.send(()).expect("announce identity probe"); + if !worker_cancellation.wait_timeout(Duration::from_secs(30)) { + worker_observations.fetch_add(1, Ordering::SeqCst); + } + Some(identity.clone()) + } + Phase::BeforeStart | Phase::NetworkProbe => { + worker_observations.fetch_add(1, Ordering::SeqCst); + Some(identity.clone()) + } + }, + |_, _, _, cancellation| { + if matches!(phase, Phase::NetworkProbe) { + entered.send(()).expect("announce network probe"); + let _ = cancellation.wait_timeout(Duration::from_secs(30)); + } + ConnectionProbe::Accepted + }, + ) + }); + + let started = if matches!(phase, Phase::BeforeStart) { + Instant::now() + } else { + blocked + .recv_timeout(Duration::from_secs(1)) + .unwrap_or_else(|error| panic!("{label}: did not block: {error}")); + let started = Instant::now(); + cancellation.cancel(); + started + }; + let result = worker.join().expect("worker joins"); + + assert!(started.elapsed() < Duration::from_millis(250), "{label}"); + assert!(matches!(result, Err(ValidationError::Canceled)), "{label}"); + assert_eq!( + observations.load(Ordering::SeqCst), + expected_observations, + "{label}" + ); + } } #[test] fn forged_file_identity_cannot_alias_a_reused_process() { - let raw = connection(8081, "key"); - let image = std::path::PathBuf::from(own_image_name()); - let first_identity = ProcessIdentity::for_test(image.clone(), 41); - let second_identity = ProcessIdentity::for_test(image, 42); + let raw = live_file(8081, "key"); + let image = PathBuf::from(own_image_name()); + let first_id = ProcessIdentity::new(image.clone(), 41); + let second_id = ProcessIdentity::new(image, 42); let first = validate_with( raw.clone(), &own_image_name(), - |_| Some(first_identity.clone()), + |_| Some(first_id.clone()), |_, _, _| ConnectionProbe::Accepted, ) - .expect("the first coherent proof validates"); + .expect("first proof validates"); let second = validate_with( raw, &own_image_name(), - |_| Some(second_identity.clone()), + |_| Some(second_id.clone()), |_, _, _| ConnectionProbe::Accepted, ) - .expect("the replacement's coherent proof validates"); + .expect("replacement proof validates"); - assert!( - !first.same_boot(&second), - "identical attacker-controlled file fields cannot forge process identity" - ); + assert!(!first.same_boot(&second)); } #[test] fn validation_errors_never_contain_the_bearer_or_metadata() { let secret = "capability-secret"; - let mut raw = connection(8081, secret); + let mut raw = live_file(8081, secret); raw.version = format!("version-{secret}\r\n"); raw.started_at = format!("started-{secret}\t"); - let image = std::path::PathBuf::from(own_image_name()); - let identity = ProcessIdentity::for_test(image, 41); + let identity = ProcessIdentity::new(PathBuf::from(own_image_name()), 41); let error = validate_with( raw, &own_image_name(), @@ -361,13 +273,8 @@ fn validation_errors_never_contain_the_bearer_or_metadata() { ) .expect_err("the bearer is rejected"); - let debug = format!("{error:?}"); - let display = format!("{error}"); - for rendered in [debug, display] { - assert!(!rendered.contains(secret), "errors redact the bearer"); - assert!( - !rendered.contains(['\r', '\n', '\t']), - "untrusted metadata cannot inject errors" - ); + for rendered in [format!("{error:?}"), format!("{error}")] { + assert!(!rendered.contains(secret)); + assert!(!rendered.contains(['\r', '\n', '\t'])); } } diff --git a/crates/workshop/gateway-discovery/src/validated.rs b/crates/workshop/gateway-discovery/src/validated.rs index 9be99eee..397fffe8 100644 --- a/crates/workshop/gateway-discovery/src/validated.rs +++ b/crates/workshop/gateway-discovery/src/validated.rs @@ -3,7 +3,6 @@ use std::ffi::OsStr; use std::fmt; -use std::path::Path; use std::time::{Duration, Instant}; use crate::health::{self, ConnectionProbe}; @@ -115,15 +114,17 @@ impl ValidatedConnection { image_name: &str, deadline: Instant, ) -> Result { - validate_before_with( + validate_core( connection, image_name, - deadline, + Some(deadline), + None, process_identity, - |address, bearer, deadline| { + |address, bearer| { health::probe_connection_until(address, KEY_PROBE_PATH, bearer, deadline) }, ) + .map_err(stale_reason) } pub(crate) fn validate_named_cancellable( @@ -220,6 +221,13 @@ impl fmt::Debug for ValidatedConnection { } } +fn stale_reason(error: ValidationError) -> StaleReason { + match error { + ValidationError::Stale(reason) => reason, + ValidationError::Canceled => StaleReason::HealthFailed, + } +} + /// Performs one validation while allowing deterministic observation and /// network seams in unit tests. Production passes only the platform process /// observer and the private shared probe. @@ -229,108 +237,97 @@ fn validate_with( observe_process: impl FnMut(u32) -> Option, prove_connection: impl FnOnce(&str, &str, Instant) -> ConnectionProbe, ) -> Result { - validate_before_with( + let deadline = Instant::now() + LIVENESS_BUDGET; + validate_core( connection, image_name, - Instant::now() + LIVENESS_BUDGET, + Some(deadline), + None, observe_process, - prove_connection, + |address, bearer| prove_connection(address, bearer, deadline), ) + .map_err(stale_reason) } -fn validate_before_with( +fn validate_cancellable_with( connection: GatewayDiscoveryFile, image_name: &str, - deadline: Instant, - mut observe_process: impl FnMut(u32) -> Option, - prove_connection: impl FnOnce(&str, &str, Instant) -> ConnectionProbe, -) -> Result { - if Instant::now() >= deadline { - return Err(StaleReason::HealthFailed); - } - if connection.validation_error().is_some() { - return Err(StaleReason::Invalid); - } - let Some(before) = observe_process(connection.pid) else { - return Err(StaleReason::ProcessDead); - }; - if !image_name_matches(&before.image, image_name) { - return Err(StaleReason::ImageMismatch); - } - if !connection.has_boot_identity() { - return Err(StaleReason::BootIdentityInvalid); - } - if Instant::now() >= deadline { - return Err(StaleReason::HealthFailed); - } - let address = format!("127.0.0.1:{}", connection.port); - match prove_connection(&address, &connection.api_key, deadline) { - ConnectionProbe::Canceled | ConnectionProbe::HealthFailed => { - return Err(StaleReason::HealthFailed); - } - ConnectionProbe::KeyRejected => return Err(StaleReason::KeyRejected), - ConnectionProbe::Accepted => {} - } - let Some(after) = observe_process(connection.pid) else { - return Err(StaleReason::ProcessChanged); - }; - if before != after { - return Err(StaleReason::ProcessChanged); - } - Ok(ValidatedConnection { + cancellation: &CancellationToken, + observe_process: impl FnMut(u32) -> Option, + prove_connection: impl FnOnce(&str, &str, Duration, &CancellationToken) -> ConnectionProbe, +) -> Result { + validate_core( connection, - process_identity: before, - }) + image_name, + None, + Some(cancellation), + observe_process, + |address, bearer| prove_connection(address, bearer, LIVENESS_BUDGET, cancellation), + ) } -fn validate_cancellable_with( +fn validate_core( connection: GatewayDiscoveryFile, image_name: &str, - cancellation: &CancellationToken, + deadline: Option, + cancellation: Option<&CancellationToken>, mut observe_process: impl FnMut(u32) -> Option, - prove_connection: impl FnOnce(&str, &str, Duration, &CancellationToken) -> ConnectionProbe, + prove_connection: impl FnOnce(&str, &str) -> ConnectionProbe, ) -> Result { - if cancellation.is_canceled() { + let pid = connection.pid; + let mut observe = || match cancellation { + Some(token) => token + .run_if_active(|| observe_process(pid)) + .ok_or(ValidationError::Canceled), + None => Ok(observe_process(pid)), + }; + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(ValidationError::Canceled); } + if deadline.is_some_and(|limit| Instant::now() >= limit) { + return Err(StaleReason::HealthFailed.into()); + } if connection.validation_error().is_some() { return Err(StaleReason::Invalid.into()); } - let Some(before_observation) = cancellation.run_if_active(|| observe_process(connection.pid)) - else { - return Err(ValidationError::Canceled); - }; - let Some(before) = before_observation else { + let Some(before) = observe()? else { return Err(StaleReason::ProcessDead.into()); }; - if cancellation.is_canceled() { + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(ValidationError::Canceled); } - if !image_name_matches(&before.image, image_name) { + if !before + .image + .file_name() + .is_some_and(|name| image_file_name_matches(name, image_name)) + { return Err(StaleReason::ImageMismatch.into()); } if !connection.has_boot_identity() { return Err(StaleReason::BootIdentityInvalid.into()); } + if deadline.is_some_and(|limit| Instant::now() >= limit) { + return Err(StaleReason::HealthFailed.into()); + } let address = format!("127.0.0.1:{}", connection.port); - let proof = prove_connection(&address, &connection.api_key, LIVENESS_BUDGET, cancellation); - if cancellation.is_canceled() || proof == ConnectionProbe::Canceled { + let proof = prove_connection(&address, &connection.api_key); + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(ValidationError::Canceled); } match proof { - ConnectionProbe::HealthFailed => return Err(StaleReason::HealthFailed.into()), + ConnectionProbe::Canceled if cancellation.is_some() => { + return Err(ValidationError::Canceled); + } + ConnectionProbe::Canceled | ConnectionProbe::HealthFailed => { + return Err(StaleReason::HealthFailed.into()); + } ConnectionProbe::KeyRejected => return Err(StaleReason::KeyRejected.into()), ConnectionProbe::Accepted => {} - ConnectionProbe::Canceled => return Err(ValidationError::Canceled), } - let Some(after_observation) = cancellation.run_if_active(|| observe_process(connection.pid)) - else { - return Err(ValidationError::Canceled); - }; - let Some(after) = after_observation else { + let Some(after) = observe()? else { return Err(StaleReason::ProcessChanged.into()); }; - if cancellation.is_canceled() { + if cancellation.is_some_and(CancellationToken::is_canceled) { return Err(ValidationError::Canceled); } if before != after { @@ -342,13 +339,6 @@ fn validate_cancellable_with( }) } -fn image_name_matches(image: &Path, expected: &str) -> bool { - let Some(name) = image.file_name() else { - return false; - }; - image_file_name_matches(name, expected) -} - #[cfg(windows)] fn image_file_name_matches(name: &OsStr, expected: &str) -> bool { name.to_string_lossy().eq_ignore_ascii_case(expected) diff --git a/crates/workshop/gateway/src/binding.rs b/crates/workshop/gateway/src/binding.rs index ed4ff4d7..292fa5bf 100644 --- a/crates/workshop/gateway/src/binding.rs +++ b/crates/workshop/gateway/src/binding.rs @@ -8,16 +8,18 @@ //! publication permanently. Explicitly configured endpoints never receive //! an updater from the desktop app. -mod publication; -mod shutdown; - use std::fmt; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError, TryLockError}; +use std::time::Duration; use arc_swap::ArcSwap; use tokio::sync::watch; use crate::client::{GatewayClient, GatewayError}; +use crate::discovery::{self, CancellationToken, ShutdownError, ValidatedConnection}; + +/// Cancellable replacement lock retry cadence. +const REPLACEMENT_RETRY_INTERVAL: Duration = Duration::from_millis(10); /// One immutable generation of every gateway client credential. pub struct GatewaySnapshot { @@ -28,7 +30,7 @@ pub struct GatewaySnapshot { /// Monotonic generation assigned before this snapshot is published. generation: u64, /// Proven local gateway boot, absent for an explicitly configured endpoint. - identity: Option, + identity: Option, } impl fmt::Debug for GatewaySnapshot { @@ -68,6 +70,34 @@ impl GatewaySnapshot { pub fn generation(&self) -> u64 { self.generation } + + /// Whether this generation is a supervised local sidecar: it holds + /// a validated local gateway boot, so the workshop may shut it down + /// and its supervisor relaunches the sibling. An explicitly configured + /// endpoint (a LAN gateway) never is. + #[must_use] + pub fn is_sidecar(&self) -> bool { + self.identity.is_some() + } + + /// Requests shutdown from the validated local gateway this snapshot + /// names, posting the authenticated `POST /shutdown`. + /// + /// Returns `Ok(false)` without sending a request when the snapshot + /// came from explicit configuration and therefore grants no local + /// shutdown authority. The request is blocking I/O; an async caller + /// runs it off the executor. + /// + /// # Errors + /// Returns [`ShutdownError`] when the local gateway refuses the request or + /// cannot be reached. + pub fn request_shutdown(&self) -> Result { + let Some(identity) = self.identity.as_ref() else { + return Ok(false); + }; + discovery::request_shutdown(identity)?; + Ok(true) + } } /// Shared atomic gateway snapshot and replacement notification. @@ -123,7 +153,7 @@ impl GatewayBinding { pub fn new_with_identity( base_url: &str, api_key: &str, - identity: Option, + identity: Option, ) -> Result { Ok(Self::from_snapshot(build_snapshot( base_url, api_key, identity, @@ -189,7 +219,7 @@ impl GatewayBinding { &self, base_url: &str, api_key: &str, - identity: Option, + identity: Option, ) -> Result<(), GatewayPublicationError> { let snapshot = build_snapshot(base_url, api_key, identity)?; self.publish_snapshot(snapshot) @@ -204,6 +234,46 @@ impl GatewayBinding { self.commit(&mut publication, snapshot) } + fn replace_with_identity_cancellable_with_wait( + &self, + base_url: &str, + api_key: &str, + identity: ValidatedConnection, + cancellation: &CancellationToken, + mut wait: impl FnMut(&CancellationToken, Duration) -> bool, + ) -> Result { + let canceled_outcome = || { + if self.publication_closed() { + Err(GatewayPublicationError::PublicationClosed) + } else { + Ok(false) + } + }; + if cancellation.is_canceled() { + return canceled_outcome(); + } + let snapshot = build_snapshot(base_url, api_key, Some(identity))?; + cancellation + .run_if_active(|| { + let mut publication = loop { + match self.publication.try_lock() { + Ok(publication) => break publication, + Err(TryLockError::Poisoned(error)) => break error.into_inner(), + Err(TryLockError::WouldBlock) => { + if wait(cancellation, REPLACEMENT_RETRY_INTERVAL) { + return Ok(false); + } + } + } + }; + if cancellation.is_canceled() { + return Ok(false); + } + self.commit(&mut publication, snapshot).map(|()| true) + }) + .unwrap_or_else(canceled_outcome) + } + /// Stores `snapshot` as the next generation under the held publication /// lock, then wakes consumers, unless teardown closed publication. fn commit( @@ -275,7 +345,7 @@ impl GatewayUpdater { #[cfg(any(test, feature = "test-fixtures"))] pub fn replace_sidecar( &self, - connection: &crate::discovery::ValidatedConnection, + connection: &ValidatedConnection, ) -> Result<(), GatewayPublicationError> { self.binding.replace_with_identity( &format!("http://127.0.0.1:{}", connection.port()), @@ -284,6 +354,30 @@ impl GatewayUpdater { ) } + /// Atomically replaces the local gateway unless caller cancellation wins. + /// + /// Returns `Ok(false)` without publication when cancellation wins while + /// another publisher owns the replacement lock. + /// + /// # Errors + /// Returns [`GatewayPublicationError::Build`] if the replacement clients + /// cannot initialize, or + /// [`GatewayPublicationError::PublicationClosed`] after teardown revokes + /// replacement publication. + pub fn replace_sidecar_cancellable( + &self, + connection: &ValidatedConnection, + cancellation: &CancellationToken, + ) -> Result { + self.binding.replace_with_identity_cancellable_with_wait( + &format!("http://127.0.0.1:{}", connection.port()), + connection.api_key(), + connection.clone(), + cancellation, + CancellationToken::wait_timeout, + ) + } + /// Replaces the configured gateway in the crate's integration fixtures /// without manufacturing a production sidecar capability. /// @@ -311,6 +405,21 @@ impl GatewayUpdater { pub fn publication_closed(&self) -> bool { self.binding.publication_closed() } + + /// Requests shutdown from the validated local gateway in the current + /// consumer snapshot, as that snapshot's + /// [`GatewaySnapshot::request_shutdown`] does. + /// + /// Returns `Ok(false)` without sending a request when the current gateway + /// came from explicit configuration and therefore grants no local shutdown + /// authority. + /// + /// # Errors + /// Returns [`ShutdownError`] when the current local gateway refuses the + /// request or cannot be reached. + pub fn request_shutdown(&self) -> Result { + self.binding.snapshot().request_shutdown() + } } /// Builds all clients before publication so URL and bearer never tear. @@ -318,7 +427,7 @@ impl GatewayUpdater { fn build_snapshot( base_url: &str, api_key: &str, - identity: Option, + identity: Option, ) -> Result { Ok(GatewaySnapshot { client: GatewayClient::new(base_url, api_key)?, diff --git a/crates/workshop/gateway/src/binding/publication.rs b/crates/workshop/gateway/src/binding/publication.rs deleted file mode 100644 index d1f1b0f0..00000000 --- a/crates/workshop/gateway/src/binding/publication.rs +++ /dev/null @@ -1,95 +0,0 @@ -//! Cancellation-aware publication of validated gateway replacements. - -use std::sync::TryLockError; -use std::time::Duration; - -use super::{GatewayBinding, GatewayPublicationError, GatewayUpdater, build_snapshot}; - -/// Cancellable replacement lock retry cadence. -const REPLACEMENT_RETRY_INTERVAL: Duration = Duration::from_millis(10); - -impl GatewayBinding { - fn replace_with_identity_cancellable( - &self, - base_url: &str, - api_key: &str, - identity: crate::discovery::ValidatedConnection, - cancellation: &crate::discovery::CancellationToken, - ) -> Result { - self.replace_with_identity_cancellable_with_wait( - base_url, - api_key, - identity, - cancellation, - crate::discovery::CancellationToken::wait_timeout, - ) - } - - pub(super) fn replace_with_identity_cancellable_with_wait( - &self, - base_url: &str, - api_key: &str, - identity: crate::discovery::ValidatedConnection, - cancellation: &crate::discovery::CancellationToken, - mut wait: impl FnMut(&crate::discovery::CancellationToken, Duration) -> bool, - ) -> Result { - if cancellation.is_canceled() { - return if self.publication_closed() { - Err(GatewayPublicationError::PublicationClosed) - } else { - Ok(false) - }; - } - let snapshot = build_snapshot(base_url, api_key, Some(identity))?; - cancellation - .run_if_active(|| { - let mut publication = loop { - match self.publication.try_lock() { - Ok(publication) => break publication, - Err(TryLockError::Poisoned(error)) => break error.into_inner(), - Err(TryLockError::WouldBlock) => { - if wait(cancellation, REPLACEMENT_RETRY_INTERVAL) { - return Ok(false); - } - } - } - }; - if cancellation.is_canceled() { - return Ok(false); - } - self.commit(&mut publication, snapshot).map(|()| true) - }) - .unwrap_or_else(|| { - if self.publication_closed() { - Err(GatewayPublicationError::PublicationClosed) - } else { - Ok(false) - } - }) - } -} - -impl GatewayUpdater { - /// Atomically replaces the local gateway unless caller cancellation wins. - /// - /// Returns `Ok(false)` without publication when cancellation wins while - /// another publisher owns the replacement lock. - /// - /// # Errors - /// Returns [`GatewayPublicationError::Build`] if the replacement clients - /// cannot initialize, or - /// [`GatewayPublicationError::PublicationClosed`] after teardown revokes - /// replacement publication. - pub fn replace_sidecar_cancellable( - &self, - connection: &crate::discovery::ValidatedConnection, - cancellation: &crate::discovery::CancellationToken, - ) -> Result { - self.binding.replace_with_identity_cancellable( - &format!("http://127.0.0.1:{}", connection.port()), - connection.api_key(), - connection.clone(), - cancellation, - ) - } -} diff --git a/crates/workshop/gateway/src/binding/shutdown.rs b/crates/workshop/gateway/src/binding/shutdown.rs deleted file mode 100644 index cef97ddc..00000000 --- a/crates/workshop/gateway/src/binding/shutdown.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! Shutdown authority derived from a gateway snapshot's validated identity. - -use super::{GatewaySnapshot, GatewayUpdater}; - -impl GatewaySnapshot { - /// Whether this generation is a supervised local sidecar: it holds - /// a validated local gateway boot, so the workshop may shut it down - /// and its supervisor relaunches the sibling. An explicitly configured - /// endpoint (a LAN gateway) never is. - #[must_use] - pub fn is_sidecar(&self) -> bool { - self.identity.is_some() - } - - /// Requests shutdown from the validated local gateway this snapshot - /// names, posting the authenticated `POST /shutdown`. - /// - /// Returns `Ok(false)` without sending a request when the snapshot - /// came from explicit configuration and therefore grants no local - /// shutdown authority. The request is blocking I/O; an async caller - /// runs it off the executor. - /// - /// # Errors - /// Returns [`crate::discovery::ShutdownError`] when the local gateway - /// refuses the request or cannot be reached. - pub fn request_shutdown(&self) -> Result { - let Some(identity) = self.identity.as_ref() else { - return Ok(false); - }; - crate::discovery::request_shutdown(identity)?; - Ok(true) - } -} - -impl GatewayUpdater { - /// Requests shutdown from the validated local gateway in the current - /// consumer snapshot, as that snapshot's - /// [`GatewaySnapshot::request_shutdown`] does. - /// - /// Returns `Ok(false)` without sending a request when the current gateway - /// came from explicit configuration and therefore grants no local shutdown - /// authority. - /// - /// # Errors - /// Returns [`crate::discovery::ShutdownError`] when the current local - /// gateway refuses the request or cannot be reached. - pub fn request_shutdown(&self) -> Result { - self.binding.snapshot().request_shutdown() - } -} diff --git a/crates/workshop/gateway/src/client.rs b/crates/workshop/gateway/src/client.rs index 66615b31..e9438f95 100644 --- a/crates/workshop/gateway/src/client.rs +++ b/crates/workshop/gateway/src/client.rs @@ -7,18 +7,24 @@ //! subscription is decoded from SSE into a [`ProgressStream`] of decoded //! snapshots. +use std::error::Error; use std::fmt; +use std::io; +use std::pin::Pin; use std::time::Duration; -mod events; -mod progress_stream; -mod socket; -mod sse; +use futures_util::{Stream, stream}; +use reqwest::header::CONTENT_TYPE; +use reqwest::{Client, Method, RequestBuilder, Response, StatusCode}; +use serde::Deserialize; +use tokio::net::TcpStream; +use tokio::time; +use tokio_tungstenite::tungstenite::client::IntoClientRequest as _; +use tokio_tungstenite::tungstenite::http::header::AUTHORIZATION; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; +use url::Url; -pub use events::{ForwardedResponse, GatewayResponse, SwitchProfileBody, SwitchResponse}; -pub(crate) use progress_stream::ProgressStream; -pub use socket::GatewayRealtimeSocket; -use sse::read; +use crate::progress::Progress; /// Default bound on a single `GET /health` probe: a gateway that accepts /// the connection but never answers must still read as unreachable, and two @@ -37,6 +43,79 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); /// body stays open-ended. pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +/// The largest single SSE event block buffered before the stream refuses +/// it, in bytes. A peer that never sends a blank-line terminator would +/// otherwise grow the reassembly buffer unbounded; sized well above any +/// realistic progress event. +const MAX_EVENT_BLOCK: usize = 1024 * 1024; + +/// The largest error body kept for a subscription diagnostic, in bytes. +const MAX_ERROR_BODY: usize = 2000; + +/// An authenticated WebSocket connection to the gateway's Realtime transcription. +pub type GatewayRealtimeSocket = WebSocketStream>; + +/// A stream of decoded [`Progress`] snapshots from the gateway, in +/// arrival order. +/// +/// A `data:` block that does not decode is yielded as one error item +/// without ending the stream; a read failure or an event block oversized +/// beyond `MAX_EVENT_BLOCK` is yielded as one error item that ends the +/// stream. The stream ends when the gateway closes the body; whether to +/// resubscribe is the caller's decision. +pub(crate) type ProgressStream = Pin> + Send>>; + +/// A gateway HTTP response captured for verbatim relay. +#[derive(Debug)] +pub struct GatewayResponse { + /// The gateway's status code, relayed unchanged. + pub status: StatusCode, + /// The gateway's response body, relayed byte-for-byte. + pub body: Vec, +} + +/// A gateway response captured for the config-panel proxy: the relay +/// keeps the content type alongside the status and body, because the +/// config UI distinguishes a buffered JSON answer from an SSE stream by +/// it. +#[derive(Debug)] +pub struct ForwardedResponse { + /// The gateway's status code, relayed unchanged. + pub status: StatusCode, + /// The gateway's `Content-Type`, when it sent one. + pub content_type: Option, + /// The gateway's response body, relayed byte-for-byte. + pub body: Vec, +} + +/// The gateway's answer to a profile selection, `POST /admin/switch-profile`. +/// +/// An accepted selection answers one JSON document decoding as +/// [`SwitchProfileBody`]: the gateway persisted the selection and reports +/// whether it must restart to load it. A refusal (bad auth, a malformed or +/// undefined name) is buffered rather than reported as an error, matching +/// the relay contract of the other client methods. +#[derive(Debug)] +#[non_exhaustive] +pub enum SwitchResponse { + /// The gateway accepted and persisted the selection. + Selected(SwitchProfileBody), + + /// A refusal, buffered: the gateway's error envelope. + Buffered(GatewayResponse), +} + +/// The body of an accepted profile selection. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct SwitchProfileBody { + /// The selection now persisted: a profile name, or `None` for no + /// profile. + pub profile: Option, + /// Whether the gateway must restart before the selection is served; + /// `false` when the selection already matches the running profile. + pub restart_required: bool, +} + /// A gateway request failure. #[derive(Debug, thiserror::Error)] #[non_exhaustive] @@ -44,18 +123,18 @@ pub enum GatewayError { /// The HTTP client could not be built. #[non_exhaustive] #[error("build gateway http client")] - Build(#[source] Box), + Build(#[source] Box), /// The request could not be sent or no response arrived (connect /// refused, DNS, TLS, timeout). #[non_exhaustive] #[error("gateway transport error")] - Transport(#[source] Box), + Transport(#[source] Box), /// The response body could not be read to completion. #[non_exhaustive] #[error("read gateway response body")] - ReadBody(#[source] Box), + ReadBody(#[source] Box), /// The gateway answered a streaming-only request with a non-success /// status (for example 401 on a rejected token). The body is bounded @@ -64,7 +143,7 @@ pub enum GatewayError { #[error("gateway answered status {status}: {body}")] Status { /// The gateway's status code. - status: reqwest::StatusCode, + status: StatusCode, /// The gateway's error body, bounded and control-escaped. body: String, }, @@ -79,7 +158,7 @@ pub enum GatewayError { message: String, /// The decode failure, when the block or body was undecodable. #[source] - source: Option>, + source: Option>, }, } @@ -88,7 +167,7 @@ impl GatewayError { /// error-mapping fixtures. #[cfg(feature = "test-fixtures")] #[must_use] - pub fn transport_for_test(source: Box) -> Self { + pub fn transport_for_test(source: Box) -> Self { Self::Transport(source) } } @@ -98,7 +177,7 @@ impl GatewayError { /// for gateways running with authentication disabled. #[derive(Clone)] pub struct GatewayClient { - http: reqwest::Client, + http: Client, pub(crate) base_url: String, pub(crate) api_key: String, /// Whole-request bound for buffered calls; header-phase bound for @@ -110,7 +189,7 @@ pub struct GatewayClient { // Manual so the bearer key is never written to logs. impl fmt::Debug for GatewayClient { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("GatewayClient") .field("base_url", &self.base_url) .field("api_key", &"") @@ -128,28 +207,19 @@ impl GatewayClient { /// # Errors /// Returns [`GatewayError::Build`] if the TLS backend cannot initialize. pub fn new(base_url: &str, api_key: &str) -> Result { - let http = reqwest::Client::builder() + let http = Client::builder() .connect_timeout(CONNECT_TIMEOUT) .build() .map_err(|source| GatewayError::Build(Box::new(source)))?; Ok(Self { http, - base_url: base_url.trim_end_matches('/').to_string(), - api_key: api_key.to_string(), + base_url: base_url.trim_end_matches('/').to_owned(), + api_key: api_key.to_owned(), request_timeout: REQUEST_TIMEOUT, health_timeout: HEALTH_PROBE_TIMEOUT, }) } - /// Overrides the request and probe bounds, so tests can trip them - /// without waiting out the production values. - #[cfg(test)] - pub(crate) fn with_timeouts_for_test(mut self, request: Duration, health: Duration) -> Self { - self.request_timeout = request; - self.health_timeout = health; - self - } - /// Sends `request`, bounding the wait for the response headers on the /// client's request timeout. /// @@ -158,11 +228,8 @@ impl GatewayClient { /// call rather than hang its caller, but an accepted stream may /// legitimately run for minutes, so only the header phase is bounded /// and the body stream stays open-ended. - async fn send_bounded( - &self, - request: reqwest::RequestBuilder, - ) -> Result { - match tokio::time::timeout(self.request_timeout, request.send()).await { + async fn send_bounded(&self, request: RequestBuilder) -> Result { + match time::timeout(self.request_timeout, request.send()).await { Ok(Ok(response)) => Ok(response), Ok(Err(source)) => Err(GatewayError::Transport(Box::new(source))), Err(elapsed) => Err(GatewayError::Transport(Box::new(elapsed))), @@ -172,7 +239,7 @@ impl GatewayClient { /// Applies bearer authentication to `request`, unless the client was /// built with an empty API key, in which case the request goes out with /// no `Authorization` header. - fn authorize(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + fn authorize(&self, request: RequestBuilder) -> RequestBuilder { if self.api_key.is_empty() { request } else { @@ -201,7 +268,7 @@ impl GatewayClient { /// [`GatewayError::ReadBody`] if the response body cannot be read. pub async fn forward( &self, - method: reqwest::Method, + method: Method, path_and_query: &str, body: Option>, ) -> Result { @@ -210,22 +277,20 @@ impl GatewayClient { .request(method, format!("{}{}", self.base_url, path_and_query)), ); if let Some(bytes) = body { - request = request - .header(reqwest::header::CONTENT_TYPE, "application/json") - .body(bytes); + request = request.header(CONTENT_TYPE, "application/json").body(bytes); } let response = self.send_bounded(request).await?; let status = response.status(); let content_type = response .headers() - .get(reqwest::header::CONTENT_TYPE) + .get(CONTENT_TYPE) .and_then(|value| value.to_str().ok()) - .map(str::to_string); + .map(str::to_owned); let body = response .bytes() .await .map_err(|source| GatewayError::ReadBody(Box::new(source)))? - .to_vec(); + .into(); Ok(ForwardedResponse { status, content_type, @@ -297,7 +362,7 @@ impl GatewayClient { .send() .await .map_err(|source| GatewayError::Transport(Box::new(source)))?; - read(response).await + read_response(response).await } /// Posts a profile selection to `POST /admin/switch-profile`: `name` @@ -325,7 +390,7 @@ impl GatewayClient { .send() .await .map_err(|source| GatewayError::Transport(Box::new(source)))?; - let answer = read(response).await?; + let answer = read_response(response).await?; if !answer.status.is_success() { return Ok(SwitchResponse::Buffered(answer)); } @@ -337,6 +402,37 @@ impl GatewayClient { }) } + /// Opens the gateway's authenticated Realtime transcription socket. + /// + /// The target is fixed to `/v1/realtime?intent=transcription`; browser + /// query parameters and handshake policy headers never cross the relay. + /// + /// # Errors + /// Returns [`GatewayError::Transport`] if the socket cannot be + /// connected (the header bound elapsing included). + pub async fn connect_realtime(&self) -> Result { + let mut request = realtime_url(&self.base_url)? + .as_str() + .into_client_request() + .map_err(|source| GatewayError::Transport(Box::new(source)))?; + if !self.api_key.is_empty() { + let value = format!("Bearer {}", self.api_key) + .parse() + .map_err(|source| GatewayError::Transport(Box::new(source)))?; + request.headers_mut().insert(AUTHORIZATION, value); + } + match time::timeout( + self.request_timeout, + tokio_tungstenite::connect_async(request), + ) + .await + { + Ok(Ok((socket, _response))) => Ok(socket), + Ok(Err(source)) => Err(GatewayError::Transport(Box::new(source))), + Err(elapsed) => Err(GatewayError::Transport(Box::new(elapsed))), + } + } + /// Subscribes to the gateway's `GET /admin/progress` event stream. /// /// The returned stream yields every progress event the gateway @@ -363,10 +459,184 @@ impl GatewayClient { /// read. pub async fn subscribe_progress(&self) -> Result { let request = self.authorize(self.http.get(format!("{}/admin/progress", self.base_url))); - let response = self.send_bounded(request).await?; - progress_stream::subscribe(response).await + let mut response = self.send_bounded(request).await?; + let status = response.status(); + if !status.is_success() { + let mut buffer: Vec = Vec::new(); + while buffer.len() < MAX_ERROR_BODY { + match response.chunk().await { + Ok(Some(chunk)) => { + let take = (MAX_ERROR_BODY - buffer.len()).min(chunk.len()); + buffer.extend_from_slice(&chunk[..take]); + if take < chunk.len() { + break; + } + } + Ok(None) => break, + Err(source) => return Err(GatewayError::ReadBody(Box::new(source))), + } + } + let body = if buffer.is_empty() { + "(empty body)".to_owned() + } else { + let lossy = String::from_utf8_lossy(&buffer); + let mut escaped = String::with_capacity(lossy.len()); + for ch in lossy.chars() { + if ch.is_control() { + escaped.extend(ch.escape_default()); + } else { + escaped.push(ch); + } + } + escaped + }; + return Err(GatewayError::Status { status, body }); + } + let events = stream::unfold( + (response, Vec::new(), false), + |(mut response, mut buffer, mut failed)| async move { + loop { + if let Some(item) = next_buffered_event(&mut buffer) { + return Some((item, (response, buffer, failed))); + } + if failed { + return None; + } + match response.chunk().await { + Ok(Some(chunk)) => { + if buffer.len() + chunk.len() > MAX_EVENT_BLOCK { + failed = true; + let item = Err(GatewayError::Malformed { + message: format!( + "progress event block exceeds the {MAX_EVENT_BLOCK}-byte limit" + ), + source: None, + }); + return Some((item, (response, buffer, failed))); + } + buffer.extend_from_slice(&chunk); + } + // An incomplete trailing block is discarded, matching + // the SSE rule that only blank-line-terminated blocks + // dispatch. + Ok(None) => return None, + Err(source) => { + failed = true; + let item = Err(GatewayError::ReadBody(Box::new(source))); + return Some((item, (response, buffer, failed))); + } + } + } + }, + ); + Ok(Box::pin(events)) } } +/// Captures the status and raw body of a gateway response. +async fn read_response(response: Response) -> Result { + let status = response.status(); + let body = response + .bytes() + .await + .map_err(|source| GatewayError::ReadBody(Box::new(source)))? + .into(); + Ok(GatewayResponse { status, body }) +} + +/// The Realtime transcription URL under `base_url`, upgraded to its +/// WebSocket scheme: http to ws and https to wss. +fn realtime_url(base_url: &str) -> Result { + let mut url = + Url::parse(base_url).map_err(|source| GatewayError::Transport(Box::new(source)))?; + let scheme = match url.scheme() { + "http" => "ws", + "https" => "wss", + scheme => { + return Err(GatewayError::Transport(Box::new(io::Error::new( + io::ErrorKind::InvalidInput, + format!("gateway URL scheme {scheme:?} cannot be upgraded to a WebSocket"), + )))); + } + }; + url.set_scheme(scheme).map_err(|()| { + GatewayError::Transport(Box::new(io::Error::new( + io::ErrorKind::InvalidInput, + "gateway URL scheme cannot be converted to WebSocket", + ))) + })?; + let path = format!("{}/v1/realtime", url.path().trim_end_matches('/')); + url.set_path(&path); + url.set_query(Some("intent=transcription")); + url.set_fragment(None); + Ok(url) +} + +/// Pops the next decodable snapshot out of `buffer`, or `None` when no +/// complete block is buffered yet. Comment-only blocks (heartbeats) are +/// consumed and skipped. +fn next_buffered_event(buffer: &mut Vec) -> Option> { + loop { + let mut start = 0; + let end = loop { + let (length, next) = first_line(buffer.get(start..)?)?; + if length == 0 { + break start + next; + } + start += next; + }; + let mut single: Option<&[u8]> = None; + let mut multi: Vec = Vec::new(); + let mut unread = &buffer[..end]; + while let Some((length, next)) = first_line(unread) { + let line = &unread[..length]; + unread = &unread[next..]; + if let Some(rest) = line.strip_prefix(b"data:") { + let payload = rest.strip_prefix(b" ").unwrap_or(rest); + if !multi.is_empty() { + multi.push(b'\n'); + multi.extend_from_slice(payload); + } else if let Some(first) = single { + multi.reserve(first.len() + 1 + payload.len()); + multi.extend_from_slice(first); + multi.push(b'\n'); + multi.extend_from_slice(payload); + } else if !payload.is_empty() { + single = Some(payload); + } + } + } + let payload = if multi.is_empty() { + single + } else { + Some(multi.as_slice()) + }; + let item = payload.map(|bytes| { + serde_json::from_slice(bytes).map_err(|source| GatewayError::Malformed { + message: "progress snapshot was not a valid {busy, text} JSON object".to_owned(), + source: Some(Box::new(source)), + }) + }); + buffer.drain(..end); + if let Some(item) = item { + return Some(item); + } + } +} + +/// The length of the first line in `bytes` and the offset just past its +/// CRLF, LF, or CR terminator, or `None` when no terminator is buffered. +fn first_line(bytes: &[u8]) -> Option<(usize, usize)> { + let length = bytes + .iter() + .position(|byte| matches!(byte, b'\r' | b'\n'))?; + let terminator = if bytes[length..].starts_with(b"\r\n") { + 2 + } else { + 1 + }; + Some((length, length + terminator)) +} + #[cfg(test)] mod tests; diff --git a/crates/workshop/gateway/src/client/events.rs b/crates/workshop/gateway/src/client/events.rs deleted file mode 100644 index 056cef5b..00000000 --- a/crates/workshop/gateway/src/client/events.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! The gateway client's wire types: the buffered relay response, the -//! forwarded config-panel response, and the profile-selection outcome. - -use serde::Deserialize; - -/// A gateway HTTP response captured for verbatim relay. -#[derive(Debug)] -pub struct GatewayResponse { - /// The gateway's status code, relayed unchanged. - pub status: reqwest::StatusCode, - /// The gateway's response body, relayed byte-for-byte. - pub body: Vec, -} - -/// A gateway response captured for the config-panel proxy: the relay -/// keeps the content type alongside the status and body, because the -/// config UI distinguishes a buffered JSON answer from an SSE stream by -/// it. -#[derive(Debug)] -pub struct ForwardedResponse { - /// The gateway's status code, relayed unchanged. - pub status: reqwest::StatusCode, - /// The gateway's `Content-Type`, when it sent one. - pub content_type: Option, - /// The gateway's response body, relayed byte-for-byte. - pub body: Vec, -} - -/// The gateway's answer to a profile selection, `POST /admin/switch-profile`. -/// -/// An accepted selection answers one JSON document decoding as -/// [`SwitchProfileBody`]: the gateway persisted the selection and reports -/// whether it must restart to load it. A refusal (bad auth, a malformed or -/// undefined name) is buffered rather than reported as an error, matching -/// the relay contract of the other client methods. -#[derive(Debug)] -#[non_exhaustive] -pub enum SwitchResponse { - /// The gateway accepted and persisted the selection. - Selected(SwitchProfileBody), - - /// A refusal, buffered: the gateway's error envelope. - Buffered(GatewayResponse), -} - -/// The body of an accepted profile selection. -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub struct SwitchProfileBody { - /// The selection now persisted: a profile name, or `None` for no - /// profile. - pub profile: Option, - /// Whether the gateway must restart before the selection is served; - /// `false` when the selection already matches the running profile. - pub restart_required: bool, -} diff --git a/crates/workshop/gateway/src/client/progress_stream.rs b/crates/workshop/gateway/src/client/progress_stream.rs deleted file mode 100644 index bf6f9cf6..00000000 --- a/crates/workshop/gateway/src/client/progress_stream.rs +++ /dev/null @@ -1,210 +0,0 @@ -//! The `GET /admin/progress` subscription: a long-lived SSE stream of -//! [`Progress`] snapshots, decoded block-by-block under a hard size -//! bound. -//! -//! Unlike a profile switch, which answers a single JSON document, a -//! progress subscription never terminates on its own and yields -//! snapshots the workshop renders verbatim, so the decode keeps the -//! stricter posture the subscriber always had: only -//! blank-line-terminated blocks dispatch (an incomplete trailing block -//! is discarded), and a block that grows past `MAX_EVENT_BLOCK` without -//! its terminator is refused rather than buffered unbounded. - -use std::pin::Pin; - -use super::super::progress::Progress; -use futures_util::Stream; - -use super::GatewayError; - -/// The largest single SSE event block buffered before the stream refuses -/// it, in bytes. A peer that never sends a blank-line terminator would -/// otherwise grow the reassembly buffer unbounded; sized well above any -/// realistic progress event. -pub(super) const MAX_EVENT_BLOCK: usize = 1024 * 1024; - -/// The largest error body kept for a subscription diagnostic, in bytes. -const MAX_ERROR_BODY: usize = 2000; - -/// A stream of decoded [`Progress`] snapshots from the gateway, in -/// arrival order. -/// -/// A `data:` block that does not decode is yielded as one error item -/// without ending the stream; a read failure or an event block oversized -/// beyond `MAX_EVENT_BLOCK` is yielded as one error item that ends the -/// stream. The stream ends when the gateway closes the body; whether to -/// resubscribe is the caller's decision. -pub(crate) type ProgressStream = Pin> + Send>>; - -/// Turns an answered `GET /admin/progress` request into the snapshot -/// stream. -/// -/// The endpoint answers only an event stream on success, so a -/// non-success status is [`GatewayError::Status`] with a bounded, -/// control-escaped body rather than a relayed response. -pub(super) async fn subscribe(response: reqwest::Response) -> Result { - let status = response.status(); - if !status.is_success() { - return Err(GatewayError::Status { - status, - body: error_body(response).await?, - }); - } - Ok(decode(response)) -} - -/// Reads at most [`MAX_ERROR_BODY`] bytes of a non-success response -/// body, escaping control characters so a hostile body cannot forge log -/// lines or smuggle terminal control sequences into a diagnostic. -async fn error_body(mut response: reqwest::Response) -> Result { - let mut buffer: Vec = Vec::new(); - while buffer.len() < MAX_ERROR_BODY { - match response.chunk().await { - Ok(Some(chunk)) => { - let take = (MAX_ERROR_BODY - buffer.len()).min(chunk.len()); - buffer.extend_from_slice(&chunk[..take]); - if take < chunk.len() { - break; - } - } - Ok(None) => break, - Err(source) => return Err(GatewayError::ReadBody(Box::new(source))), - } - } - if buffer.is_empty() { - return Ok("(empty body)".to_owned()); - } - let lossy = String::from_utf8_lossy(&buffer); - let mut escaped = String::with_capacity(lossy.len()); - for ch in lossy.chars() { - if ch.is_control() { - escaped.extend(ch.escape_default()); - } else { - escaped.push(ch); - } - } - Ok(escaped) -} - -/// Decodes an SSE body into a snapshot stream: chunks are buffered -/// until a blank line terminates an event block (CRLF, LF, or CR line -/// endings alike), comment-only blocks (heartbeats) are skipped, and an -/// undecodable block becomes one error item rather than killing the -/// stream. A mid-stream read failure likewise surfaces as one error -/// item, after which the stream ends. A block that grows past -/// [`MAX_EVENT_BLOCK`] without a terminator is refused as one error -/// item, after which the stream ends, so a peer cannot buffer the client -/// unbounded. -fn decode(response: reqwest::Response) -> ProgressStream { - let events = futures_util::stream::unfold( - (response, Vec::new(), false), - |(mut response, mut buffer, mut failed)| async move { - loop { - if let Some(item) = next_buffered_event(&mut buffer) { - return Some((item, (response, buffer, failed))); - } - if failed { - return None; - } - match response.chunk().await { - Ok(Some(chunk)) => { - if buffer.len() + chunk.len() > MAX_EVENT_BLOCK { - failed = true; - let item = Err(GatewayError::Malformed { - message: format!( - "progress event block exceeds the {MAX_EVENT_BLOCK}-byte limit" - ), - source: None, - }); - return Some((item, (response, buffer, failed))); - } - buffer.extend_from_slice(&chunk); - } - // An incomplete trailing block is discarded, matching - // the SSE rule that only blank-line-terminated blocks - // dispatch. - Ok(None) => return None, - Err(source) => { - failed = true; - let item = Err(GatewayError::ReadBody(Box::new(source))); - return Some((item, (response, buffer, failed))); - } - } - } - }, - ); - Box::pin(events) -} - -/// Pops the next decodable snapshot out of `buffer`, or `None` when no -/// complete block is buffered yet. Comment-only blocks (heartbeats) are -/// consumed and skipped. -fn next_buffered_event(buffer: &mut Vec) -> Option> { - loop { - let end = block_end(buffer)?; - let block: Vec = buffer.drain(..end).collect(); - if let Some(item) = parse_event_block(&block) { - return Some(item); - } - } -} - -/// The end (terminator included) of the first complete event block: a -/// blank line, whether the peer terminates its lines with CRLF, LF, CR, -/// or a mix. -/// -/// A CR that ends the buffer counts as a whole terminator, so a CR-only -/// peer dispatches without waiting for its next chunk. When that CR was -/// half of a split CRLF, the orphaned LF opens the next block as an empty -/// line, which carries no payload and is skipped. -fn block_end(buffer: &[u8]) -> Option { - let mut start = 0; - loop { - let (length, next) = first_line(buffer.get(start..)?)?; - if length == 0 { - return Some(start + next); - } - start += next; - } -} - -/// The length of the first line in `bytes` and the offset just past its -/// CRLF, LF, or CR terminator, or `None` when no terminator is buffered. -fn first_line(bytes: &[u8]) -> Option<(usize, usize)> { - let length = bytes - .iter() - .position(|byte| matches!(byte, b'\r' | b'\n'))?; - let terminator = if bytes[length..].starts_with(b"\r\n") { - 2 - } else { - 1 - }; - Some((length, length + terminator)) -} - -/// Decodes one SSE event block: `data:` lines join into the payload, -/// comment lines and unrecognized fields are ignored, and a block with -/// no payload (a heartbeat) yields `None`. -fn parse_event_block(block: &[u8]) -> Option> { - let mut data: Vec = Vec::new(); - let mut unread = block; - while let Some((length, next)) = first_line(unread) { - let line = &unread[..length]; - unread = &unread[next..]; - if let Some(rest) = line.strip_prefix(b"data:") { - if !data.is_empty() { - data.push(b'\n'); - } - data.extend_from_slice(rest.strip_prefix(b" ").unwrap_or(rest)); - } - } - if data.is_empty() { - return None; - } - Some( - serde_json::from_slice(&data).map_err(|source| GatewayError::Malformed { - message: "progress snapshot was not a valid {busy, text} JSON object".to_owned(), - source: Some(Box::new(source)), - }), - ) -} diff --git a/crates/workshop/gateway/src/client/socket.rs b/crates/workshop/gateway/src/client/socket.rs deleted file mode 100644 index f093e785..00000000 --- a/crates/workshop/gateway/src/client/socket.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Authenticated WebSocket connections from the workshop to the gateway. - -use tokio_tungstenite::tungstenite::client::IntoClientRequest as _; - -use super::{GatewayClient, GatewayError}; - -/// An authenticated WebSocket connection to the gateway's Realtime transcription. -pub type GatewayRealtimeSocket = - tokio_tungstenite::WebSocketStream>; - -impl GatewayClient { - /// Opens the gateway's authenticated Realtime transcription socket. - /// - /// The target is fixed to `/v1/realtime?intent=transcription`; browser - /// query parameters and handshake policy headers never cross the relay. - /// - /// # Errors - /// Returns [`GatewayError::Transport`] if the socket cannot be - /// connected (the header bound elapsing included). - pub async fn connect_realtime(&self) -> Result { - let mut request = realtime_url(&self.base_url)? - .as_str() - .into_client_request() - .map_err(|source| GatewayError::Transport(Box::new(source)))?; - if !self.api_key.is_empty() { - let value = format!("Bearer {}", self.api_key) - .parse() - .map_err(|source| GatewayError::Transport(Box::new(source)))?; - request.headers_mut().insert( - tokio_tungstenite::tungstenite::http::header::AUTHORIZATION, - value, - ); - } - match tokio::time::timeout( - self.request_timeout, - tokio_tungstenite::connect_async(request), - ) - .await - { - Ok(Ok((socket, _response))) => Ok(socket), - Ok(Err(source)) => Err(GatewayError::Transport(Box::new(source))), - Err(elapsed) => Err(GatewayError::Transport(Box::new(elapsed))), - } - } -} - -/// The Realtime transcription URL under `base_url`, upgraded to its -/// WebSocket scheme: http to ws and https to wss. -pub(super) fn realtime_url(base_url: &str) -> Result { - let mut url = - url::Url::parse(base_url).map_err(|source| GatewayError::Transport(Box::new(source)))?; - let scheme = match url.scheme() { - "http" => "ws", - "https" => "wss", - scheme => { - return Err(GatewayError::Transport(Box::new(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!("gateway URL scheme {scheme:?} cannot be upgraded to a WebSocket"), - )))); - } - }; - url.set_scheme(scheme).map_err(|()| { - GatewayError::Transport(Box::new(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "gateway URL scheme cannot be converted to WebSocket", - ))) - })?; - let path = format!("{}/v1/realtime", url.path().trim_end_matches('/')); - url.set_path(&path); - url.set_query(Some("intent=transcription")); - url.set_fragment(None); - Ok(url) -} diff --git a/crates/workshop/gateway/src/client/sse.rs b/crates/workshop/gateway/src/client/sse.rs deleted file mode 100644 index c09e2bf1..00000000 --- a/crates/workshop/gateway/src/client/sse.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! Response-body capture for the gateway client's buffered calls. - -use super::{GatewayError, GatewayResponse}; - -/// Captures the status and raw body of a gateway response. -pub(super) async fn read(response: reqwest::Response) -> Result { - let status = response.status(); - let body = response - .bytes() - .await - .map_err(|source| GatewayError::ReadBody(Box::new(source)))? - .to_vec(); - Ok(GatewayResponse { status, body }) -} diff --git a/crates/workshop/gateway/src/client/tests.rs b/crates/workshop/gateway/src/client/tests.rs index 527976c6..32f2d7a1 100644 --- a/crates/workshop/gateway/src/client/tests.rs +++ b/crates/workshop/gateway/src/client/tests.rs @@ -1,18 +1,23 @@ //! Tests for the gateway client: the client basics live here beside the -//! shared mock-server helper; the progress, socket, switch, and timeout +//! test-only timeout override; the progress, socket, switch, and timeout //! areas each have their own submodule. use super::*; +use crate::test_support::serve; mod progress; mod socket; mod switch; mod timeouts; -/// Binds `app` on a free loopback port and returns its base URL. -async fn serve(app: axum::Router) -> String { - let (addr, _handle) = workshop_support::fixtures::serve(app).await; - format!("http://{addr}") +impl GatewayClient { + /// Overrides the request and probe bounds, so tests can trip them + /// without waiting out the production values. + pub(crate) fn with_timeouts_for_test(mut self, request: Duration, health: Duration) -> Self { + self.request_timeout = request; + self.health_timeout = health; + self + } } #[test] diff --git a/crates/workshop/gateway/src/client/tests/progress.rs b/crates/workshop/gateway/src/client/tests/progress.rs index a325cfba..d8a8d5da 100644 --- a/crates/workshop/gateway/src/client/tests/progress.rs +++ b/crates/workshop/gateway/src/client/tests/progress.rs @@ -1,40 +1,29 @@ -//! Progress-subscription tests: the `GET /admin/progress` event stream -//! decodes block-by-block, heartbeat comments are skipped, a malformed -//! block degrades to one error item without ending the stream, a read -//! failure or an oversized block ends it, and a non-success status is an -//! error rather than a stream. - -use super::*; +//! Progress-subscription tests: SSE framing, chunk boundaries, malformed +//! events, mid-stream read failures, oversized blocks, and non-success status. +use axum::Router; +use axum::response::IntoResponse; +use axum::routing::get; use futures_util::StreamExt as _; -use crate::client::progress_stream::MAX_EVENT_BLOCK; +use super::*; use crate::progress::Progress; -/// Serializes a wire-format progress snapshot by hand, so the tests pin -/// the JSON shape the gateway emits rather than the types crate's -/// serializer. fn snapshot_json(busy: bool, text: &str) -> String { serde_json::json!({"busy": busy, "text": text}).to_string() } -/// The decoded snapshot as a `(busy, text)` pair. fn decoded(item: &Result) -> (bool, String) { let snapshot = item.as_ref().expect("every item decodes"); (snapshot.busy, snapshot.text.clone()) } -/// A mock `GET /admin/progress` that requires the bearer token and -/// answers with `body` as the verbatim SSE payload. -fn mock_progress(body: String) -> axum::Router { - use axum::Router; - use axum::response::IntoResponse; - use axum::routing::get; - +fn mock_progress_chunks(chunks: Vec) -> Router { Router::new().route( "/admin/progress", get(move |headers: axum::http::HeaderMap| { - let body = body.clone(); + let chunks: Vec> = + chunks.iter().cloned().map(Ok).collect(); async move { let auth = headers .get(axum::http::header::AUTHORIZATION) @@ -42,78 +31,144 @@ fn mock_progress(body: String) -> axum::Router { if auth != Some("Bearer tok") { return (axum::http::StatusCode::UNAUTHORIZED, "bad token").into_response(); } - ( - [(axum::http::header::CONTENT_TYPE, "text/event-stream")], - body, - ) - .into_response() - } - }), - ) -} - -/// A mock `GET /admin/progress` that answers with each of `chunks` as its -/// own body chunk, so a test controls where the SSE payload splits. -fn mock_progress_chunks(chunks: Vec) -> axum::Router { - axum::Router::new().route( - "/admin/progress", - axum::routing::get(move || { - let chunks: Vec> = - chunks.iter().cloned().map(Ok).collect(); - async move { ( [(axum::http::header::CONTENT_TYPE, "text/event-stream")], axum::body::Body::from_stream(futures_util::stream::iter(chunks)), ) + .into_response() } }), ) } -/// Subscribes against `app` and collects the whole event stream. -async fn collect_events(app: axum::Router) -> Vec> { +async fn collect_events(app: Router) -> Vec> { let base_url = serve(app).await; - let client = GatewayClient::new(&base_url, "tok").expect("client builds in tests"); - let events = client + GatewayClient::new(&base_url, "tok") + .expect("client builds") .subscribe_progress() .await - .expect("a well-formed stream subscribes"); - events.collect().await + .expect("stream subscribes") + .collect() + .await } #[tokio::test] -async fn subscribe_progress_decodes_snapshots_and_skips_heartbeat_comments() { - let begun = snapshot_json(true, "Downloading qwen3-8b.gguf"); - let updated = snapshot_json(true, "Downloading qwen3-8b.gguf 45%"); - let idle = snapshot_json(false, ""); - let body = format!( - ": heartbeat\n\ndata: {begun}\n\ndata: {updated}\n\n: heartbeat\n\ndata: {idle}\n\n" - ); +async fn subscribe_progress_decodes_sse_framing_and_chunk_boundaries() { + type Case = (&'static str, Vec, &'static [(bool, &'static str)]); - let events = collect_events(mock_progress(body)).await; - - let snapshots: Vec<(bool, String)> = events.iter().map(decoded).collect(); - assert_eq!( - snapshots, - vec![ - (true, "Downloading qwen3-8b.gguf".to_owned()), - (true, "Downloading qwen3-8b.gguf 45%".to_owned()), - (false, String::new()), - ], - "each data block decodes to one busy/text snapshot in arrival order" - ); + let begun = snapshot_json(true, "Loading profile"); + let finished = snapshot_json(false, ""); + let split_wire = format!("data: {begun}\n\n"); + let (split_head, split_tail) = split_wire.split_at(split_wire.len() / 2); + let byte_wire = format!("data: {begun}\r\n\r\n"); + + let cases: [Case; 13] = [ + ( + "lf blocks with heartbeat comments", + vec![format!( + ": heartbeat\n\ndata: {}\n\ndata: {}\n\n: heartbeat\n\ndata: {finished}\n\n", + snapshot_json(true, "Downloading qwen3-8b.gguf"), + snapshot_json(true, "Downloading qwen3-8b.gguf 45%"), + )], + &[ + (true, "Downloading qwen3-8b.gguf"), + (true, "Downloading qwen3-8b.gguf 45%"), + (false, ""), + ], + ), + ( + "crlf blocks", + vec![format!("data: {begun}\r\n\r\ndata: {finished}\r\n\r\n")], + &[(true, "Loading profile"), (false, "")], + ), + ( + "bare cr blocks with comment", + vec![format!( + "data: {begun}\r\r: heartbeat\rdata: {finished}\r\r" + )], + &[(true, "Loading profile"), (false, "")], + ), + ( + "mixed terminators", + vec![format!( + "data: {}\n\r\ndata: {}\r\n\n: heartbeat\rdata: {}\r\n\rdata: {finished}\n\r", + snapshot_json(true, "Downloading"), + snapshot_json(true, "Loading"), + snapshot_json(true, "Warming"), + )], + &[ + (true, "Downloading"), + (true, "Loading"), + (true, "Warming"), + (false, ""), + ], + ), + ( + "split across two chunks", + vec![split_head.to_owned(), split_tail.to_owned()], + &[(true, "Loading profile")], + ), + ( + "orphaned lf of split crlf", + vec![ + format!("data: {begun}\r\n\r"), + format!("\ndata: {finished}\r\n\r\n"), + ], + &[(true, "Loading profile"), (false, "")], + ), + ( + "single-byte chunks", + byte_wire.bytes().map(|b| (b as char).to_string()).collect(), + &[(true, "Loading profile")], + ), + ( + "incomplete trailing block discarded", + vec![format!("data: {begun}\n\ndata: {finished}")], + &[(true, "Loading profile")], + ), + ( + "data without leading space", + vec![format!("data:{begun}\n\n")], + &[(true, "Loading profile")], + ), + ( + "multiline data joined with newline", + vec!["data: {\"busy\":true,\ndata: \"text\":\"Split\"}\n\n".to_owned()], + &[(true, "Split")], + ), + ( + "non-data fields ignored", + vec![format!( + "event: progress\nid: 7\nretry: 1000\ndata: {begun}\n\n" + )], + &[(true, "Loading profile")], + ), + ("empty stream", vec![String::new()], &[]), + ( + "comments and blanks only", + vec![": ping\n\n\n: pong\r\n\r\n".to_owned()], + &[], + ), + ]; + + for (label, chunks, expected) in cases { + let events = collect_events(mock_progress_chunks(chunks)).await; + let actual: Vec<(bool, String)> = events.iter().map(decoded).collect(); + let expected: Vec<(bool, String)> = expected + .iter() + .map(|&(busy, text)| (busy, text.to_owned())) + .collect(); + assert_eq!(actual, expected, "{label}"); + } } #[tokio::test] async fn subscribe_progress_classifies_a_non_success_status() { - let base_url = serve(mock_progress(String::new())).await; - let client = GatewayClient::new(&base_url, "wrong-token").expect("client builds in tests"); + let base_url = serve(mock_progress_chunks(vec![String::new()])).await; + let client = GatewayClient::new(&base_url, "wrong-token").expect("client builds"); - let Err(error) = client.subscribe_progress().await else { - panic!("a 401 response must surface as an error"); - }; - let GatewayError::Status { status, body } = &error else { - panic!("a 401 response is a status error, got {error}"); + let Err(GatewayError::Status { status, body }) = client.subscribe_progress().await else { + panic!("expected 401 Status error"); }; assert_eq!(status.as_u16(), 401); assert_eq!(body, "bad token"); @@ -125,195 +180,50 @@ async fn subscribe_progress_yields_one_error_per_bad_event_and_continues() { let finished = snapshot_json(false, ""); let body = format!("data: {begun}\n\ndata: {{not json\n\ndata: {finished}\n\n"); - let events = collect_events(mock_progress(body)).await; - - assert_eq!(events.len(), 3, "one item per data block"); - assert!(events[0].is_ok(), "the leading event decodes"); - let error = events[1] - .as_ref() - .expect_err("the undecodable line is one error item"); - assert!( - matches!(error, GatewayError::Malformed { .. }), - "an undecodable block is a malformed error, got {error}" - ); - assert!( - events[2].is_ok(), - "a bad line must not end the stream: the trailing event still arrives" - ); -} - -#[tokio::test] -async fn subscribe_progress_reassembles_an_event_split_across_chunks() { - let begun = snapshot_json(true, "Loading profile"); - let wire = format!("data: {begun}\n\n"); - let (head, tail) = wire.split_at(wire.len() / 2); - let app = mock_progress_chunks(vec![head.to_owned(), tail.to_owned()]); - - let events = collect_events(app).await; - - assert_eq!(events.len(), 1, "the split block decodes as one event"); - assert!(events[0].is_ok(), "the reassembled event decodes"); -} - -#[tokio::test] -async fn subscribe_progress_skips_the_orphaned_lf_of_a_crlf_split_across_chunks() { - // The first chunk ends on the blank line's CR, so its block dispatches - // at once, and the LF that opens the next chunk is an empty line. - let begun = snapshot_json(true, "Loading profile"); - let finished = snapshot_json(false, ""); - let head = format!("data: {begun}\r\n\r"); - let tail = format!("\ndata: {finished}\r\n\r\n"); - - let events = collect_events(mock_progress_chunks(vec![head, tail])).await; - - let snapshots: Vec<(bool, String)> = events.iter().map(decoded).collect(); - assert_eq!( - snapshots, - vec![(true, "Loading profile".to_owned()), (false, String::new())], - "both events decode and the orphaned LF yields nothing" - ); + let events = collect_events(mock_progress_chunks(vec![body])).await; + assert_eq!(events.len(), 3); + assert!(events[0].is_ok()); + assert!(matches!(events[1], Err(GatewayError::Malformed { .. }))); + assert!(events[2].is_ok()); } #[tokio::test] async fn subscribe_progress_yields_one_error_on_a_mid_stream_read_failure_then_ends() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - // The server promises a large body, delivers one complete event, then - // drops the connection: the read failure must surface as one error - // item that ends the stream, not as a hang or a silent close. let begun = snapshot_json(true, "Loading profile"); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { if let Ok((mut sock, _)) = listener.accept().await { - let mut buf = [0u8; 1024]; + let mut buf = [0_u8; 1024]; let _ = sock.read(&mut buf).await; - let header = "HTTP/1.1 200 OK\r\n\ - Content-Type: text/event-stream\r\n\ - Content-Length: 1000000\r\n\r\n"; + let header = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: 1000000\r\n\r\n"; let _ = sock.write_all(header.as_bytes()).await; let _ = sock .write_all(format!("data: {begun}\n\n").as_bytes()) .await; - // Socket drops here: the promised body never completes. } }); - let client = GatewayClient::new(&format!("http://{addr}"), "tok").expect("client builds"); - let events = client + let events: Vec<_> = GatewayClient::new(&format!("http://{addr}"), "tok") + .expect("client builds") .subscribe_progress() .await - .expect("a well-formed stream subscribes") - .collect::>() + .expect("stream subscribes") + .collect() .await; - assert_eq!(events.len(), 2, "the decoded event, then one error item"); - assert!(events[0].is_ok(), "the leading event decodes"); - let error = events[1] - .as_ref() - .expect_err("the truncated body is one error item"); - assert!( - matches!(error, GatewayError::ReadBody(_)), - "a mid-stream read failure is a body-read error, got {error}" - ); + assert_eq!(events.len(), 2); + assert!(events[0].is_ok()); + assert!(matches!(events[1], Err(GatewayError::ReadBody(_)))); } #[tokio::test] async fn subscribe_progress_bounds_an_event_block_that_never_terminates() { - let body = "x".repeat(MAX_EVENT_BLOCK + 1); - - let events = collect_events(mock_progress(body)).await; - - assert_eq!(events.len(), 1, "the oversized block is one error item"); - let error = events[0] - .as_ref() - .expect_err("an unterminated oversized block must be refused"); - assert!( - matches!(error, GatewayError::Malformed { .. }), - "an oversized block is a malformed error, got {error}" - ); - assert!( - error.to_string().contains("exceeds"), - "the bound must report the size limit, got {error}" - ); -} - -#[tokio::test] -async fn subscribe_progress_decodes_crlf_terminated_blocks() { - // A peer that terminates its lines with CRLF still dispatches: the - // blank-line terminator is `\r\n\r\n`, which contains no `\n\n`. - let begun = snapshot_json(true, "Loading profile"); - let finished = snapshot_json(false, ""); - let body = format!("data: {begun}\r\n\r\ndata: {finished}\r\n\r\n"); - - let events = collect_events(mock_progress(body)).await; - - let snapshots: Vec<(bool, String)> = events.iter().map(decoded).collect(); - assert_eq!( - snapshots, - vec![(true, "Loading profile".to_owned()), (false, String::new())] - ); -} - -#[tokio::test] -async fn subscribe_progress_decodes_cr_terminated_blocks() { - // A peer that terminates its lines with a bare CR still dispatches, - // and a comment line ended by CR alone stays apart from its data line. - let begun = snapshot_json(true, "Loading profile"); - let finished = snapshot_json(false, ""); - let body = format!("data: {begun}\r\r: heartbeat\rdata: {finished}\r\r"); - - let events = collect_events(mock_progress(body)).await; - - let snapshots: Vec<(bool, String)> = events.iter().map(decoded).collect(); - assert_eq!( - snapshots, - vec![(true, "Loading profile".to_owned()), (false, String::new())] - ); -} - -#[tokio::test] -async fn subscribe_progress_decodes_blocks_with_mixed_line_terminators() { - // Each blank line pairs two different terminators, and one block - // ends its comment line with CR and its data line with CRLF. - let downloading = snapshot_json(true, "Downloading"); - let loading = snapshot_json(true, "Loading"); - let warming = snapshot_json(true, "Warming"); - let idle = snapshot_json(false, ""); - let body = format!( - "data: {downloading}\n\r\n\ - data: {loading}\r\n\n\ - : heartbeat\rdata: {warming}\r\n\r\ - data: {idle}\n\r" - ); - - let events = collect_events(mock_progress(body)).await; - - let snapshots: Vec<(bool, String)> = events.iter().map(decoded).collect(); - assert_eq!( - snapshots, - vec![ - (true, "Downloading".to_owned()), - (true, "Loading".to_owned()), - (true, "Warming".to_owned()), - (false, String::new()), - ] - ); -} - -#[tokio::test] -async fn subscribe_progress_discards_an_incomplete_trailing_block() { - // The body ends mid-block: only blank-line-terminated blocks - // dispatch, so the partial event is dropped and the stream ends. - let begun = snapshot_json(true, "Loading profile"); - let finished = snapshot_json(false, ""); - let body = format!("data: {begun}\n\ndata: {finished}"); - - let events = collect_events(mock_progress(body)).await; + let events = collect_events(mock_progress_chunks(vec!["x".repeat(MAX_EVENT_BLOCK + 1)])).await; - assert_eq!( - events.len(), - 1, - "the unterminated trailing block is discarded" - ); - assert!(events[0].is_ok(), "the complete event decodes"); + assert_eq!(events.len(), 1); + let error = events[0].as_ref().expect_err("oversized block refused"); + assert!(matches!(error, GatewayError::Malformed { .. })); + assert!(error.to_string().contains("exceeds")); } diff --git a/crates/workshop/gateway/src/client/tests/socket.rs b/crates/workshop/gateway/src/client/tests/socket.rs index fabc3331..0ef29dae 100644 --- a/crates/workshop/gateway/src/client/tests/socket.rs +++ b/crates/workshop/gateway/src/client/tests/socket.rs @@ -3,8 +3,6 @@ use super::*; -use crate::client::socket::realtime_url; - #[test] fn an_http_gateway_upgrades_to_ws() { let url = realtime_url("http://127.0.0.1:8081").expect("http upgrades"); diff --git a/crates/workshop/gateway/src/client/tests/timeouts.rs b/crates/workshop/gateway/src/client/tests/timeouts.rs index 148326ff..a336e720 100644 --- a/crates/workshop/gateway/src/client/tests/timeouts.rs +++ b/crates/workshop/gateway/src/client/tests/timeouts.rs @@ -2,8 +2,7 @@ //! client's bounds rather than hang its caller. use super::*; - -use crate::test_gateway::stalled_gateway; +use crate::test_support::stalled_gateway; /// A client against `base_url` whose bounds are tight enough to trip /// inside a test. diff --git a/crates/workshop/gateway/src/heartbeat-tests.rs b/crates/workshop/gateway/src/heartbeat-tests.rs index 067c9155..ed1b88ff 100644 --- a/crates/workshop/gateway/src/heartbeat-tests.rs +++ b/crates/workshop/gateway/src/heartbeat-tests.rs @@ -1,63 +1,17 @@ //! Heartbeat unit tests: the join-line recompute, the probe bound, and //! the stop signal and binding replacement ending an in-flight probe or -//! refresh. The bus-coupled loop behavior (transitions, refreshes, -//! convergence) is pinned by the workshop-server integration tests, which -//! compose the heartbeat with the real status, catalog, and menu buses. - -use super::*; -use crate::client::GatewayClient; -use crate::test_gateway::stalled_gateway; +//! refresh. use std::sync::Arc; use axum::http::StatusCode; use axum::routing::get; -use tokio::sync::{Notify, broadcast}; - -fn retained(label: &str) -> StatusBarUpdate { - StatusBarUpdate { - label: label.to_owned(), - description: String::new(), - busy: false, - severity: Severity::Info, - activity: Activity::General, - } -} +use tokio::sync::Notify; -/// Binds `app` on a free loopback port and returns its base URL. -async fn serve(app: axum::Router) -> String { - let (addr, _handle) = workshop_support::fixtures::serve(app).await; - format!("http://{addr}") -} - -/// A recording status sink standing in for the status bus: the push the -/// heartbeat reports through, the registration keeping the sink alive, -/// and the receiver the test reads. -fn status_recorder() -> ( - Push, - workshop_registry::Registration, - broadcast::Receiver, -) { - let registry = workshop_registry::Registry::new(); - let (status_tx, rx) = broadcast::channel(16); - let sink = registry.register_sink::(Arc::new( - workshop_registry::StatusSinkAdapter::new(move |update| { - let _ = status_tx.send(update); - }), - )); - (registry.push(), sink, rx) -} - -/// The next status line within a generous deadline. -async fn next_label(rx: &mut broadcast::Receiver) -> String { - tokio::time::timeout(Duration::from_secs(5), rx.recv()) - .await - .expect("a status update arrives within the deadline") - .expect("the recording sink is open") - .label -} +use super::*; +use crate::client::GatewayClient; +use crate::test_support::{StatusRecorder, serve, stalled_gateway}; -/// Waits for `notify` within a generous deadline. async fn notified(notify: &Notify, what: &str) { tokio::time::timeout(Duration::from_secs(5), notify.notified()) .await @@ -65,61 +19,59 @@ async fn notified(notify: &Notify, what: &str) { } #[test] -fn a_join_recomputes_a_stale_connect_announcement_to_the_resting_line() { - let health = GatewayHealth::new(); - let update = join_status(Some(retained(CONNECTED_LABEL)), &health) - .expect("a retained transition still yields a join line"); - assert_eq!(update.label, "Ready"); - assert_eq!(update.severity, Severity::Info); -} - -#[test] -fn a_join_recomputes_a_stale_connect_announcement_during_an_outage() { - let health = GatewayHealth::new(); - health.publish(false); - let update = join_status(Some(retained(CONNECTED_LABEL)), &health) - .expect("a retained transition still yields a join line"); - assert_eq!(update.label, UNREACHABLE_LABEL); - assert_eq!(update.description, UNREACHABLE_DESCRIPTION); -} - -#[test] -fn a_join_keeps_a_retained_outage_while_the_gateway_is_down() { - let health = GatewayHealth::new(); - health.publish(false); - let update = join_status(Some(retained(UNREACHABLE_LABEL)), &health) - .expect("the outage line survives the recompute"); - assert_eq!(update.label, UNREACHABLE_LABEL); -} - -#[test] -fn a_join_replays_a_retained_frame_describing_real_work() { - let health = GatewayHealth::new(); - let working = Some(StatusBarUpdate { - label: "Downloading model".to_owned(), - description: "ggml-large-v3.bin".to_owned(), - busy: true, +fn join_status_recomputes_retained_frames() { + type Frame = (&'static str, &'static str, bool); + type Case = (&'static str, Option, bool, Option); + const READY: Frame = ("Ready", "idle", false); + const DOWN: Frame = (UNREACHABLE_LABEL, UNREACHABLE_DESCRIPTION, false); + const WORK: Frame = ("Downloading model", "ggml-large-v3.bin", true); + const CASES: &[Case] = &[ + ("none when reachable", None, true, None), + ("none when unreachable", None, false, None), + ( + "connect when reachable", + Some((CONNECTED_LABEL, "", false)), + true, + Some(READY), + ), + ( + "connect when unreachable", + Some((CONNECTED_LABEL, "", false)), + false, + Some(DOWN), + ), + ("outage when reachable", Some(DOWN), true, Some(READY)), + ( + "outage when unreachable", + Some((UNREACHABLE_LABEL, "", false)), + false, + Some(DOWN), + ), + ("work when reachable", Some(WORK), true, Some(WORK)), + ("work when unreachable", Some(WORK), false, Some(WORK)), + ]; + let frame = |(label, desc, busy): Frame| StatusBarUpdate { + label: label.to_owned(), + description: desc.to_owned(), + busy, severity: Severity::Info, activity: Activity::General, - }); - let update = join_status(working, &health).expect("the work frame replays as-is"); - assert_eq!(update.label, "Downloading model"); - assert!(update.busy, "the busy flag survives the join recompute"); -} + }; -#[test] -fn a_join_with_no_retained_frame_sends_nothing() { - let health = GatewayHealth::new(); - assert!(join_status(None, &health).is_none()); + for &(label, retained, reachable, expected) in CASES { + let health = GatewayHealth::new(); + health.publish(reachable); + assert_eq!( + join_status(retained.map(frame), &health), + expected.map(frame), + "{label}" + ); + } } #[test] fn the_probe_bound_is_shorter_than_the_heartbeat_interval() { - assert!( - crate::client::HEALTH_PROBE_TIMEOUT < HEARTBEAT_INTERVAL, - "a probe outlasting the interval would back the heartbeat up \ - behind a stalled gateway" - ); + assert!(crate::client::HEALTH_PROBE_TIMEOUT < HEARTBEAT_INTERVAL); } #[tokio::test] @@ -139,24 +91,19 @@ async fn a_wait_with_no_reachability_watch_runs_its_future_to_completion() { &mut signals, ) .await; - assert!( - matches!(output, Ok(7)), - "an absent reachability watch never ends the wait" - ); + assert!(matches!(output, Ok(7))); } #[tokio::test] async fn a_stalled_gateway_reads_unreachable_within_the_probe_bound() { - // Without a bounded probe, the first probe would hang forever and the - // heartbeat would never report at all. let (stalled, _accepted) = stalled_gateway().await; let client = GatewayClient::new(&stalled, "") - .expect("client builds in tests") + .expect("client builds") .with_timeouts_for_test(Duration::from_millis(100), Duration::from_millis(100)); - let (push, _sink, mut rx) = status_recorder(); + let mut recorder = StatusRecorder::new(); let heartbeat = spawn( GatewayBinding::from_client(client), - push, + recorder.push.clone(), GatewayHealth::new(), Duration::from_millis(25), ReconnectBackoff::with_schedule( @@ -165,7 +112,7 @@ async fn a_stalled_gateway_reads_unreachable_within_the_probe_bound() { Duration::from_secs(60), ), ); - assert_eq!(next_label(&mut rx).await, "Gateway unreachable"); + assert_eq!(recorder.next_label().await, UNREACHABLE_LABEL); heartbeat.shutdown().await; } @@ -174,30 +121,24 @@ async fn a_binding_replacement_cancels_a_stalled_probe() { let (stalled, accepted) = stalled_gateway().await; let healthy = serve(axum::Router::new().route("/health", get(|| async { StatusCode::OK }))).await; - // A probe bound far past the test deadline: only the rebind can end - // the stalled probe in time. let client = GatewayClient::new(&stalled, "") - .expect("client builds in tests") + .expect("client builds") .with_timeouts_for_test(Duration::from_secs(60), Duration::from_secs(60)); let gateway = GatewayBinding::from_client(client); - let (push, _sink, mut rx) = status_recorder(); + let mut recorder = StatusRecorder::new(); let heartbeat = spawn( gateway.clone(), - push, + recorder.push.clone(), GatewayHealth::new(), Duration::from_secs(60), ReconnectBackoff::new(), ); - notified(&accepted, "the first probe reaches the stalled stub").await; + notified(&accepted, "first probe reaches stalled stub").await; gateway .replace(&healthy, "") - .expect("the replacement publishes"); - assert_eq!( - next_label(&mut rx).await, - CONNECTED_LABEL, - "the replacement's probe reports without waiting out the stalled one" - ); + .expect("replacement publishes"); + assert_eq!(recorder.next_label().await, CONNECTED_LABEL); heartbeat.shutdown().await; } @@ -219,20 +160,18 @@ async fn shutdown_cancels_a_stalled_refresh() { .route("/admin/profiles", get(std::future::pending::)) .route("/admin/status", get(std::future::pending::)); let base_url = serve(app).await; - let (push, _sink, mut rx) = status_recorder(); + let mut recorder = StatusRecorder::new(); let heartbeat = spawn( - GatewayBinding::new(&base_url, "").expect("the test binding builds"), - push, + GatewayBinding::new(&base_url, "").expect("binding builds"), + recorder.push.clone(), GatewayHealth::new(), Duration::from_secs(60), ReconnectBackoff::new(), ); - assert_eq!(next_label(&mut rx).await, CONNECTED_LABEL); - notified(&refreshing, "the catalog refresh reaches the gateway").await; - // The stalled refresh holds for the client's request timeout, far - // past this deadline, unless the stop signal wins the wait. + assert_eq!(recorder.next_label().await, CONNECTED_LABEL); + notified(&refreshing, "catalog refresh reaches gateway").await; tokio::time::timeout(Duration::from_secs(5), heartbeat.shutdown()) .await - .expect("shutdown does not wait out the stalled refresh"); + .expect("shutdown cancels stalled refresh"); } diff --git a/crates/workshop/gateway/src/heartbeat.rs b/crates/workshop/gateway/src/heartbeat.rs index 24d5a493..2c3c8f33 100644 --- a/crates/workshop/gateway/src/heartbeat.rs +++ b/crates/workshop/gateway/src/heartbeat.rs @@ -31,12 +31,13 @@ use std::time::Duration; use tokio::sync::{oneshot, watch}; - +use tokio::task::JoinHandle; +use tokio::time; use workshop_protocol::{Activity, Severity, StatusBarUpdate}; use workshop_registry::Push; use workshop_support::ReconnectBackoff; -use crate::binding::{GatewayBinding, GatewaySnapshot}; +use crate::binding::GatewayBinding; use crate::progress::{Ended, Signals, until}; use crate::refresh::{refresh_catalog, refresh_profiles}; @@ -63,19 +64,14 @@ pub fn join_status( if update.label != CONNECTED_LABEL && update.label != UNREACHABLE_LABEL { return Some(update); } - let reachable = health.is_reachable(); + let (label, description) = if health.is_reachable() { + ("Ready", "idle") + } else { + (UNREACHABLE_LABEL, UNREACHABLE_DESCRIPTION) + }; Some(StatusBarUpdate { - label: if reachable { - "Ready" - } else { - UNREACHABLE_LABEL - } - .to_owned(), - description: if reachable { - "idle".to_owned() - } else { - UNREACHABLE_DESCRIPTION.to_owned() - }, + label: label.to_owned(), + description: description.to_owned(), busy: false, severity: Severity::Info, activity: Activity::General, @@ -139,15 +135,15 @@ impl Default for GatewayHealth { } } -/// A running heartbeat task. +/// A running background gateway task handle (heartbeat or progress subscriber). /// /// [`Heartbeat::shutdown`] signals the loop to stop and awaits the task. /// Dropping the handle without shutting down still stops the task at its /// next select point, because the closed channel resolves the stop branch. #[derive(Debug)] pub struct Heartbeat { - stop: Option>, - task: Option>, + pub(crate) stop: Option>, + pub(crate) task: Option>, } impl Heartbeat { @@ -162,7 +158,7 @@ impl Heartbeat { } } -/// Spawns the heartbeat loop against `client`, reporting transitions +/// Spawns the heartbeat loop against `gateway`, reporting transitions /// through `push` and publishing reachability to `health` and to the /// menu behind `push`, which recomputes `chat_ready` from it. A /// transition to reachable - boot's first probe included - refreshes the @@ -191,27 +187,11 @@ pub fn spawn( } } -/// Which menu sources have converged since the gateway last became -/// reachable, and whether the selection restore has run. -#[derive(Default)] -struct RefreshState { - profiles_ready: bool, - catalog_ready: bool, - selection_restored: bool, -} - -/// What the probe loop has learned about the current binding: the last -/// probe verdict and which menu sources have converged. A replaced -/// binding starts it over. -#[derive(Default)] -struct BindingState { - last: Option, - refresh: RefreshState, -} - -/// The probe loop: repeats [`cycle`] until the stop signal or an -/// exhausted backoff budget ends it. A replaced binding restarts the -/// cycle from the top with fresh state. +/// The probe loop: waits out the probe interval, probes health, announces +/// transitions, refreshes incomplete menu sources, and restores selection +/// until the stop signal or an exhausted backoff budget ends it. Every wait +/// goes through [`until`], so the stop signal and a replaced binding end +/// the pass early; a replaced binding restarts with fresh state. async fn run( gateway: &GatewayBinding, push: &Push, @@ -226,159 +206,108 @@ async fn run( reachable: None, gateway_changed: &mut gateway_changed, }; - let mut state = BindingState::default(); - loop { - match cycle( - gateway, - push, - health, - interval, - backoff, - &mut signals, - &mut state, - ) - .await - { - Ok(()) => {} - Err(Ended::Stop) => break, - // With no reachability watch armed, `Lost` never arrives. - Err(Ended::Rebind | Ended::Lost) => state = BindingState::default(), + 'rebind: loop { + let mut last: Option = None; + let mut profiles_ready = false; + let mut catalog_ready = false; + let mut selection_restored = false; + loop { + if let Some(was_reachable) = last { + let wait = if was_reachable { + interval + } else if let Some(delay) = backoff.next_delay() { + delay + } else { + push.push_failure( + "Gateway reconnect stopped", + "the reconnect budget is exhausted; restart the workshop to retry", + Activity::General, + ); + return; + }; + match until(time::sleep(wait), &mut signals).await { + Ok(()) => {} + Err(Ended::Stop) => return, + Err(Ended::Rebind | Ended::Lost) => continue 'rebind, + } + } + let snapshot = gateway.snapshot(); + let generation = snapshot.generation(); + let reachable = match until(snapshot.client().health(), &mut signals).await { + Ok(reachable) => reachable, + Err(Ended::Stop) => return, + Err(Ended::Rebind | Ended::Lost) => continue 'rebind, + }; + if gateway.generation() != generation { + continue 'rebind; + } + health.publish(reachable); + if last.replace(reachable) != Some(reachable) { + // The menu recomputes chat_ready from reachability, so the + // verdict feeds it before any slower refresh work below. + push.menu().set_gateway_reachable(reachable); + if reachable { + push.push_status_update( + CONNECTED_LABEL, + "the gateway answers its health probe", + Activity::General, + ); + } else { + push.push_status_update( + UNREACHABLE_LABEL, + UNREACHABLE_DESCRIPTION, + Activity::General, + ); + } + } + if !reachable { + profiles_ready = false; + catalog_ready = false; + selection_restored = false; + continue; + } + if !profiles_ready || !catalog_ready { + // All menu state is server-owned and reaches the UI via socket + // pushes - the UI fetches nothing on boot - so every transition + // into reachable (re)populates the profile state and the model + // catalog, retrying either incomplete source on healthy ticks. + let refresh = async { + match (profiles_ready, catalog_ready) { + (false, false) => { + (profiles_ready, catalog_ready) = tokio::join!( + refresh_profiles(snapshot.client(), push), + refresh_catalog(snapshot.client(), push) + ); + } + (false, true) => { + profiles_ready = refresh_profiles(snapshot.client(), push).await; + } + (true, false) => { + catalog_ready = refresh_catalog(snapshot.client(), push).await; + } + (true, true) => {} + } + }; + match until(refresh, &mut signals).await { + Ok(()) => {} + Err(Ended::Stop) => return, + Err(Ended::Rebind | Ended::Lost) => continue 'rebind, + } + } + if profiles_ready && catalog_ready && !selection_restored { + // A fresh boot has no selection, so restore the remembered + // model for the now-known active profile (else the first + // catalog model); a reconnect whose selection survived the + // outage is a no-op. This branch runs exactly once per + // reachable convergence because both readiness facts remain + // true. + push.menu().restore_selection(); + selection_restored = true; + } } } } -/// One pass of the probe loop, in named phases: wait out the probe -/// interval, probe the health endpoint, announce a transition, refresh -/// stale menu sources, and restore the selection. Every wait goes through -/// [`until`], so the stop signal and a replaced binding end the pass -/// early. -async fn cycle( - gateway: &GatewayBinding, - push: &Push, - health: &GatewayHealth, - interval: Duration, - backoff: &ReconnectBackoff, - signals: &mut Signals<'_>, - state: &mut BindingState, -) -> Result<(), Ended> { - await_probe_interval(state.last, interval, backoff, push, signals).await?; - let snapshot = gateway.snapshot(); - let generation = snapshot.generation(); - let reachable = until(snapshot.client().health(), signals).await?; - if gateway.generation() != generation { - return Err(Ended::Rebind); - } - announce_transition(push, health, reachable, &mut state.last); - let refresh = &mut state.refresh; - if !reachable { - *refresh = RefreshState::default(); - return Ok(()); - } - if !refresh.profiles_ready || !refresh.catalog_ready { - until( - refresh_incomplete_sources(&snapshot, push, refresh), - signals, - ) - .await?; - } - if refresh.profiles_ready && refresh.catalog_ready && !refresh.selection_restored { - // A fresh boot has no selection, so restore the remembered - // model for the now-known active profile (else the first - // catalog model); a reconnect whose selection survived the - // outage is a no-op. This branch runs exactly once per reachable - // convergence because both readiness facts remain true. - push.menu().restore_selection(); - refresh.selection_restored = true; - } - Ok(()) -} - -/// The wait before a probe: skipped on the first, `interval` while the -/// gateway answered last time (measured from the previous probe's -/// completion, so a slow probe never bunches into a catch-up burst), and -/// the backoff's next delay while it did not, ending the loop when the -/// backoff's budget exhausts. -async fn await_probe_interval( - last: Option, - interval: Duration, - backoff: &ReconnectBackoff, - push: &Push, - signals: &mut Signals<'_>, -) -> Result<(), Ended> { - let Some(reachable) = last else { - return Ok(()); - }; - let wait = if reachable { - interval - } else if let Some(delay) = backoff.next_delay() { - delay - } else { - push.push_failure( - "Gateway reconnect stopped", - "the reconnect budget is exhausted; restart the workshop to retry", - Activity::General, - ); - return Err(Ended::Stop); - }; - until(tokio::time::sleep(wait), signals).await -} - -/// Publishes the probe outcome and, when it differs from the last -/// verdict, reports the transition to the menu and the status bar. -fn announce_transition( - push: &Push, - health: &GatewayHealth, - reachable: bool, - last: &mut Option, -) { - health.publish(reachable); - let transitioned = *last != Some(reachable); - *last = Some(reachable); - if transitioned { - // The menu recomputes chat_ready from reachability, so the - // verdict feeds it before any slower refresh work below. - push.menu().set_gateway_reachable(reachable); - if reachable { - push.push_status_update( - CONNECTED_LABEL, - "the gateway answers its health probe", - Activity::General, - ); - } else { - push.push_status_update( - UNREACHABLE_LABEL, - UNREACHABLE_DESCRIPTION, - Activity::General, - ); - } - } -} - -/// Refreshes only the gateway-owned menu sources that have not converged. -/// All menu state is server-owned and reaches the UI via socket pushes - -/// the UI fetches nothing on boot - so every transition into reachable, -/// boot's first probe included, (re)populates the profile state and the -/// model catalog. Healthy ticks independently repeat either refresh until -/// both sources are populated, because health and one ready source do not -/// imply the other source is ready; the probe interval bounds retries and -/// keeps this from becoming a busy loop. -async fn refresh_incomplete_sources( - snapshot: &GatewaySnapshot, - push: &Push, - refresh: &mut RefreshState, -) { - match (refresh.profiles_ready, refresh.catalog_ready) { - (false, false) => { - (refresh.profiles_ready, refresh.catalog_ready) = tokio::join!( - refresh_profiles(snapshot.client(), push), - refresh_catalog(snapshot.client(), push) - ); - } - (false, true) => refresh.profiles_ready = refresh_profiles(snapshot.client(), push).await, - (true, false) => refresh.catalog_ready = refresh_catalog(snapshot.client(), push).await, - (true, true) => {} - } -} #[cfg(test)] #[path = "heartbeat-tests.rs"] mod tests; diff --git a/crates/workshop/gateway/src/lib.rs b/crates/workshop/gateway/src/lib.rs index c5d22fe2..c6b3abd0 100644 --- a/crates/workshop/gateway/src/lib.rs +++ b/crates/workshop/gateway/src/lib.rs @@ -24,7 +24,7 @@ //! [`MenuPush`](workshop_registry::MenuPush) face, so this crate never //! names another subsystem's bus. //! - The gateway's progress reaches this crate as one wire type defined in -//! `progress-wire.rs`: no progress machinery is shared with the gateway +//! `progress.rs`: no progress machinery is shared with the gateway //! family, and its field names are pinned by a golden JSON test so drift //! is caught. @@ -37,6 +37,8 @@ mod refresh; mod resolve; #[cfg(any(test, feature = "test-fixtures"))] pub mod test_gateway; +#[cfg(test)] +mod test_support; mod version; pub use binding::{GatewayBinding, GatewayPublicationError, GatewaySnapshot, GatewayUpdater}; diff --git a/crates/workshop/gateway/src/progress-wire-tests.rs b/crates/workshop/gateway/src/progress-wire-tests.rs index 9b320b20..29461d18 100644 --- a/crates/workshop/gateway/src/progress-wire-tests.rs +++ b/crates/workshop/gateway/src/progress-wire-tests.rs @@ -1,66 +1,57 @@ //! The progress wire contract, pinned by golden JSON. -//! -//! Workshop only deserializes `Progress`, so this file pins the field names -//! and their JSON types rather than a round trip. A rename on the Gateway's -//! side, or a type change here, fails one of these assertions instead of -//! silently leaving the status bar stuck. use super::*; #[test] -fn the_canonical_document_decodes_to_the_two_fields() { - let snapshot: Progress = - serde_json::from_str(r#"{"busy":true,"text":"Downloading qwen3-8b.gguf 45%"}"#) - .expect("the canonical document decodes"); - assert_eq!( - snapshot, - Progress { - busy: true, - text: "Downloading qwen3-8b.gguf 45%".to_owned(), - } - ); -} +fn progress_wire_json_decodes_valid_documents_and_rejects_malformed_ones() { + const VALID: &[(&str, &str, bool, &str)] = &[ + ( + "canonical busy document", + r#"{"busy":true,"text":"Downloading qwen3-8b.gguf 45%"}"#, + true, + "Downloading qwen3-8b.gguf 45%", + ), + ("idle document", r#"{"busy":false,"text":""}"#, false, ""), + ( + "tolerates unknown scalar field", + r#"{"busy":true,"text":"Loading","fraction":0.45}"#, + true, + "Loading", + ), + ( + "tolerates unknown nested field", + r#"{"busy":false,"text":"","extra":{"nested":[1,2]}}"#, + false, + "", + ), + ]; + const INVALID: &[(&str, &str)] = &[ + ("missing text field", r#"{"busy":true}"#), + ("missing busy field", r#"{"text":"Loading"}"#), + ("empty object", "{}"), + ("busy is string", r#"{"busy":"yes","text":""}"#), + ("text is number", r#"{"busy":false,"text":7}"#), + ("null text", r#"{"busy":false,"text":null}"#), + ]; -#[test] -fn an_idle_document_decodes_to_an_empty_text() { - let snapshot: Progress = - serde_json::from_str(r#"{"busy":false,"text":""}"#).expect("an idle document decodes"); - assert_eq!(snapshot, Progress::default()); -} + for &(label, document, busy, text) in VALID { + let snapshot: Progress = serde_json::from_str(document) + .unwrap_or_else(|error| panic!("{label}: expected valid JSON: {error}")); + assert_eq!( + snapshot, + Progress { + busy, + text: text.to_owned(), + }, + "{label}" + ); + } -#[test] -fn the_field_names_and_json_types_are_the_contract() { - // Pins the wire names and types through a decode of each, so a rename - // on either side fails here even if nobody updates a fixture. - // - // Both fields are required: the Gateway writes the whole snapshot on - // every event, so a document missing either one is malformed, and the - // decoder reports it rather than filling in a default. - for document in [r#"{"busy":true}"#, r#"{"text":"Loading"}"#] { + for &(label, document) in INVALID { let decoded = serde_json::from_str::(document); assert!( decoded.is_err(), - "both fields are required, so {document} must not decode: {decoded:?}" + "{label}: must fail to decode: {decoded:?}" ); } - - let wrong_type = serde_json::from_str::(r#"{"busy":"yes","text":""}"#); - assert!( - wrong_type.is_err(), - "busy is a boolean, not a string: {wrong_type:?}" - ); - let wrong_text = serde_json::from_str::(r#"{"busy":false,"text":7}"#); - assert!( - wrong_text.is_err(), - "text is a string, not a number: {wrong_text:?}" - ); -} - -#[test] -fn an_unknown_field_is_tolerated() { - // A newer Gateway adding a field must not break an older Workshop. - let snapshot: Progress = - serde_json::from_str(r#"{"busy":true,"text":"Loading","fraction":0.45}"#) - .expect("an unknown field is ignored"); - assert_eq!(snapshot.text, "Loading"); } diff --git a/crates/workshop/gateway/src/progress-wire.rs b/crates/workshop/gateway/src/progress-wire.rs deleted file mode 100644 index c4543b28..00000000 --- a/crates/workshop/gateway/src/progress-wire.rs +++ /dev/null @@ -1,35 +0,0 @@ -//! The gateway progress wire type, as Workshop reads it: one live activity, -//! a busy flag and a producer-owned text. -//! -//! [`Progress`] is the shape of one `GET /admin/progress` event and of the -//! progress field in `GET /admin/status`. Workshop only ever deserializes -//! it; the Gateway owns the producing side and the anti-flicker policy -//! lives in [`crate::progress`]. -//! -//! The field names and types are the contract. [`tests`] pins them against -//! a golden JSON document, so a rename or a type change on either side -//! fails here rather than in a status bar that silently stops updating. -//! -//! The text is user-visible, so a producer must never place a bearer key, -//! API key, or other credential in it. - -use serde::Deserialize; - -/// One snapshot of the Gateway's live activity. -/// -/// Deserialization tolerates fields this type does not know, which is what -/// lets a newer Gateway add one without breaking an older Workshop. There -/// is no schema version. -#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] -pub struct Progress { - /// Whether any activity is live. The UI shows an indeterminate - /// barberpole while this is set. - pub busy: bool, - /// The newest live activity's text, e.g. `"Downloading qwen3-8b.gguf - /// 45%"`; empty when idle. - pub text: String, -} - -#[cfg(test)] -#[path = "progress-wire-tests.rs"] -mod tests; diff --git a/crates/workshop/gateway/src/progress.rs b/crates/workshop/gateway/src/progress.rs index a9f15752..6d4cec74 100644 --- a/crates/workshop/gateway/src/progress.rs +++ b/crates/workshop/gateway/src/progress.rs @@ -5,7 +5,7 @@ //! barberpole plus the gateway's own text. //! //! The task follows the heartbeat's lifecycle posture: spawned with the -//! server, stopped through its [`Subscriber`] handle inside the same +//! server, stopped through its [`Heartbeat`] handle inside the same //! graceful-shutdown signal, and driven by the shared [`GatewayHealth`] //! verdict rather than by probes of its own. It subscribes while the //! gateway reads reachable and idles while it does not; a reconnect @@ -17,27 +17,18 @@ //! appeared still waits out its minimum visible time first, so a //! dropped stream cannot flash it. -mod presenter; -#[path = "progress-wire.rs"] -mod wire; - -use std::future::Future; +use std::future::{self, Future}; use std::time::Duration; use futures_util::StreamExt; +use serde::Deserialize; use tokio::sync::{oneshot, watch}; -use tokio::time::Instant; - +use tokio::time::{self, Instant}; +use workshop_protocol::Activity; use workshop_registry::Push; -use crate::binding::{GatewayBinding, GatewaySnapshot}; -use crate::client::ProgressStream; -use crate::heartbeat::GatewayHealth; -pub(crate) use wire::Progress; - -#[cfg(test)] -use presenter::{MIN_VISIBLE, SHOW_DELAY}; -use presenter::{Policy, Presenter}; +use crate::binding::GatewayBinding; +use crate::heartbeat::{GatewayHealth, Heartbeat}; /// How long a resubscribe waits when the stream ended while the gateway /// still reads reachable, so an endpoint that accepts and immediately @@ -45,6 +36,165 @@ use presenter::{Policy, Presenter}; /// matched to the heartbeat's probe cadence. const RESUBSCRIBE_DELAY: Duration = Duration::from_secs(5); +/// How long the gateway must stay busy before the barberpole appears; +/// work shorter than this never disturbs the status bar. +const SHOW_DELAY: Duration = Duration::from_secs(1); + +/// How long the barberpole stays up once shown, so work that ends just +/// past [`SHOW_DELAY`] reads as a completed activity. +const MIN_VISIBLE: Duration = Duration::from_millis(500); + +/// The tooltip on every gateway busy frame. +const DESCRIPTION: &str = "gateway activity"; + +/// One snapshot of the Gateway's live activity (`GET /admin/progress` and +/// the progress field in `GET /admin/status`). +/// +/// Deserialization tolerates fields this type does not know, which is what +/// lets a newer Gateway add one without breaking an older Workshop. There +/// is no schema version. The text is user-visible, so a producer must never +/// place a bearer key, API key, or other credential in it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct Progress { + /// Whether any activity is live. The UI shows an indeterminate + /// barberpole while this is set. + pub busy: bool, + /// The newest live activity's text, e.g. `"Downloading qwen3-8b.gguf + /// 45%"`; empty when idle. + pub text: String, +} + +/// The two anti-flicker durations, injectable so the subscriber tests +/// run against a live mock gateway without waiting out the production +/// values. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Policy { + /// Busy time before the barberpole appears. + show_delay: Duration, + /// Minimum time the barberpole stays up once shown. + min_visible: Duration, +} + +impl Policy { + /// The production policy. + const DEFAULT: Self = Self { + show_delay: SHOW_DELAY, + min_visible: MIN_VISIBLE, + }; +} + +/// The gateway is busy: since when, and its newest text. +#[derive(Debug)] +struct Live { + since: Instant, + text: String, +} + +/// The barberpole is up: since when, and the text last pushed. +#[derive(Debug)] +struct Shown { + at: Instant, + text: String, +} + +/// The anti-flicker state machine over gateway snapshots. +#[derive(Debug)] +struct Presenter { + policy: Policy, + live: Option, + shown: Option, +} + +impl Presenter { + /// A presenter at rest: nothing live, nothing shown. + fn new(policy: Policy) -> Self { + Self { + policy, + live: None, + shown: None, + } + } + + /// Records one decoded snapshot at `now` and pushes whatever + /// transition it calls for. A busy snapshot starts the show delay + /// (or replaces the live text); an idle snapshot ends the busy run + /// and starts the minimum-visible hold if the bar is up. + fn apply(&mut self, snapshot: Progress, now: Instant, push: &Push) { + if snapshot.busy { + match &mut self.live { + Some(live) => live.text = snapshot.text, + None => { + self.live = Some(Live { + since: now, + text: snapshot.text, + }); + } + } + } else { + self.live = None; + } + self.settle(now, push); + } + + /// Re-evaluates the deadlines at `now` without a new snapshot: the + /// show delay lapsing pushes the bar up, the minimum-visible hold + /// lapsing pushes it idle. + fn tick(&mut self, now: Instant, push: &Push) { + self.settle(now, push); + } + + /// The next moment [`Presenter::tick`] can change state without a + /// snapshot: the show deadline while the gateway warms up, or the + /// earliest idle moment once the gateway went idle under a shown bar. + fn next_wake(&self) -> Option { + match (&self.live, &self.shown) { + (Some(live), None) => Some(live.since + self.policy.show_delay), + (None, Some(shown)) => Some(shown.at + self.policy.min_visible), + (Some(_), Some(_)) | (None, None) => None, + } + } + + /// The subscription is gone at `now`: progress from a gateway the + /// workshop can no longer hear is stale, so this reads as an idle + /// snapshot. Any pending show is forgotten, and a shown bar rests once + /// its minimum-visible hold has lapsed, the same hold an idle snapshot + /// gets; the subscriber keeps [`Presenter::next_wake`] armed between + /// subscriptions so the hold lapses on time. + fn detach(&mut self, now: Instant, push: &Push) { + self.live = None; + self.settle(now, push); + } + + fn settle(&mut self, now: Instant, push: &Push) { + let Some(live) = &self.live else { + if let Some(shown) = &self.shown + && now.duration_since(shown.at) >= self.policy.min_visible + { + self.shown = None; + push.push_idle(); + } + return; + }; + match self.shown.as_mut() { + None => { + if now.duration_since(live.since) >= self.policy.show_delay { + push.push_busy(live.text.clone(), DESCRIPTION, Activity::General); + self.shown = Some(Shown { + at: now, + text: live.text.clone(), + }); + } + } + Some(shown) => { + if shown.text != live.text { + push.push_busy(live.text.clone(), DESCRIPTION, Activity::General); + shown.text.clone_from(&live.text); + } + } + } + } +} + /// The subscriber's durations, injectable so tests can shorten them. #[derive(Debug, Clone, Copy)] struct Timing { @@ -62,34 +212,11 @@ impl Timing { }; } -/// A running subscriber task. -/// -/// [`Subscriber::shutdown`] signals the task to stop and awaits it. -/// Dropping the handle without shutting down still stops the task at its -/// next select point, because the closed channel resolves the stop branch. -#[derive(Debug)] -pub(crate) struct Subscriber { - stop: Option>, - task: Option>, -} - -impl Subscriber { - /// Signals the subscriber to stop and waits for its task to finish. - pub(crate) async fn shutdown(mut self) { - if let Some(stop) = self.stop.take() { - let _ = stop.send(()); - } - if let Some(task) = self.task.take() { - let _ = task.await; - } - } -} - /// Spawns the subscriber task against the gateway behind `gateway`, /// pushing busy and idle frames through `push` while `health` reads /// reachable. #[must_use] -pub(crate) fn spawn(gateway: GatewayBinding, push: Push, health: GatewayHealth) -> Subscriber { +pub(crate) fn spawn(gateway: GatewayBinding, push: Push, health: GatewayHealth) -> Heartbeat { spawn_with_timing(gateway, push, health, Timing::DEFAULT) } @@ -99,12 +226,12 @@ fn spawn_with_timing( push: Push, health: GatewayHealth, timing: Timing, -) -> Subscriber { +) -> Heartbeat { let (stop, mut stopped) = oneshot::channel(); let task = tokio::spawn(async move { run(&gateway, &push, &health, timing, &mut stopped).await; }); - Subscriber { + Heartbeat { stop: Some(stop), task: Some(task), } @@ -141,11 +268,10 @@ impl Signals<'_> { } } -/// The subscription loop, in named phases: idle while unreachable, -/// subscribe, drive the subscription, and recover from its end. Every -/// wait goes through [`until`] and [`ticking`], so the stop signal wins -/// each select and the presenter's deadlines keep ticking between -/// subscriptions. +/// The subscription loop: idle while unreachable, subscribe, drive the +/// subscription, and recover from its end. Every wait goes through +/// [`until`] and [`ticking`], so the stop signal wins each select and the +/// presenter's deadlines keep ticking between subscriptions. async fn run( gateway: &GatewayBinding, push: &Push, @@ -162,139 +288,75 @@ async fn run( }; let mut presenter = Presenter::new(timing.policy); loop { - if let Err(Ended::Stop) = idle_until_reachable(&mut signals, &mut presenter, push).await { - return; + while !signals.reachable_now() { + match until( + ticking(future::pending::<()>(), &mut presenter, push), + &mut signals, + ) + .await + { + Err(Ended::Stop) => return, + Err(Ended::Lost | Ended::Rebind) | Ok(()) => {} + } } let snapshot = gateway.snapshot(); - let stream = match subscribe(&snapshot, timing, &mut signals, &mut presenter, push).await { - Ok(stream) => stream, - Err(Ended::Stop) => return, - Err(Ended::Lost | Ended::Rebind) => continue, - }; - let ended = drive_stream(stream, &mut signals, &mut presenter, push).await; - if let Err(Ended::Stop) = recover(ended, timing, &mut signals, &mut presenter, push).await { - return; - } - } -} - -/// Idles while the gateway reads unreachable, waking on any control -/// signal. Returns to proceed with a subscription, or on stop. -async fn idle_until_reachable( - signals: &mut Signals<'_>, - presenter: &mut Presenter, - push: &Push, -) -> Result<(), Ended> { - while !signals.reachable_now() { - match until( - ticking(std::future::pending::<()>(), presenter, push), - signals, + let stream = match until( + ticking(snapshot.client().subscribe_progress(), &mut presenter, push), + &mut signals, ) .await { - Err(Ended::Stop) => return Err(Ended::Stop), - Err(Ended::Lost | Ended::Rebind) | Ok(()) => {} - } - } - Ok(()) -} - -/// Opens one progress subscription, waiting out the resubscribe delay and -/// looping around when the endpoint declines. Returns the stream, or an -/// [`Ended`] telling the loop to stop or loop around again. -async fn subscribe( - snapshot: &GatewaySnapshot, - timing: Timing, - signals: &mut Signals<'_>, - presenter: &mut Presenter, - push: &Push, -) -> Result { - match until( - ticking(snapshot.client().subscribe_progress(), presenter, push), - signals, - ) - .await - { - Err(ended) => return Err(ended), - Ok(Ok(stream)) => return Ok(stream), - Ok(Err(error)) => { - tracing::warn!(%error, "gateway progress subscription failed"); - } - } - // A declined subscription waits out the resubscribe delay, then loops - // around to try again. - match until( - ticking( - tokio::time::sleep(timing.resubscribe_delay), - presenter, - push, - ), - signals, - ) - .await - { - Err(Ended::Stop) => Err(Ended::Stop), - Err(Ended::Lost | Ended::Rebind) | Ok(()) => Err(Ended::Lost), - } -} - -/// Drives one subscription: every snapshot reaches the presenter, a -/// malformed snapshot is skipped, and the stream's own end is reported. -async fn drive_stream( - stream: ProgressStream, - signals: &mut Signals<'_>, - presenter: &mut Presenter, - push: &Push, -) -> Ended { - tokio::pin!(stream); - loop { - match until(ticking(stream.next(), presenter, push), signals).await { - Err(ended) => break ended, - Ok(Some(Ok(snapshot))) => presenter.apply(snapshot, Instant::now(), push), - // One malformed snapshot or a terminal read failure; the - // stream itself decides which by continuing or ending. - Ok(Some(Err(error))) => { - tracing::warn!(%error, "gateway progress snapshot skipped"); + Err(Ended::Stop) => return, + Err(Ended::Lost | Ended::Rebind) => continue, + Ok(Ok(stream)) => stream, + Ok(Err(error)) => { + tracing::warn!(%error, "gateway progress subscription failed"); + match until( + ticking(time::sleep(timing.resubscribe_delay), &mut presenter, push), + &mut signals, + ) + .await + { + Err(Ended::Stop) => return, + Err(Ended::Lost | Ended::Rebind) | Ok(()) => continue, + } } - Ok(None) => break Ended::Lost, - } - } -} - -/// Handles a subscription's end: the bar rests because a subscription the -/// workshop can no longer hear is stale, and - while still reachable - the -/// loop waits out the resubscribe delay before subscribing again. -async fn recover( - ended: Ended, - timing: Timing, - signals: &mut Signals<'_>, - presenter: &mut Presenter, - push: &Push, -) -> Result<(), Ended> { - match ended { - Ended::Stop => return Err(Ended::Stop), - Ended::Rebind => { - presenter.detach(Instant::now(), push); - return Ok(()); + }; + let ended = { + tokio::pin!(stream); + loop { + match until(ticking(stream.next(), &mut presenter, push), &mut signals).await { + Err(ended) => break ended, + Ok(Some(Ok(snapshot))) => presenter.apply(snapshot, Instant::now(), push), + // One malformed snapshot or a terminal read failure; the + // stream itself decides which by continuing or ending. + Ok(Some(Err(error))) => { + tracing::warn!(%error, "gateway progress snapshot skipped"); + } + Ok(None) => break Ended::Lost, + } + } + }; + match ended { + Ended::Stop => return, + Ended::Rebind => { + presenter.detach(Instant::now(), push); + continue; + } + Ended::Lost => presenter.detach(Instant::now(), push), } - Ended::Lost => presenter.detach(Instant::now(), push), - } - if signals.reachable_now() { - match until( - ticking( - tokio::time::sleep(timing.resubscribe_delay), - presenter, - push, - ), - signals, - ) - .await - { - Err(Ended::Stop) => return Err(Ended::Stop), - Err(Ended::Lost | Ended::Rebind) | Ok(()) => {} + if signals.reachable_now() { + match until( + ticking(time::sleep(timing.resubscribe_delay), &mut presenter, push), + &mut signals, + ) + .await + { + Err(Ended::Stop) => return, + Err(Ended::Lost | Ended::Rebind) | Ok(()) => {} + } } } - Ok(()) } /// Awaits `future` with the control signals armed beside it. A control @@ -323,7 +385,7 @@ async fn reachability_changed( ) -> Result<(), watch::error::RecvError> { match reachable { Some(reachable) => reachable.changed().await, - None => std::future::pending().await, + None => future::pending().await, } } @@ -343,8 +405,8 @@ async fn ticking(future: F, presenter: &mut Presenter, push: &Push) - /// Waits for `at`, or forever when there is no pending deadline. async fn wake_at(at: Option) { match at { - Some(at) => tokio::time::sleep_until(at).await, - None => std::future::pending().await, + Some(at) => time::sleep_until(at).await, + None => future::pending().await, } } diff --git a/crates/workshop/gateway/src/progress/presenter.rs b/crates/workshop/gateway/src/progress/presenter.rs deleted file mode 100644 index 1c791786..00000000 --- a/crates/workshop/gateway/src/progress/presenter.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! The anti-flicker policy between the gateway's progress snapshots and -//! the status bar: the barberpole appears only once the gateway has been -//! busy for [`SHOW_DELAY`], stays up at least [`MIN_VISIBLE`] once shown, -//! and follows the newest text while up. The policy lives here, next to -//! the subscriber that feeds it, so the UI stays dumb and the wire type -//! stays a plain busy flag plus text. -//! -//! [`Presenter`] is a pure state machine over explicit instants: the -//! subscriber loop hands it every decoded snapshot and wakes it at -//! [`Presenter::next_wake`], and the tests drive it with instants of -//! their own choosing. - -use std::time::Duration; - -use tokio::time::Instant; - -use workshop_protocol::Activity; -use workshop_registry::Push; - -use super::Progress; - -/// How long the gateway must stay busy before the barberpole appears; -/// work shorter than this never disturbs the status bar. -pub(super) const SHOW_DELAY: Duration = Duration::from_secs(1); - -/// How long the barberpole stays up once shown, so work that ends just -/// past [`SHOW_DELAY`] reads as a completed activity. -pub(super) const MIN_VISIBLE: Duration = Duration::from_millis(500); - -/// The tooltip on every gateway busy frame. -const DESCRIPTION: &str = "gateway activity"; - -/// The two anti-flicker durations, injectable so the subscriber tests -/// run against a live mock gateway without waiting out the production -/// values. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) struct Policy { - /// Busy time before the barberpole appears. - pub(super) show_delay: Duration, - /// Minimum time the barberpole stays up once shown. - pub(super) min_visible: Duration, -} - -impl Policy { - /// The production policy. - pub(super) const DEFAULT: Self = Self { - show_delay: SHOW_DELAY, - min_visible: MIN_VISIBLE, - }; -} - -/// The gateway is busy: since when, and its newest text. -#[derive(Debug)] -struct Live { - since: Instant, - text: String, -} - -/// The barberpole is up: since when, and the text last pushed. -#[derive(Debug)] -struct Shown { - at: Instant, - text: String, -} - -/// The anti-flicker state machine over gateway snapshots. -#[derive(Debug)] -pub(super) struct Presenter { - policy: Policy, - live: Option, - shown: Option, -} - -impl Presenter { - /// A presenter at rest: nothing live, nothing shown. - pub(super) fn new(policy: Policy) -> Self { - Self { - policy, - live: None, - shown: None, - } - } - - /// Records one decoded snapshot at `now` and pushes whatever - /// transition it calls for. A busy snapshot starts the show delay - /// (or replaces the live text); an idle snapshot ends the busy run - /// and starts the minimum-visible hold if the bar is up. - pub(super) fn apply(&mut self, snapshot: Progress, now: Instant, push: &Push) { - if snapshot.busy { - match &mut self.live { - Some(live) => live.text = snapshot.text, - None => { - self.live = Some(Live { - since: now, - text: snapshot.text, - }); - } - } - } else { - self.live = None; - } - self.settle(now, push); - } - - /// Re-evaluates the deadlines at `now` without a new snapshot: the - /// show delay lapsing pushes the bar up, the minimum-visible hold - /// lapsing pushes it idle. - pub(super) fn tick(&mut self, now: Instant, push: &Push) { - self.settle(now, push); - } - - /// The next moment [`Presenter::tick`] can change state without a - /// snapshot: the show deadline while the gateway warms up, or the - /// earliest idle moment once the gateway went idle under a shown bar. - pub(super) fn next_wake(&self) -> Option { - match (&self.live, &self.shown) { - (Some(live), None) => Some(live.since + self.policy.show_delay), - (None, Some(shown)) => Some(shown.at + self.policy.min_visible), - (Some(_), Some(_)) | (None, None) => None, - } - } - - /// The subscription is gone at `now`: progress from a gateway the - /// workshop can no longer hear is stale, so this reads as an idle - /// snapshot. Any pending show is forgotten, and a shown bar rests once - /// its minimum-visible hold has lapsed, the same hold an idle snapshot - /// gets; the subscriber keeps [`Presenter::next_wake`] armed between - /// subscriptions so the hold lapses on time. - pub(super) fn detach(&mut self, now: Instant, push: &Push) { - self.live = None; - self.settle(now, push); - } - - fn settle(&mut self, now: Instant, push: &Push) { - let Some(live) = &self.live else { - if let Some(shown) = &self.shown - && now.duration_since(shown.at) >= self.policy.min_visible - { - self.shown = None; - push.push_idle(); - } - return; - }; - match self.shown.as_mut() { - None => { - if now.duration_since(live.since) >= self.policy.show_delay { - push.push_busy(live.text.clone(), DESCRIPTION, Activity::General); - self.shown = Some(Shown { - at: now, - text: live.text.clone(), - }); - } - } - Some(shown) => { - if shown.text != live.text { - push.push_busy(live.text.clone(), DESCRIPTION, Activity::General); - shown.text.clone_from(&live.text); - } - } - } - } -} diff --git a/crates/workshop/gateway/src/progress/tests-presenter.rs b/crates/workshop/gateway/src/progress/tests-presenter.rs index f7285ea4..bfc49476 100644 --- a/crates/workshop/gateway/src/progress/tests-presenter.rs +++ b/crates/workshop/gateway/src/progress/tests-presenter.rs @@ -1,14 +1,11 @@ -//! The anti-flicker presenter pinned with explicit instants: a busy -//! snapshot shows only after the show delay, an idle snapshot before the -//! delay pushes nothing, an idle arriving within the minimum visible time -//! is deferred to it, text changes republish while shown, and a detach -//! rests a shown bar under the same hold. +//! The anti-flicker presenter pinned with explicit instants: show delay, +//! symmetric idle/detach deferral and immediate rest, text republishing, +//! and work resuming during the minimum-visible hold. use super::*; -/// A presenter under the production policy, its push, and the recorder. -fn wired() -> (Presenter, Recorder) { - (Presenter::new(Policy::DEFAULT), recorder()) +fn wired() -> (Presenter, StatusRecorder) { + (Presenter::new(Policy::DEFAULT), StatusRecorder::new()) } fn busy(text: &str) -> Progress { @@ -18,114 +15,119 @@ fn busy(text: &str) -> Progress { } } -fn idle() -> Progress { - Progress::default() +#[derive(Clone, Copy)] +enum Trigger { + Idle, + Detach, } -#[tokio::test] -async fn a_busy_snapshot_pushes_only_once_the_show_delay_has_passed() { - let (mut presenter, recorder) = wired(); - let start = Instant::now(); - presenter.apply(busy("Downloading model"), start, &recorder.push); - assert!( - recorder.pushed().is_empty(), - "a fresh busy snapshot must not flash the bar" - ); - assert_eq!( - presenter.next_wake(), - Some(start + SHOW_DELAY), - "the presenter asks to wake exactly at the show deadline" - ); - - presenter.tick( - start + SHOW_DELAY - Duration::from_millis(1), - &recorder.push, - ); - assert!( - recorder.pushed().is_empty(), - "one millisecond short of the delay is still too soon" - ); +impl Trigger { + const ALL: [(&'static str, Self); 2] = [("idle", Self::Idle), ("detach", Self::Detach)]; - presenter.tick(start + SHOW_DELAY, &recorder.push); - assert_eq!( - recorder.pushed(), - [("Downloading model".to_owned(), true)], - "the delay lapsing pushes one busy frame holding the gateway text" - ); - assert_eq!( - presenter.next_wake(), - None, - "a shown bar with live work has no deadline of its own" - ); -} - -#[tokio::test] -async fn an_idle_snapshot_before_the_show_delay_pushes_nothing() { - let (mut presenter, recorder) = wired(); - let start = Instant::now(); - presenter.apply(busy("Loading profile"), start, &recorder.push); - presenter.apply(idle(), start + Duration::from_millis(300), &recorder.push); - presenter.tick(start + SHOW_DELAY * 2, &recorder.push); - assert!( - recorder.pushed().is_empty(), - "sub-second work never disturbs the status bar" - ); - assert_eq!(presenter.next_wake(), None); + fn fire(self, presenter: &mut Presenter, at: Instant, push: &Push) { + match self { + Self::Idle => presenter.apply(Progress::default(), at, push), + Self::Detach => presenter.detach(at, push), + } + } } #[tokio::test] -async fn an_idle_snapshot_within_the_minimum_visible_time_is_deferred_to_it() { +async fn a_busy_snapshot_pushes_only_once_the_show_delay_has_passed() { let (mut presenter, recorder) = wired(); let start = Instant::now(); presenter.apply(busy("Downloading model"), start, &recorder.push); - let shown = start + SHOW_DELAY; - presenter.tick(shown, &recorder.push); - assert_eq!(recorder.pushed().len(), 1, "the bar is up"); - - let ended = shown + Duration::from_millis(100); - presenter.apply(idle(), ended, &recorder.push); - assert_eq!( - recorder.pushed().len(), - 1, - "an idle arriving 100ms after showing must not flash the bar off" - ); - assert_eq!( - presenter.next_wake(), - Some(shown + MIN_VISIBLE), - "the presenter asks to wake when the minimum visible time lapses" - ); + assert!(recorder.pushed().is_empty()); + assert_eq!(presenter.next_wake(), Some(start + SHOW_DELAY)); presenter.tick( - shown + MIN_VISIBLE - Duration::from_millis(1), + start + SHOW_DELAY - Duration::from_millis(1), &recorder.push, ); - assert_eq!(recorder.pushed().len(), 1, "still inside the hold"); + assert!(recorder.pushed().is_empty()); - presenter.tick(shown + MIN_VISIBLE, &recorder.push); - assert_eq!( - recorder.pushed(), - [ - ("Downloading model".to_owned(), true), - ("Ready".to_owned(), false), - ], - "the hold lapsing rests the bar" - ); + presenter.tick(start + SHOW_DELAY, &recorder.push); + assert_eq!(recorder.pushed(), [("Downloading model".to_owned(), true)]); assert_eq!(presenter.next_wake(), None); } #[tokio::test] -async fn an_idle_snapshot_after_the_minimum_visible_time_rests_the_bar_at_once() { - let (mut presenter, recorder) = wired(); - let start = Instant::now(); - presenter.apply(busy("Downloading model"), start, &recorder.push); - let shown = start + SHOW_DELAY; - presenter.tick(shown, &recorder.push); - presenter.apply(idle(), shown + MIN_VISIBLE * 4, &recorder.push); - assert_eq!( - recorder.pushed().last(), - Some(&("Ready".to_owned(), false)), - "an idle past the hold needs no deferral" - ); +async fn idle_and_detach_obey_symmetric_delay_and_min_visible_rules() { + #[derive(Clone, Copy)] + enum Phase { + Rested, + Pending(u64), + Shown(u64, bool), + } + const CASES: &[(&str, Phase)] = &[ + ("while rested is no-op", Phase::Rested), + ("before show delay pushes nothing", Phase::Pending(300)), + ("inside min_visible defers", Phase::Shown(100, true)), + ("1ms before min_visible defers", Phase::Shown(499, true)), + ( + "at exact min_visible rests immediately", + Phase::Shown(500, false), + ), + ( + "well past min_visible rests immediately", + Phase::Shown(2000, false), + ), + ]; + + for (trigger_name, trigger) in Trigger::ALL { + for &(scenario, phase) in CASES { + let label = format!("{trigger_name} {scenario}"); + let (mut presenter, recorder) = wired(); + let start = Instant::now(); + match phase { + Phase::Rested => { + trigger.fire(&mut presenter, start, &recorder.push); + assert!(recorder.pushed().is_empty(), "{label}"); + assert_eq!(presenter.next_wake(), None, "{label}"); + } + Phase::Pending(ms) => { + presenter.apply(busy("Loading profile"), start, &recorder.push); + trigger.fire( + &mut presenter, + start + Duration::from_millis(ms), + &recorder.push, + ); + assert_eq!(presenter.next_wake(), None, "{label}"); + presenter.tick(start + SHOW_DELAY * 2, &recorder.push); + assert!(recorder.pushed().is_empty(), "{label}"); + } + Phase::Shown(ms, defers) => { + presenter.apply(busy("Downloading model"), start, &recorder.push); + let shown = start + SHOW_DELAY; + presenter.tick(shown, &recorder.push); + trigger.fire( + &mut presenter, + shown + Duration::from_millis(ms), + &recorder.push, + ); + if defers { + assert_eq!(recorder.pushed().len(), 1, "{label}"); + assert_eq!(presenter.next_wake(), Some(shown + MIN_VISIBLE), "{label}"); + presenter.tick( + shown + MIN_VISIBLE - Duration::from_millis(1), + &recorder.push, + ); + assert_eq!(recorder.pushed().len(), 1, "{label}"); + presenter.tick(shown + MIN_VISIBLE, &recorder.push); + } + assert_eq!( + recorder.pushed(), + [ + ("Downloading model".to_owned(), true), + ("Ready".to_owned(), false) + ], + "{label}" + ); + assert_eq!(presenter.next_wake(), None, "{label}"); + } + } + } + } } #[tokio::test] @@ -138,16 +140,13 @@ async fn a_text_change_while_shown_republishes_and_an_unchanged_text_does_not() start + Duration::from_millis(500), &recorder.push, ); - assert!( - recorder.pushed().is_empty(), - "text changes before the delay stay pending" - ); + assert!(recorder.pushed().is_empty()); + let shown = start + SHOW_DELAY; presenter.tick(shown, &recorder.push); assert_eq!( recorder.pushed(), - [("Downloading model 20%".to_owned(), true)], - "the delay lapsing pushes the newest text, not the first" + [("Downloading model 20%".to_owned(), true)] ); presenter.apply( @@ -155,11 +154,7 @@ async fn a_text_change_while_shown_republishes_and_an_unchanged_text_does_not() shown + Duration::from_millis(10), &recorder.push, ); - assert_eq!( - recorder.pushed().len(), - 1, - "a snapshot repeating the shown text is not re-pushed" - ); + assert_eq!(recorder.pushed().len(), 1); presenter.apply( busy("Downloading model 30%"), @@ -168,92 +163,36 @@ async fn a_text_change_while_shown_republishes_and_an_unchanged_text_does_not() ); assert_eq!( recorder.pushed().last(), - Some(&("Downloading model 30%".to_owned(), true)), - "a new text republishes while the bar is up" + Some(&("Downloading model 30%".to_owned(), true)) ); } #[tokio::test] async fn work_resuming_during_the_hold_keeps_the_bar_up_without_a_new_delay() { - let (mut presenter, recorder) = wired(); - let start = Instant::now(); - presenter.apply(busy("Selecting profile"), start, &recorder.push); - let shown = start + SHOW_DELAY; - presenter.tick(shown, &recorder.push); - presenter.apply(idle(), shown + Duration::from_millis(100), &recorder.push); - presenter.apply( - busy("Starting models"), - shown + Duration::from_millis(200), - &recorder.push, - ); - assert_eq!( - recorder.pushed(), - [ - ("Selecting profile".to_owned(), true), - ("Starting models".to_owned(), true), - ], - "back-to-back work shares one visible run: no idle frame, no second delay" - ); - assert_eq!(presenter.next_wake(), None); -} - -#[tokio::test] -async fn a_detach_within_the_minimum_visible_time_is_deferred_to_it() { - let (mut presenter, recorder) = wired(); - let start = Instant::now(); - presenter.apply(busy("Downloading model"), start, &recorder.push); - let shown = start + SHOW_DELAY; - presenter.tick(shown, &recorder.push); - presenter.detach(shown + Duration::from_millis(100), &recorder.push); - assert_eq!( - recorder.pushed().len(), - 1, - "a subscription lost 100ms after showing must not flash the bar off" - ); - assert_eq!( - presenter.next_wake(), - Some(shown + MIN_VISIBLE), - "the presenter asks to wake when the minimum visible time lapses" - ); - - presenter.tick(shown + MIN_VISIBLE, &recorder.push); - assert_eq!( - recorder.pushed(), - [ - ("Downloading model".to_owned(), true), - ("Ready".to_owned(), false), - ], - "the hold lapsing rests the bar" - ); - assert_eq!(presenter.next_wake(), None); -} - -#[tokio::test] -async fn a_detach_after_the_minimum_visible_time_rests_the_bar_at_once() { - let (mut presenter, recorder) = wired(); - let start = Instant::now(); - presenter.apply(busy("Downloading model"), start, &recorder.push); - let shown = start + SHOW_DELAY; - presenter.tick(shown, &recorder.push); - presenter.detach(shown + MIN_VISIBLE, &recorder.push); - assert_eq!( - recorder.pushed().last(), - Some(&("Ready".to_owned(), false)), - "a lost subscription past the hold rests the bar at once" - ); - assert_eq!(presenter.next_wake(), None); -} - -#[tokio::test] -async fn a_detach_before_the_bar_showed_forgets_the_pending_work() { - let (mut presenter, recorder) = wired(); - let start = Instant::now(); - presenter.apply(busy("Downloading model"), start, &recorder.push); - presenter.detach(start + Duration::from_millis(300), &recorder.push); - assert_eq!(presenter.next_wake(), None); - presenter.tick(start + SHOW_DELAY * 2, &recorder.push); - assert!( - recorder.pushed().is_empty(), - "a detach before the bar showed pushes nothing, then or later" - ); + for (label, trigger) in Trigger::ALL { + let (mut presenter, recorder) = wired(); + let start = Instant::now(); + presenter.apply(busy("Selecting profile"), start, &recorder.push); + let shown = start + SHOW_DELAY; + presenter.tick(shown, &recorder.push); + trigger.fire( + &mut presenter, + shown + Duration::from_millis(100), + &recorder.push, + ); + presenter.apply( + busy("Starting models"), + shown + Duration::from_millis(200), + &recorder.push, + ); + assert_eq!( + recorder.pushed(), + [ + ("Selecting profile".to_owned(), true), + ("Starting models".to_owned(), true) + ], + "{label}" + ); + assert_eq!(presenter.next_wake(), None, "{label}"); + } } diff --git a/crates/workshop/gateway/src/progress/tests-recovery.rs b/crates/workshop/gateway/src/progress/tests-recovery.rs index 874dc639..32b3e8cc 100644 --- a/crates/workshop/gateway/src/progress/tests-recovery.rs +++ b/crates/workshop/gateway/src/progress/tests-recovery.rs @@ -5,11 +5,11 @@ use super::*; #[tokio::test] async fn an_endpoint_replacement_moves_the_progress_subscription_immediately() { let original = Arc::new(MockProgress::new()); - let original_url = spawn_gateway(Arc::clone(&original).router()).await; + let original_url = serve(Arc::clone(&original).router()).await; let replacement = Arc::new(MockProgress::new()); - let replacement_url = spawn_gateway(Arc::clone(&replacement).router()).await; + let replacement_url = serve(Arc::clone(&replacement).router()).await; let gateway = binding(&original_url); - let recorder = recorder(); + let recorder = StatusRecorder::new(); let subscriber = spawn_with_timing( gateway.clone(), recorder.push.clone(), diff --git a/crates/workshop/gateway/src/progress/tests.rs b/crates/workshop/gateway/src/progress/tests.rs index af02b547..e296cac5 100644 --- a/crates/workshop/gateway/src/progress/tests.rs +++ b/crates/workshop/gateway/src/progress/tests.rs @@ -2,23 +2,17 @@ //! reach the status bar as busy frames under the anti-flicker policy, //! a malformed snapshot is skipped, a closed stream resubscribes after //! the delay, an unreachable gateway holds no subscription, and a -//! reconnect rests the bar and resubscribes once. A lost subscription -//! rests the bar under the presenter's minimum-visible hold, which the -//! loop keeps ticking between subscriptions. The presenter's timing -//! rules are pinned separately with explicit instants; here the policy -//! runs at millisecond scale so the mock round trips stay fast. - -use super::*; +//! reconnect rests the bar and resubscribes once. use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::{Arc, Mutex}; use axum::extract::State; use axum::response::{IntoResponse, Response}; use tokio::sync::broadcast; -use workshop_protocol::StatusBarUpdate; -use workshop_registry::{Registration, Registry, StatusSink, StatusSinkAdapter}; +use super::*; +use crate::test_support::{StatusRecorder, serve}; /// The anti-flicker policy the mock-gateway tests run under: short /// enough that a test waits milliseconds, long enough that a snapshot @@ -34,80 +28,14 @@ const FAST_TIMING: Timing = Timing { policy: FAST_POLICY, }; -/// Binds `app` as a mock gateway on a free loopback port and returns its -/// base URL. -async fn spawn_gateway(app: axum::Router) -> String { - let (addr, _handle) = workshop_support::fixtures::serve(app).await; - format!("http://{addr}") -} - /// A replaceable binding for one mock gateway. fn binding(base_url: &str) -> GatewayBinding { GatewayBinding::new(base_url, "").expect("the test binding builds") } -/// A recording status sink behind a [`Push`]: every frame the subscriber -/// pushes lands in `frames`, in order. -struct Recorder { - push: Push, - frames: Arc>>, - _guard: Registration, -} - -fn recorder() -> Recorder { - let registry = Registry::new(); - let frames: Arc>> = Arc::new(Mutex::new(Vec::new())); - let sink = Arc::clone(&frames); - let guard = - registry.register_sink::(Arc::new(StatusSinkAdapter::new(move |update| { - sink.lock() - .unwrap_or_else(PoisonError::into_inner) - .push(update); - }))); - Recorder { - push: registry.push(), - frames, - _guard: guard, - } -} - -impl Recorder { - /// The `(label, busy)` of every frame pushed so far. - fn pushed(&self) -> Vec<(String, bool)> { - self.frames - .lock() - .unwrap_or_else(PoisonError::into_inner) - .iter() - .map(|update| (update.label.clone(), update.busy)) - .collect() - } - - /// Polls until `accept` holds over the pushed frames, within a - /// generous deadline (the heartbeat tests' snapshot_where pattern). - async fn frames_where( - &self, - accept: impl Fn(&[(String, bool)]) -> bool, - ) -> Vec<(String, bool)> { - tokio::time::timeout(Duration::from_secs(5), async { - loop { - let pushed = self.pushed(); - if accept(&pushed) { - return pushed; - } - tokio::time::sleep(Duration::from_millis(5)).await; - } - }) - .await - .expect("matching frames arrive within the deadline") - } -} - /// A mock `GET /admin/progress`: every payload published to the feed /// streams to every connected subscriber as an SSE `data:` frame, and -/// `connections` counts how often the endpoint was hit. The receiver -/// is created before the count increments, so a test that observes a -/// connection can publish without losing the frame. [`close`](Self::close) -/// ends every live stream, so a test can drive the resubscribe path. +/// `connections` counts how often the endpoint was hit. struct MockProgress { connections: AtomicUsize, feeds: Mutex>, @@ -187,18 +115,23 @@ async fn wait_for_connections(mock: &MockProgress, n: usize) { .expect("the subscriber connects within the deadline"); } -#[tokio::test] -async fn a_busy_snapshot_reaches_the_status_bar_as_a_busy_frame_with_the_gateway_text() { +/// Spawns a mock progress server, recording sink, and subscriber task. +async fn spawn_fixture(health: GatewayHealth) -> (Arc, StatusRecorder, Heartbeat) { let mock = Arc::new(MockProgress::new()); - let base_url = spawn_gateway(Arc::clone(&mock).router()).await; - let recorder = recorder(); - // The flag starts optimistic, so the subscriber connects at once. + let base_url = serve(Arc::clone(&mock).router()).await; + let recorder = StatusRecorder::new(); let subscriber = spawn_with_timing( binding(&base_url), recorder.push.clone(), - GatewayHealth::new(), + health, FAST_TIMING, ); + (mock, recorder, subscriber) +} + +#[tokio::test] +async fn a_busy_snapshot_reaches_the_status_bar_as_a_busy_frame_with_the_gateway_text() { + let (mock, recorder, subscriber) = spawn_fixture(GatewayHealth::new()).await; wait_for_connections(&mock, 1).await; mock.send(true, "Downloading qwen3-8b.gguf 45%"); @@ -222,19 +155,9 @@ async fn a_busy_snapshot_reaches_the_status_bar_as_a_busy_frame_with_the_gateway #[tokio::test] async fn a_malformed_snapshot_is_skipped_and_the_stream_continues() { - let mock = Arc::new(MockProgress::new()); - let base_url = spawn_gateway(Arc::clone(&mock).router()).await; - let recorder = recorder(); - let subscriber = spawn_with_timing( - binding(&base_url), - recorder.push.clone(), - GatewayHealth::new(), - FAST_TIMING, - ); + let (mock, recorder, subscriber) = spawn_fixture(GatewayHealth::new()).await; wait_for_connections(&mock, 1).await; - // One undecodable `data:` block ahead of a valid snapshot: the - // subscriber warns and continues rather than dropping the stream. mock.send_raw("{not valid json".to_owned()); mock.send(true, "Loading profile"); @@ -254,23 +177,12 @@ async fn a_malformed_snapshot_is_skipped_and_the_stream_continues() { #[tokio::test] async fn a_stream_that_ends_while_reachable_rests_the_bar_and_resubscribes_after_the_delay() { - let mock = Arc::new(MockProgress::new()); - let base_url = spawn_gateway(Arc::clone(&mock).router()).await; - let recorder = recorder(); - let subscriber = spawn_with_timing( - binding(&base_url), - recorder.push.clone(), - GatewayHealth::new(), - FAST_TIMING, - ); + let (mock, recorder, subscriber) = spawn_fixture(GatewayHealth::new()).await; wait_for_connections(&mock, 1).await; mock.send(true, "Downloading"); recorder.frames_where(|frames| frames.len() == 1).await; - // The stream ends while the gateway still reads reachable: the bar - // rests once its minimum visible time lapses, which falls inside the - // resubscribe wait, and a fresh subscription follows the delay. let closed = std::time::Instant::now(); mock.close(); let pushed = recorder.frames_where(|frames| frames.len() == 2).await; @@ -289,17 +201,9 @@ async fn a_stream_that_ends_while_reachable_rests_the_bar_and_resubscribes_after #[tokio::test] async fn an_unreachable_gateway_holds_no_subscription_and_pushes_nothing() { - let mock = Arc::new(MockProgress::new()); - let base_url = spawn_gateway(Arc::clone(&mock).router()).await; - let recorder = recorder(); let health = GatewayHealth::new(); health.publish(false); - let subscriber = spawn_with_timing( - binding(&base_url), - recorder.push.clone(), - health.clone(), - FAST_TIMING, - ); + let (mock, recorder, subscriber) = spawn_fixture(health.clone()).await; let quiet = tokio::time::timeout(Duration::from_millis(200), async { wait_for_connections(&mock, 1).await; @@ -321,16 +225,8 @@ async fn an_unreachable_gateway_holds_no_subscription_and_pushes_nothing() { #[tokio::test] async fn a_reconnect_rests_the_bar_and_resubscribes_once() { - let mock = Arc::new(MockProgress::new()); - let base_url = spawn_gateway(Arc::clone(&mock).router()).await; - let recorder = recorder(); let health = GatewayHealth::new(); - let subscriber = spawn_with_timing( - binding(&base_url), - recorder.push.clone(), - health.clone(), - FAST_TIMING, - ); + let (mock, recorder, subscriber) = spawn_fixture(health.clone()).await; wait_for_connections(&mock, 1).await; mock.send(true, "Downloading"); @@ -365,3 +261,5 @@ async fn a_reconnect_rests_the_bar_and_resubscribes_once() { mod presenter; #[path = "tests-recovery.rs"] mod recovery; +#[path = "../progress-wire-tests.rs"] +mod wire; diff --git a/crates/workshop/gateway/src/refresh.rs b/crates/workshop/gateway/src/refresh.rs index 0af53d67..5a698319 100644 --- a/crates/workshop/gateway/src/refresh.rs +++ b/crates/workshop/gateway/src/refresh.rs @@ -1,45 +1,22 @@ //! Gateway profile and model-catalog refresh after reachability. +use serde::Deserialize; +use serde::de::DeserializeOwned; +use serde_json::Value; use workshop_protocol::is_chat_capable; use workshop_registry::Push; -use crate::client::GatewayClient; +use crate::client::{GatewayClient, GatewayError, GatewayResponse}; -/// Re-fetches the gateway's model catalog and pushes it to every session. -/// -/// A failed, declined, or malformed catalog is logged and skipped rather -/// than pushed: pushing a bad snapshot would clear pickers that still hold -/// a usable list. -pub async fn refresh_catalog(client: &GatewayClient, push: &Push) -> bool { - let response = match client.list_models().await { - Ok(response) => response, - Err(error) => { - tracing::warn!(%error, "catalog refresh failed"); - return false; - } - }; - if !response.status.is_success() { - tracing::warn!(status = %response.status, "catalog refresh was declined"); - return false; - } - let body: serde_json::Value = match serde_json::from_slice(&response.body) { - Ok(body) => body, - Err(error) => { - tracing::warn!(%error, "catalog refresh was not JSON"); - return false; - } - }; - let Some(models) = body.get("data").and_then(serde_json::Value::as_array) else { - tracing::warn!("catalog refresh is missing its data array"); - return false; - }; - let selectable = models.iter().any(is_chat_capable); - push.push_models_catalog(models.clone()); - selectable +/// The decoded body of `GET /v1/models`, reduced to the catalog array. +#[derive(Deserialize)] +struct ModelCatalog { + /// Every model record the gateway advertises. + data: Vec, } /// The decoded body of `GET /admin/profiles`. -#[derive(serde::Deserialize)] +#[derive(Deserialize)] struct ProfileList { /// Every profile name the gateway can serve, in gateway order. profiles: Vec, @@ -47,12 +24,53 @@ struct ProfileList { /// The decoded body of `GET /admin/status`, reduced to the one field the /// menu needs. -#[derive(serde::Deserialize)] +#[derive(Deserialize)] struct ProfileStatus { /// The profile the gateway is serving. profile: Option, } +/// Decodes a buffered gateway JSON response, logging and returning `None` on +/// transport, non-success status, or deserialization failure. +fn fetch_json( + result: Result, + label: &str, +) -> Option { + let response = match result { + Ok(response) => response, + Err(error) => { + tracing::warn!(%error, "{label} fetch failed"); + return None; + } + }; + if !response.status.is_success() { + tracing::warn!(status = %response.status, "{label} was declined"); + return None; + } + match serde_json::from_slice(&response.body) { + Ok(body) => Some(body), + Err(error) => { + tracing::warn!(%error, "{label} was not the expected JSON"); + None + } + } +} + +/// Re-fetches the gateway's model catalog and pushes it to every session. +/// +/// A failed, declined, or malformed catalog is logged and skipped rather +/// than pushed: pushing a bad snapshot would clear pickers that still hold +/// a usable list. +pub async fn refresh_catalog(client: &GatewayClient, push: &Push) -> bool { + let Some(catalog) = fetch_json::(client.list_models().await, "catalog refresh") + else { + return false; + }; + let selectable = catalog.data.iter().any(is_chat_capable); + push.push_models_catalog(catalog.data); + selectable +} + /// Fetches the gateway's profile list and active profile and publishes /// them into the workbench snapshot. /// @@ -60,7 +78,10 @@ struct ProfileStatus { /// degrades its half to empty, as a malformed answer does, so the menu /// shows no profiles rather than stale names. pub async fn refresh_profiles(client: &GatewayClient, push: &Push) -> bool { - let (profiles, active) = tokio::join!(fetch_profile_list(client), fetch_active_profile(client)); + let (list, status) = tokio::join!(client.list_profiles(), client.profile_status()); + let profiles = fetch_json::(list, "profile list").map(|list| list.profiles); + let active = + fetch_json::(status, "profile status").and_then(|status| status.profile); let ready = profiles.as_ref().is_some_and(|profiles| { !profiles.is_empty() && active @@ -71,47 +92,3 @@ pub async fn refresh_profiles(client: &GatewayClient, push: &Push) -> bool { .set_profiles(profiles.unwrap_or_default(), active); ready } - -/// The gateway's profile names, or `None` on a failed response. -async fn fetch_profile_list(client: &GatewayClient) -> Option> { - let response = match client.list_profiles().await { - Ok(response) => response, - Err(error) => { - tracing::warn!(%error, "profile list fetch failed"); - return None; - } - }; - if !response.status.is_success() { - tracing::warn!(status = %response.status, "profile list was declined"); - return None; - } - match serde_json::from_slice::(&response.body) { - Ok(list) => Some(list.profiles), - Err(error) => { - tracing::warn!(%error, "profile list was not the expected JSON"); - None - } - } -} - -/// The active profile name, or `None` on a failed response. -async fn fetch_active_profile(client: &GatewayClient) -> Option { - let response = match client.profile_status().await { - Ok(response) => response, - Err(error) => { - tracing::warn!(%error, "profile status fetch failed"); - return None; - } - }; - if !response.status.is_success() { - tracing::warn!(status = %response.status, "profile status was declined"); - return None; - } - match serde_json::from_slice::(&response.body) { - Ok(status) => status.profile, - Err(error) => { - tracing::warn!(%error, "profile status was not the expected JSON"); - None - } - } -} diff --git a/crates/workshop/gateway/src/resolve-tests.rs b/crates/workshop/gateway/src/resolve-tests.rs index 7df81781..e8ddd1b0 100644 --- a/crates/workshop/gateway/src/resolve-tests.rs +++ b/crates/workshop/gateway/src/resolve-tests.rs @@ -1,86 +1,9 @@ //! Gateway resolution tests: discovery file versus explicit config, stale files, and probe failures. use super::*; - -use std::io::{Read, Write as _}; -use std::net::TcpListener; - use crate::discovery::GatewayDiscoveryFile; +use crate::test_support::StatusRecorder; -/// The test process's own image name, so the probe's pid and image -/// checks pass and the test reaches the liveness probes. -fn own_image_name() -> String { - std::env::current_exe() - .expect("current exe") - .file_name() - .expect("the exe has a file name") - .to_string_lossy() - .into_owned() -} - -/// A probe running the real liveness gauntlet against the test -/// binary's own image. -fn probe_own_image(run_dir: &Path) -> Result { - crate::discovery::resolve_for_test(run_dir, &own_image_name()) -} - -/// A gateway discovery file pointing at the test process itself. -fn live_file(port: u16, api_key: &str) -> GatewayDiscoveryFile { - GatewayDiscoveryFile { - port, - api_key: api_key.to_owned(), - pid: std::process::id(), - epoch: 1_757_000_000, - version: "0.2.0".to_owned(), - started_at: "2026-09-03T12:00:00Z".to_owned(), - } -} - -/// A pid guaranteed dead: a short-lived child, reaped and dropped so -/// no handle keeps the process object alive. -fn dead_pid() -> u32 { - let mut child = std::process::Command::new(std::env::current_exe().expect("current exe")) - .arg("--list") - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - .expect("spawn a short-lived child"); - let pid = child.id(); - child.wait().expect("the child exits"); - drop(child); - pid -} - -/// A fixture gateway: answers `GET /health` with 200 and the key -/// probe with 200 only when the bearer matches `expected_key`. -fn fixture_gateway(expected_key: &'static str) -> u16 { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); - let port = listener.local_addr().expect("fixture address").port(); - std::thread::spawn(move || { - while let Ok((mut stream, _)) = listener.accept() { - for _ in 0..2 { - let mut buffer = [0u8; 1024]; - let Ok(read) = stream.read(&mut buffer) else { - break; - }; - let request = String::from_utf8_lossy(&buffer[..read]); - let accepted = request.starts_with("GET /health ") - || request.contains(&format!("Authorization: Bearer {expected_key}\r\n")); - let response = if accepted { - &b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"[..] - } else { - &b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"[..] - }; - if stream.write_all(response).is_err() { - break; - } - } - } - }); - port -} - -/// An explicit gateway config: a LAN URL, never the built-in default. fn explicit_config() -> GatewayConfig { GatewayConfig { base_url: "http://gateway.lan:9999".to_owned(), @@ -88,6 +11,18 @@ fn explicit_config() -> GatewayConfig { } } +fn empty_config() -> GatewayConfig { + GatewayConfig { + base_url: String::new(), + api_key: String::new(), + } +} + +fn probe_read_failure(run_dir: &Path) -> Result { + std::fs::create_dir(run_dir.join("gateway.json")).expect("plant unreadable directory"); + crate::discovery::resolve(run_dir) +} + #[test] fn a_live_gateway_discovery_file_wins_over_explicit_config() { let dir = tempfile::TempDir::new().expect("tempdir"); @@ -98,235 +33,183 @@ fn a_live_gateway_discovery_file_wins_over_explicit_config() { .write_to(dir.path()) .expect("write"); - let resolved = - resolve_with(Some(dir.path()), &explicit_config(), probe).expect("a live file resolves"); - assert_eq!(resolved.source(), GatewaySource::GatewayDiscoveryFile); + let resolved = resolve_with( + Some(dir.path()), + &explicit_config(), + crate::discovery::resolve, + ) + .expect("a live file resolves"); + assert_eq!(resolved.source, GatewaySource::GatewayDiscoveryFile); assert_eq!(resolved.base_url(), format!("http://127.0.0.1:{port}")); assert_eq!(resolved.api_key(), "file-key"); assert_eq!( resolved.identity().map(ValidatedConnection::port), - Some(port), - "the winning sidecar retains its validated identity for the initial snapshot" + Some(port) ); assert_eq!(resolved.stale(), None); } #[test] -fn a_stale_file_is_cleaned_and_explicit_config_wins() { +fn a_real_stale_file_is_cleaned_and_explicit_config_wins() { let dir = tempfile::TempDir::new().expect("tempdir"); - let file = GatewayDiscoveryFile { - pid: dead_pid(), - ..live_file(1, "k") - }; - file.write_to(dir.path()).expect("write"); - - let resolved = resolve_with(Some(dir.path()), &explicit_config(), probe_own_image) - .expect("explicit config is the fallback"); - assert_eq!(resolved.source(), GatewaySource::Config); + GatewayDiscoveryFile { + port: 1, + api_key: "k".to_owned(), + pid: std::process::id(), + epoch: 1_757_000_000, + version: "0.2.0".to_owned(), + started_at: "2026-09-03T12:00:00Z".to_owned(), + } + .write_to(dir.path()) + .expect("write"); + + let resolved = resolve_with( + Some(dir.path()), + &explicit_config(), + crate::discovery::resolve, + ) + .expect("explicit config is the fallback"); + assert_eq!(resolved.source, GatewaySource::Config); assert_eq!(resolved.base_url(), "http://gateway.lan:9999"); assert_eq!(resolved.api_key(), "config-key"); - assert_eq!(resolved.stale(), Some(StaleReason::ProcessDead)); - assert!( - !crate::discovery::gateway_discovery_file_path(dir.path()).exists(), - "the stale file was removed" - ); -} - -#[test] -fn a_wrong_key_is_reported_distinctly_from_a_dead_pid() { - // Wrong key: the pid, image, and health checks pass; the key - // probe rejects. - let dir = tempfile::TempDir::new().expect("tempdir"); - let port = fixture_gateway("right"); - live_file(port, "wrong") - .write_to(dir.path()) - .expect("write"); - let resolved = resolve_with(Some(dir.path()), &explicit_config(), probe_own_image) - .expect("explicit config is the fallback"); - assert_eq!(resolved.stale(), Some(StaleReason::KeyRejected)); - - // Dead pid: the process check fails before any probe runs. - let dir = tempfile::TempDir::new().expect("tempdir"); - let file = GatewayDiscoveryFile { - pid: dead_pid(), - ..live_file(1, "k") - }; - file.write_to(dir.path()).expect("write"); - let resolved = resolve_with(Some(dir.path()), &explicit_config(), probe_own_image) - .expect("explicit config is the fallback"); - assert_eq!(resolved.stale(), Some(StaleReason::ProcessDead)); + assert_eq!(resolved.stale(), Some(StaleReason::ImageMismatch)); + assert!(!crate::discovery::gateway_discovery_file_path(dir.path()).exists()); } #[test] -fn no_file_and_no_explicit_config_is_the_plain_error() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let config = GatewayConfig { - base_url: String::new(), - api_key: String::new(), - }; - let error = resolve_with(Some(dir.path()), &config, probe_own_image) - .expect_err("an empty base_url is not explicit config"); - assert!( - error - .to_string() - .contains("no gateway configured or running"), - "the error says it plainly: {error}" +fn fallback_and_error_resolution_cover_all_stale_absent_io_and_no_run_dir_cases() { + use StaleReason as S; + + type ProbeFn = fn(&Path) -> Result; + type Case = ( + &'static str, + bool, + ProbeFn, + Option, + Option<&'static str>, ); - assert_eq!(error.stale(), None, "no file existed to remove"); -} + const CASES: &[Case] = &[ + ("absent file", true, |_| Ok(Resolution::Absent), None, None), + ("no run_dir", false, crate::discovery::resolve, None, None), + ("probe I/O error", true, probe_read_failure, None, None), + ( + "stale invalid", + true, + |_| Ok(Resolution::Stale(S::Invalid)), + Some(S::Invalid), + Some("not valid"), + ), + ( + "stale dead pid", + true, + |_| Ok(Resolution::Stale(S::ProcessDead)), + Some(S::ProcessDead), + Some("process is dead"), + ), + ( + "stale image", + true, + |_| Ok(Resolution::Stale(S::ImageMismatch)), + Some(S::ImageMismatch), + Some("another program"), + ), + ( + "stale health", + true, + |_| Ok(Resolution::Stale(S::HealthFailed)), + Some(S::HealthFailed), + Some("does not answer"), + ), + ( + "stale key", + true, + |_| Ok(Resolution::Stale(S::KeyRejected)), + Some(S::KeyRejected), + Some("key was rejected"), + ), + ]; + + for &(label, with_run_dir, probe, expected_stale, expected_clause) in CASES { + let dir = tempfile::TempDir::new().expect("tempdir"); + let resolved = resolve_with( + with_run_dir.then_some(dir.path()), + &explicit_config(), + probe, + ) + .unwrap_or_else(|error| panic!("{label}: config fallback failed: {error}")); + assert_eq!(resolved.source, GatewaySource::Config, "{label}"); + assert_eq!(resolved.base_url(), "http://gateway.lan:9999", "{label}"); + assert_eq!(resolved.api_key(), "config-key", "{label}"); + assert_eq!(resolved.stale(), expected_stale, "{label}"); + + let dir = tempfile::TempDir::new().expect("tempdir"); + let error = resolve_with(with_run_dir.then_some(dir.path()), &empty_config(), probe) + .expect_err("no explicit config remains"); + assert_eq!(error.stale(), expected_stale, "{label}"); + let message = error.to_string(); + assert!( + message.contains("no gateway configured or running"), + "{label}: {message}" + ); + if let Some(clause) = expected_clause { + assert!( + message.contains(clause), + "{label}: missing `{clause}` in `{message}`" + ); + } + } -#[test] -fn an_explicitly_configured_default_url_is_honored() { - // The well-known default URL written by hand is explicit config: - // it names a gateway discovery cannot see (an SSH-tunneled remote, - // a gateway whose discovery-file write failed), so it must - // resolve, not read as an unset value. let dir = tempfile::TempDir::new().expect("tempdir"); - let config = GatewayConfig { + let default_cfg = GatewayConfig { base_url: "http://127.0.0.1:8081".to_owned(), api_key: "config-key".to_owned(), }; - let resolved = resolve_with(Some(dir.path()), &config, probe_own_image) - .expect("an explicitly configured URL resolves"); - assert_eq!(resolved.source(), GatewaySource::Config); + let resolved = resolve_with(Some(dir.path()), &default_cfg, |_| Ok(Resolution::Absent)) + .expect("explicitly configured default URL resolves"); + assert_eq!(resolved.source, GatewaySource::Config); assert_eq!(resolved.base_url(), "http://127.0.0.1:8081"); assert_eq!(resolved.api_key(), "config-key"); } #[test] -fn a_stale_file_with_no_explicit_config_names_the_reason_in_the_error() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let port = fixture_gateway("right"); - live_file(port, "wrong") - .write_to(dir.path()) - .expect("write"); - let config = GatewayConfig { - base_url: String::new(), - api_key: String::new(), - }; - let error = resolve_with(Some(dir.path()), &config, probe_own_image) - .expect_err("no explicit config remains"); - assert_eq!(error.stale(), Some(StaleReason::KeyRejected)); - let message = error.to_string(); - assert!( - message.contains("no gateway configured or running"), - "the error says it plainly: {message}" - ); - assert!( - message.contains("key was rejected"), - "the removed file's reason is named: {message}" - ); -} +fn report_announces_source_and_optional_stale_reason() { + let mut recorder = StatusRecorder::new(); -#[test] -fn no_file_and_explicit_config_uses_the_config() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let resolved = resolve_with(Some(dir.path()), &explicit_config(), probe_own_image) - .expect("explicit config resolves"); - assert_eq!(resolved.source(), GatewaySource::Config); - assert_eq!(resolved.stale(), None); -} - -/// A probe whose discovery-file read fails: a directory sits where -/// `gateway.json` belongs, so the read errors instead of answering. -fn probe_read_failure(run_dir: &Path) -> Result { - std::fs::create_dir(run_dir.join("gateway.json")).expect("the unreadable file plants"); - crate::discovery::resolve_for_test(run_dir, &own_image_name()) -} - -#[test] -fn a_probe_io_failure_degrades_to_the_config_fallback() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let resolved = resolve_with(Some(dir.path()), &explicit_config(), probe_read_failure) - .expect("a probe failure never fails startup on its own"); - assert_eq!(resolved.source(), GatewaySource::Config); - assert_eq!(resolved.base_url(), "http://gateway.lan:9999"); - assert_eq!(resolved.stale(), None, "nothing was removed"); -} - -#[test] -fn a_probe_io_failure_with_no_explicit_config_is_the_plain_error() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let config = GatewayConfig { - base_url: String::new(), - api_key: String::new(), - }; - let error = resolve_with(Some(dir.path()), &config, probe_read_failure) - .expect_err("no explicit config remains after a probe failure"); - assert!( - error - .to_string() - .contains("no gateway configured or running"), - "the error says it plainly: {error}" - ); - assert_eq!( - error.stale(), - None, - "a probe failure does not remove the file" - ); -} - -#[test] -fn no_run_directory_skips_discovery() { - // The production probe stands in: with no run directory it is - // never called, so resolution is the config fallback or the plain - // error, and the real run directory is never consulted. - let resolved = resolve_with(None, &explicit_config(), probe) - .expect("explicit config resolves without a run directory"); - assert_eq!(resolved.source(), GatewaySource::Config); - assert_eq!(resolved.stale(), None); - - let config = GatewayConfig { - base_url: String::new(), - api_key: String::new(), - }; - let error = resolve_with(None, &config, probe) - .expect_err("no run directory and no explicit config is the plain error"); - assert!( - error - .to_string() - .contains("no gateway configured or running"), - "the error says it plainly: {error}" - ); -} - -#[test] -fn the_report_names_the_winning_source_and_a_removed_file() { - // A recording status sink stands in for the status bus: the report's - // frames land on it through the registry's push facade. - let registry = workshop_registry::Registry::new(); - let (status_tx, mut receiver) = tokio::sync::broadcast::channel(16); - let _sink = registry.register_sink::(std::sync::Arc::new( - workshop_registry::StatusSinkAdapter::new(move |update| { - let _ = status_tx.send(update); - }), - )); - let push = registry.push(); - - let resolved = ResolvedGateway { + let with_stale = ResolvedGateway { base_url: "http://127.0.0.1:4000".to_owned(), api_key: "k".to_owned(), identity: None, source: GatewaySource::Config, stale: Some(StaleReason::KeyRejected), }; - report(&resolved, &push); + report(&with_stale, &recorder.push); - let stale_frame = receiver.try_recv().expect("the stale note is reported"); + let stale_frame = recorder.try_recv().expect("stale note reported"); assert_eq!(stale_frame.label, "Stale gateway discovery file"); + assert!(stale_frame.description.contains("key was rejected")); + let connecting = recorder.try_recv().expect("winning source reported"); + assert_eq!(connecting.label, "Connecting to gateway"); assert!( - stale_frame.description.contains("key was rejected"), - "the stale reason is named: {}", - stale_frame.description + connecting.description.contains("http://127.0.0.1:4000") + && connecting.description.contains("workshop.toml") ); - let connecting = receiver.try_recv().expect("the winning source is reported"); + + let discovery_win = ResolvedGateway { + base_url: "http://127.0.0.1:4001".to_owned(), + api_key: "k".to_owned(), + identity: None, + source: GatewaySource::GatewayDiscoveryFile, + stale: None, + }; + report(&discovery_win, &recorder.push); + + let connecting = recorder.try_recv().expect("connecting frame reported"); assert_eq!(connecting.label, "Connecting to gateway"); assert!( - connecting.description.contains("http://127.0.0.1:4000") - && connecting.description.contains("workshop.toml"), - "the endpoint and its source are named: {}", - connecting.description + connecting.description.contains("http://127.0.0.1:4001") + && connecting.description.contains("gateway discovery file") ); + assert!(recorder.try_recv().is_err(), "no stale frame emitted"); } #[test] @@ -338,6 +221,5 @@ fn debug_redacts_the_api_key() { source: GatewaySource::Config, stale: None, }; - let rendered = format!("{resolved:?}"); - assert!(!rendered.contains("secret-key"), "key leaked: {rendered}"); + assert!(!format!("{resolved:?}").contains("secret-key")); } diff --git a/crates/workshop/gateway/src/resolve.rs b/crates/workshop/gateway/src/resolve.rs index ca2ca4d0..db0a72c6 100644 --- a/crates/workshop/gateway/src/resolve.rs +++ b/crates/workshop/gateway/src/resolve.rs @@ -12,12 +12,12 @@ use std::fmt; use std::path::Path; -use crate::discovery::{Resolution, SidecarError, StaleReason, ValidatedConnection}; - use workshop_protocol::Activity; use workshop_registry::Push; use workshop_support::GatewayConfig; +use crate::discovery::{self, Resolution, SidecarError, StaleReason, ValidatedConnection}; + /// The gateway endpoint state construction connects to, and how it was /// found. #[derive(Clone, PartialEq, Eq)] @@ -31,7 +31,7 @@ pub struct ResolvedGateway { // Manual so the bearer key is never written to logs. impl fmt::Debug for ResolvedGateway { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ResolvedGateway") .field("base_url", &self.base_url) .field("api_key", &"") @@ -112,13 +112,6 @@ impl ResolvedGateway { self.identity.as_ref() } - /// Which source won the resolution. - #[cfg(test)] - #[must_use] - fn source(&self) -> GatewaySource { - self.source - } - /// Why a gateway discovery file was removed on the way to the config /// fallback, when one was. #[must_use] @@ -151,20 +144,15 @@ impl ResolveError { /// The failure with the stale-file note rendered in, when a file was /// removed on the way. fn new(stale: Option) -> Self { - let note = stale - .map(|reason| { - format!( - " (removed a stale gateway discovery file: {})", - stale_clause(reason) - ) - }) - .unwrap_or_default(); - Self { - detail: format!( - "{note}; start runvil-gateway or set [gateway] base_url and api_key in workshop.toml" + let detail = match stale { + Some(reason) => format!( + " (removed a stale gateway discovery file: {}); start runvil-gateway or set [gateway] base_url and api_key in workshop.toml", + stale_clause(reason) ), - stale, - } + None => "; start runvil-gateway or set [gateway] base_url and api_key in workshop.toml" + .to_owned(), + }; + Self { detail, stale } } /// Why the gateway discovery file was removed, when one was: a wrong key, @@ -185,17 +173,12 @@ impl ResolveError { /// config names no explicit gateway. pub fn resolve(config: &GatewayConfig) -> Result { resolve_with( - crate::discovery::default_run_dir().as_deref(), + discovery::default_run_dir().as_deref(), config, - probe, + discovery::resolve, ) } -/// The production probe: the fork's stale-detecting resolve. -fn probe(run_dir: &Path) -> Result { - crate::discovery::resolve(run_dir) -} - /// `resolve` against an explicit run directory and probe, so tests point /// at a tempdir and at a probe that accepts the test binary's own image. fn resolve_with( @@ -206,7 +189,7 @@ fn resolve_with( let mut stale = None; if let Some(run_dir) = run_dir { match probe(run_dir) { - Ok(Resolution::Attach(file)) => match validate_resolved(file) { + Ok(Resolution::Attach(file)) => match ValidatedConnection::validate(file) { Ok(identity) => { return Ok(ResolvedGateway { base_url: format!("http://127.0.0.1:{}", identity.port()), @@ -234,7 +217,7 @@ fn resolve_with( _ => {} } } - if is_explicit(config) { + if !config.base_url.is_empty() { return Ok(ResolvedGateway { base_url: config.base_url.clone(), api_key: config.api_key.clone(), @@ -246,14 +229,6 @@ fn resolve_with( Err(ResolveError::new(stale)) } -/// Reifies the shared resolver's live result as the capability stored in -/// the workshop's immutable gateway snapshot. -fn validate_resolved( - file: crate::discovery::GatewayDiscoveryFile, -) -> Result { - ValidatedConnection::validate(file) -} - /// Reports the resolution outcome where the server surfaces startup state: /// a removed file's reason and the winning source on the status bus, /// the same facts in the log. @@ -281,15 +256,6 @@ pub fn report(gateway: &ResolvedGateway, push: &Push) { ); } -/// Whether the config names a gateway itself: a non-empty `base_url` is -/// explicit, an empty one (unset, or an unset `${RUNVIL_GATEWAY_URL}` -/// interpolation) is not. The explicit fallback exists for the gateways -/// discovery cannot see - a LAN gateway; a local gateway writes a -/// gateway discovery file, which discovery finds first. -fn is_explicit(config: &GatewayConfig) -> bool { - !config.base_url.is_empty() -} - /// Renders a stale reason as a user-facing clause: a wrong key, a dead /// pid, and a foreign image are different problems for the operator. fn stale_clause(reason: StaleReason) -> &'static str { diff --git a/crates/workshop/gateway/src/test_gateway-process.rs b/crates/workshop/gateway/src/test_gateway-process.rs index bba435cd..0d409d78 100644 --- a/crates/workshop/gateway/src/test_gateway-process.rs +++ b/crates/workshop/gateway/src/test_gateway-process.rs @@ -1,9 +1,13 @@ //! Child-process protocol for the named local gateway fixture. +use std::env; use std::io::{Read as _, Write as _}; use std::net::{TcpListener, TcpStream}; +use std::path::Path; +use std::thread; use super::{CONTROL_ADDRESS_ENV, EXPECTED_KEY_ENV, INSTANCE_LEASE_RUN_DIR_ENV}; +use crate::discovery::GatewayInstanceLease; /// Serves health, bearer, and shutdown requests inside the named child. #[expect( @@ -11,16 +15,16 @@ use super::{CONTROL_ADDRESS_ENV, EXPECTED_KEY_ENV, INSTANCE_LEASE_RUN_DIR_ENV}; reason = "the isolated fixture process fails immediately with the failed invariant" )] pub(super) fn run() { - let Ok(control_address) = std::env::var(CONTROL_ADDRESS_ENV) else { + let Ok(control_address) = env::var(CONTROL_ADDRESS_ENV) else { return; }; - let _instance_lease = std::env::var_os(INSTANCE_LEASE_RUN_DIR_ENV).map(|run_dir| { - crate::discovery::GatewayInstanceLease::try_acquire(std::path::Path::new(&run_dir)) + let _instance_lease = env::var_os(INSTANCE_LEASE_RUN_DIR_ENV).map(|run_dir| { + GatewayInstanceLease::try_acquire(Path::new(&run_dir)) .expect("acquire named fixture process lease") .expect("the named fixture is the process lease owner") }); let expected_key = - std::env::var(EXPECTED_KEY_ENV).expect("the fixture child receives an expected key"); + env::var(EXPECTED_KEY_ENV).expect("the fixture child receives an expected key"); let listener = TcpListener::bind("127.0.0.1:0").expect("bind named fixture Gateway"); let port = listener .local_addr() @@ -37,7 +41,7 @@ pub(super) fn run() { let mut connection_control = control .try_clone() .expect("clone the fixture control connection"); - std::thread::spawn(move || { + thread::spawn(move || { while let Some(shutdown) = answer_request(&mut stream, expected_key.as_bytes()) { if shutdown { connection_control @@ -87,41 +91,48 @@ fn has_bearer(request: &[u8], expected_key: &[u8]) -> bool { }) } -#[test] -fn bearer_credentials_are_byte_exact_and_case_sensitive() { - let expected = b"CaseSensitive-Key"; - assert!(has_bearer( - b"GET / HTTP/1.1\r\naUtHoRiZaTiOn: bEaReR CaseSensitive-Key\r\n\r\n", - expected - )); +#[cfg(test)] +mod tests { + use std::net::Shutdown; - let listener = TcpListener::bind("127.0.0.1:0").expect("bind credential regression"); - let address = listener.local_addr().expect("read regression address"); - let client = std::thread::spawn(move || { - let mut stream = TcpStream::connect(address).expect("connect credential regression"); - stream - .write_all( - b"GET /protected HTTP/1.1\r\nAuthorization: Bearer casesensitive-key\r\n\r\n", - ) - .expect("send wrong-case credential"); - stream - .shutdown(std::net::Shutdown::Write) - .expect("finish fixture request"); - let mut response = String::new(); - stream - .read_to_string(&mut response) - .expect("read fixture response"); - response - }); - let (mut server, _) = listener.accept().expect("accept credential regression"); - assert!( - !answer_request(&mut server, expected).expect("the fixture answers the request"), - "an unauthorized request cannot report shutdown" - ); - drop(server); - let response = client.join().expect("credential regression client joins"); - assert!( - response.starts_with("HTTP/1.1 401 Unauthorized"), - "the shared fixture rejects a bearer that differs only by case: {response}" - ); + use super::*; + + #[test] + fn bearer_credentials_are_byte_exact_and_case_sensitive() { + let expected = b"CaseSensitive-Key"; + assert!(has_bearer( + b"GET / HTTP/1.1\r\naUtHoRiZaTiOn: bEaReR CaseSensitive-Key\r\n\r\n", + expected + )); + + let listener = TcpListener::bind("127.0.0.1:0").expect("bind credential regression"); + let address = listener.local_addr().expect("read regression address"); + let client = thread::spawn(move || { + let mut stream = TcpStream::connect(address).expect("connect credential regression"); + stream + .write_all( + b"GET /protected HTTP/1.1\r\nAuthorization: Bearer casesensitive-key\r\n\r\n", + ) + .expect("send wrong-case credential"); + stream + .shutdown(Shutdown::Write) + .expect("finish fixture request"); + let mut response = String::new(); + stream + .read_to_string(&mut response) + .expect("read fixture response"); + response + }); + let (mut server, _) = listener.accept().expect("accept credential regression"); + assert!( + !answer_request(&mut server, expected).expect("the fixture answers the request"), + "an unauthorized request cannot report shutdown" + ); + drop(server); + let response = client.join().expect("credential regression client joins"); + assert!( + response.starts_with("HTTP/1.1 401 Unauthorized"), + "the shared fixture rejects a bearer that differs only by case: {response}" + ); + } } diff --git a/crates/workshop/gateway/src/test_gateway.rs b/crates/workshop/gateway/src/test_gateway.rs index f8a72091..af679417 100644 --- a/crates/workshop/gateway/src/test_gateway.rs +++ b/crates/workshop/gateway/src/test_gateway.rs @@ -1,12 +1,17 @@ -//! Gateway test fixtures: the named local gateway process shared by -//! capability and supervision tests, and a stalled TCP stub for the -//! timeout tests. +//! Gateway test fixture: the named local gateway process shared by +//! capability and supervision tests. -use std::io::Read; +use std::env; +use std::fs; +use std::io::{ErrorKind, Read}; use std::net::{TcpListener, TcpStream}; +use std::path::Path; use std::process::{Child, Command, Stdio}; +use std::thread; use std::time::{Duration, Instant}; +use tempfile::TempDir; + use crate::discovery::{GatewayDiscoveryFile, ValidatedConnection}; #[path = "test_gateway-process.rs"] @@ -27,28 +32,10 @@ pub struct ValidatedGateway { child: Child, port: u16, control: TcpStream, - _directory: tempfile::TempDir, + _directory: TempDir, } impl ValidatedGateway { - #[cfg(test)] - pub(crate) fn spawn(expected_key: &str) -> Self { - Self::spawn_in_with_lease( - expected_key, - "test_gateway::validated_gateway_fixture_process", - None, - ) - } - - #[cfg(test)] - fn spawn_with_instance_lease(expected_key: &str, run_dir: &std::path::Path) -> Self { - Self::spawn_in_with_lease( - expected_key, - "test_gateway::validated_gateway_fixture_process", - Some(run_dir), - ) - } - /// Starts the fixture in the current test binary through `fixture_test`. /// /// The named ignored test must call @@ -69,16 +56,16 @@ impl ValidatedGateway { fn spawn_in_with_lease( expected_key: &str, fixture_test: &str, - lease_run_dir: Option<&std::path::Path>, + lease_run_dir: Option<&Path>, ) -> Self { let control = TcpListener::bind("127.0.0.1:0").expect("bind fixture control"); control .set_nonblocking(true) .expect("make fixture control nonblocking"); - let directory = tempfile::TempDir::new().expect("create fixture executable directory"); + let directory = TempDir::new().expect("create fixture executable directory"); let executable = directory.path().join(GATEWAY_EXE_NAME); - std::fs::copy( - std::env::current_exe().expect("locate test executable"), + fs::copy( + env::current_exe().expect("locate test executable"), &executable, ) .expect("copy test executable under the Gateway image name"); @@ -106,7 +93,7 @@ impl ValidatedGateway { let mut stream = loop { match control.accept() { Ok((stream, _)) => break stream, - Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + Err(error) if error.kind() == ErrorKind::WouldBlock => { assert!( child.try_wait().expect("observe fixture process").is_none(), "the named Gateway fixture exited before becoming ready" @@ -115,7 +102,7 @@ impl ValidatedGateway { Instant::now() < deadline, "the named Gateway fixture did not become ready" ); - std::thread::sleep(Duration::from_millis(10)); + thread::sleep(Duration::from_millis(10)); } Err(error) => panic!("accept fixture control connection: {error}"), } @@ -193,45 +180,12 @@ impl ValidatedGateway { assert_eq!(marker, [1], "the fixture reports only shutdown requests"); true } - Err(error) - if matches!( - error.kind(), - std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut - ) => - { + Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { false } Err(error) => panic!("read fixture shutdown marker: {error}"), } } - - #[cfg(test)] - fn terminate_within(&mut self, timeout: Duration) { - if self - .child - .try_wait() - .expect("observe named Gateway fixture") - .is_none() - { - let _ = self.child.kill(); - } - let deadline = Instant::now() + timeout; - loop { - if self - .child - .try_wait() - .expect("observe named Gateway fixture") - .is_some() - { - return; - } - assert!( - Instant::now() < deadline, - "the named Gateway fixture did not stop within {timeout:?}" - ); - std::thread::sleep(Duration::from_millis(10)); - } - } } impl Drop for ValidatedGateway { @@ -241,95 +195,121 @@ impl Drop for ValidatedGateway { } let deadline = Instant::now() + Duration::from_secs(5); while self.child.try_wait().ok().flatten().is_none() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); + thread::sleep(Duration::from_millis(10)); } } } -/// Binds a loopback stub that completes TCP handshakes and never answers, -/// modeling a gateway that is up but wedged. Returns its base URL and a -/// handle notified as the stub takes each connection. -#[cfg(test)] -pub(crate) async fn stalled_gateway() -> (String, std::sync::Arc) { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind stalled stub"); - let addr = listener.local_addr().expect("stalled stub address"); - let accepted = std::sync::Arc::new(tokio::sync::Notify::new()); - let notify = std::sync::Arc::clone(&accepted); - tokio::spawn(async move { - // Sockets are held open and never answered until the test's - // runtime tears the task down. - let mut held = Vec::new(); - while let Ok((socket, _)) = listener.accept().await { - held.push(socket); - notify.notify_one(); - } - }); - (format!("http://{addr}"), accepted) +/// Runs the child half of [`ValidatedGateway`] inside an ignored test. +/// +/// This function never returns during a successful fixture run. +/// +/// # Panics +/// Panics when required fixture environment, listener, control connection, +/// request acceptance, or shutdown reporting cannot be established. +pub fn run_validated_gateway_fixture_process() { + process::run(); } #[cfg(test)] -#[test] -#[ignore = "runs only as a named child process"] -fn validated_gateway_fixture_process() { - run_validated_gateway_fixture_process(); -} +mod tests { + use super::*; + use crate::discovery::{GatewayInstanceLease, request_shutdown}; -#[cfg(test)] -#[test] -fn received_shutdown_waits_for_a_delayed_marker() { - let mut gateway = ValidatedGateway::spawn("fixture-key"); - let validated = gateway.validate("fixture-key", 1_778_000_001, "2026-09-07T18:00:01Z"); - let delay = Duration::from_millis(100); - let started = Instant::now(); + impl ValidatedGateway { + pub(crate) fn spawn(expected_key: &str) -> Self { + Self::spawn_in_with_lease( + expected_key, + "test_gateway::tests::validated_gateway_fixture_process", + None, + ) + } + + fn spawn_with_instance_lease(expected_key: &str, run_dir: &Path) -> Self { + Self::spawn_in_with_lease( + expected_key, + "test_gateway::tests::validated_gateway_fixture_process", + Some(run_dir), + ) + } - std::thread::scope(|scope| { - scope.spawn(move || { - std::thread::sleep(delay); - crate::discovery::request_shutdown(&validated) - .expect("the delayed authenticated shutdown is accepted"); + fn terminate_within(&mut self, timeout: Duration) { + if self + .child + .try_wait() + .expect("observe named Gateway fixture") + .is_none() + { + let _ = self.child.kill(); + } + let deadline = Instant::now() + timeout; + loop { + if self + .child + .try_wait() + .expect("observe named Gateway fixture") + .is_some() + { + return; + } + assert!( + Instant::now() < deadline, + "the named Gateway fixture did not stop within {timeout:?}" + ); + thread::sleep(Duration::from_millis(10)); + } + } + } + + #[test] + #[ignore = "runs only as a named child process"] + fn validated_gateway_fixture_process() { + run_validated_gateway_fixture_process(); + } + + #[test] + fn received_shutdown_waits_for_a_delayed_marker() { + let mut gateway = ValidatedGateway::spawn("fixture-key"); + let validated = gateway.validate("fixture-key", 1_778_000_001, "2026-09-07T18:00:01Z"); + let delay = Duration::from_millis(100); + let started = Instant::now(); + + thread::scope(|scope| { + scope.spawn(move || { + thread::sleep(delay); + request_shutdown(&validated) + .expect("the delayed authenticated shutdown is accepted"); + }); + assert!( + gateway.received_shutdown(Duration::from_secs(2)), + "the control stream waits for the delayed shutdown marker" + ); }); + assert!( - gateway.received_shutdown(Duration::from_secs(2)), - "the control stream waits for the delayed shutdown marker" + started.elapsed() >= delay, + "the delayed marker cannot be reported before it is sent" ); - }); - - assert!( - started.elapsed() >= delay, - "the delayed marker cannot be reported before it is sent" - ); -} - -#[cfg(test)] -#[test] -fn a_named_fixture_releases_its_process_lease_when_terminated() { - let run_dir = tempfile::TempDir::new().expect("create lease run directory"); - let mut gateway = ValidatedGateway::spawn_with_instance_lease("fixture-key", run_dir.path()); - assert!( - crate::discovery::GatewayInstanceLease::try_acquire(run_dir.path()) - .expect("contend for the named fixture lease") - .is_none(), - "the live fixture owns the process lease" - ); + } - gateway.terminate_within(Duration::from_secs(5)); - assert!( - crate::discovery::GatewayInstanceLease::try_acquire(run_dir.path()) - .expect("recover the named fixture lease") - .is_some(), - "the operating system releases the lease when the named fixture dies" - ); -} + #[test] + fn a_named_fixture_releases_its_process_lease_when_terminated() { + let run_dir = TempDir::new().expect("create lease run directory"); + let mut gateway = + ValidatedGateway::spawn_with_instance_lease("fixture-key", run_dir.path()); + assert!( + GatewayInstanceLease::try_acquire(run_dir.path()) + .expect("contend for the named fixture lease") + .is_none(), + "the live fixture owns the process lease" + ); -/// Runs the child half of [`ValidatedGateway`] inside an ignored test. -/// -/// This function never returns during a successful fixture run. -/// -/// # Panics -/// Panics when required fixture environment, listener, control connection, -/// request acceptance, or shutdown reporting cannot be established. -pub fn run_validated_gateway_fixture_process() { - process::run(); + gateway.terminate_within(Duration::from_secs(5)); + assert!( + GatewayInstanceLease::try_acquire(run_dir.path()) + .expect("recover the named fixture lease") + .is_some(), + "the operating system releases the lease when the named fixture dies" + ); + } } diff --git a/crates/workshop/gateway/src/test_support.rs b/crates/workshop/gateway/src/test_support.rs new file mode 100644 index 00000000..b3ddd91f --- /dev/null +++ b/crates/workshop/gateway/src/test_support.rs @@ -0,0 +1,114 @@ +#![cfg(test)] +//! Shared test fixtures for `workshop-gateway` unit tests. + +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use tokio::net::TcpListener; +use tokio::sync::{Notify, broadcast}; +use workshop_protocol::StatusBarUpdate; +use workshop_registry::{Push, Registration, Registry, StatusSink, StatusSinkAdapter}; + +/// Binds `app` on a free loopback port and returns its base URL. +pub(crate) async fn serve(app: axum::Router) -> String { + let (addr, _handle) = workshop_support::fixtures::serve(app).await; + format!("http://{addr}") +} + +/// Binds a loopback stub that completes TCP handshakes and never answers, +/// modeling a gateway that is up but wedged. Returns its base URL and a +/// handle notified as the stub takes each connection. +pub(crate) async fn stalled_gateway() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind stalled stub"); + let addr = listener.local_addr().expect("stalled stub address"); + let accepted = Arc::new(Notify::new()); + let notify = Arc::clone(&accepted); + tokio::spawn(async move { + // Sockets are held open and never answered until the test's + // runtime tears the task down. + let mut held = Vec::new(); + while let Ok((socket, _)) = listener.accept().await { + held.push(socket); + notify.notify_one(); + } + }); + (format!("http://{addr}"), accepted) +} + +/// A recording status sink behind a [`Push`]: every frame pushed lands in +/// both the broadcast receiver (for pull-based tests) and the history buffer +/// (for polling tests). +pub(crate) struct StatusRecorder { + pub(crate) push: Push, + rx: broadcast::Receiver, + frames: Arc>>, + _guard: Registration, +} + +impl StatusRecorder { + pub(crate) fn new() -> Self { + let registry = Registry::new(); + let (tx, rx) = broadcast::channel(16); + let frames: Arc>> = Arc::new(Mutex::new(Vec::new())); + let sink_frames = Arc::clone(&frames); + let guard = registry.register_sink::(Arc::new(StatusSinkAdapter::new( + move |update| { + sink_frames + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(update.clone()); + let _ = tx.send(update); + }, + ))); + Self { + push: registry.push(), + rx, + frames, + _guard: guard, + } + } + + pub(crate) fn try_recv(&mut self) -> Result { + self.rx.try_recv() + } + + /// The next status line within a generous deadline. + pub(crate) async fn next_label(&mut self) -> String { + tokio::time::timeout(Duration::from_secs(5), self.rx.recv()) + .await + .expect("a status update arrives within the deadline") + .expect("the recording sink is open") + .label + } + + /// The `(label, busy)` of every frame pushed so far. + pub(crate) fn pushed(&self) -> Vec<(String, bool)> { + self.frames + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .map(|update| (update.label.clone(), update.busy)) + .collect() + } + + /// Polls until `accept` holds over the pushed frames, within a + /// generous deadline. + pub(crate) async fn frames_where( + &self, + accept: impl Fn(&[(String, bool)]) -> bool, + ) -> Vec<(String, bool)> { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let pushed = self.pushed(); + if accept(&pushed) { + return pushed; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("matching frames arrive within the deadline") + } +} diff --git a/crates/workshop/gateway/src/version-tests.rs b/crates/workshop/gateway/src/version-tests.rs index 41a7c80d..48fd72e7 100644 --- a/crates/workshop/gateway/src/version-tests.rs +++ b/crates/workshop/gateway/src/version-tests.rs @@ -1,208 +1,161 @@ //! Unit tests for the Gateway version comparison. use super::*; +use crate::test_support::StatusRecorder; -use std::sync::Arc; - -use tokio::sync::broadcast; - -/// A recording status sink standing in for the status bus, and the push -/// facade the report writes through. -fn status_recorder() -> ( - Push, - broadcast::Receiver, - workshop_registry::Registration, -) { - let registry = workshop_registry::Registry::new(); - let (tx, rx) = broadcast::channel(16); - let sink = registry.register_sink::(Arc::new( - workshop_registry::StatusSinkAdapter::new(move |update| { - let _ = tx.send(update); - }), - )); - (registry.push(), rx, sink) -} - -#[test] -fn parses_a_plain_three_part_version() { - assert_eq!( - Version::parse("0.4.1"), - Some(Version { - major: 0, - minor: 4, - patch: 1 - }) - ); -} - -#[test] -fn parses_a_leading_v_and_a_prerelease_suffix() { - let expected = Version::parse("1.2.3"); - assert_eq!(Version::parse("v1.2.3"), expected); - assert_eq!(Version::parse("1.2.3-rc.1"), expected); - assert_eq!(Version::parse("1.2.3+build.7"), expected); -} - -#[test] -fn a_two_part_version_treats_the_missing_patch_as_zero() { - assert_eq!(Version::parse("2.5"), Version::parse("2.5.0")); +const fn ver(major: u64, minor: u64, patch: u64) -> Version { + Version { + major, + minor, + patch, + } } #[test] -fn a_version_that_is_not_numbers_is_unreadable() { - for text in ["", " ", "unknown", "1.x.0", "1.2.3.4", "-1.0.0"] { - assert_eq!(Version::parse(text), None, "{text}"); +fn version_parse_handles_valid_and_invalid_inputs() { + const CASES: &[(&str, &str, Option)] = &[ + ("plain three-part", "0.4.1", Some(ver(0, 4, 1))), + ("leading v prefix", "v1.2.3", Some(ver(1, 2, 3))), + ("prerelease suffix", "1.2.3-rc.1", Some(ver(1, 2, 3))), + ("build metadata suffix", "1.2.3+build.7", Some(ver(1, 2, 3))), + ("two-part defaults patch", "2.5", Some(ver(2, 5, 0))), + ("empty string", "", None), + ("whitespace only", " ", None), + ("non-numeric word", "unknown", None), + ("non-numeric minor", "1.x.0", None), + ("four parts rejected", "1.2.3.4", None), + ("negative major rejected", "-1.0.0", None), + ]; + + for &(label, input, expected) in CASES { + assert_eq!(Version::parse(input), expected, "{label}"); } -} -#[test] -fn versions_compare_numerically_not_as_strings() { - let older = Version::parse("0.9.0").expect("a version"); - let newer = Version::parse("0.10.0").expect("a version"); - assert!(newer > older, "0.10.0 is newer than 0.9.0"); + let older = ver(0, 9, 0); + let newer = ver(0, 10, 0); + assert!(newer > older); assert!(newer.is_at_least(older)); assert!(!older.is_at_least(newer)); assert_eq!(older.to_string(), "0.9.0"); } #[test] -fn an_equal_version_satisfies_the_minimum() { - assert_eq!( - VersionCheck::compare("0.4.0", "0.4.0"), - VersionCheck::Satisfied { - running: Version::parse("0.4.0").expect("a version"), - minimum: Version::parse("0.4.0").expect("a version"), - } - ); -} - -#[test] -fn an_older_gateway_is_reported_too_old() { - let check = VersionCheck::compare("0.3.9", "0.4.0"); - assert!(matches!(check, VersionCheck::TooOld { .. }), "{check:?}"); - assert!(check.is_problem()); -} - -#[test] -fn a_newer_gateway_satisfies_the_minimum() { - assert!(!VersionCheck::compare("2.0.0", "0.4.0").is_problem()); -} - -#[test] -fn an_empty_minimum_means_the_pin_recorded_none() { - let check = VersionCheck::compare("0.1.0", ""); - assert_eq!(check, VersionCheck::NoMinimumRecorded); - assert!( - !check.is_problem(), - "a placeholder pin must not warn about every Gateway" - ); -} - -#[test] -fn an_unreadable_version_is_reported_rather_than_assumed() { - let check = VersionCheck::compare("nightly", "0.4.0"); - assert!( - matches!(check, VersionCheck::Unreadable { .. }), - "an unreadable running version is a problem, not a pass: {check:?}" - ); - assert!(check.is_problem()); - assert!(VersionCheck::compare("0.4.0", "not a version").is_problem()); -} - -#[test] -fn a_too_old_gateway_warns_on_the_status_bar_and_names_both_versions() { - let (push, mut rx, _sink) = status_recorder(); - announce(&VersionCheck::compare("0.3.9", "0.4.0"), &push); - let frame = rx.try_recv().expect("the warning is pushed"); - assert_eq!(frame.label, "Gateway too old"); - assert!( - frame.description.contains("0.3.9") && frame.description.contains("0.4.0"), - "both versions are named: {}", - frame.description - ); -} - -#[test] -fn an_unreadable_version_warns_on_the_status_bar() { - let (push, mut rx, _sink) = status_recorder(); - announce(&VersionCheck::compare("nightly", "0.4.0"), &push); - let frame = rx.try_recv().expect("the warning is pushed"); - assert_eq!(frame.label, "Gateway version unknown"); - assert!( - frame.description.contains("nightly"), - "{}", - frame.description - ); -} - -#[test] -fn a_satisfied_check_says_nothing_on_the_status_bar() { - let (push, mut rx, _sink) = status_recorder(); - announce(&VersionCheck::compare("0.4.0", "0.4.0"), &push); - assert!( - rx.try_recv().is_err(), - "a healthy boot pushes no status line" - ); -} - -#[test] -fn an_unfilled_pin_warns_on_the_status_bar_in_a_release_build() { - let (push, mut rx, _sink) = status_recorder(); - announce_for(&VersionCheck::NoMinimumRecorded, &push, Build::Release); - let frame = rx.try_recv().expect("the unfilled pin is pushed"); - assert_eq!(frame.label, "Gateway version unchecked"); - assert!( - frame.description.contains("no minimum version"), - "the description names the cause: {}", - frame.description - ); - assert!( - frame.description.contains("nothing checks"), - "the description names the consequence: {}", - frame.description - ); +fn version_check_compare_classifies_all_outcomes() { + #[derive(Clone, Copy)] + enum Kind { + Satisfied, + TooOld, + NoMinimum, + Unreadable, + } + const CASES: &[(&str, &str, &str, Kind, bool)] = &[ + ("equal satisfies", "0.4.0", "0.4.0", Kind::Satisfied, false), + ("newer satisfies", "2.0.0", "0.4.0", Kind::Satisfied, false), + ("older is too old", "0.3.9", "0.4.0", Kind::TooOld, true), + ("empty minimum", "0.1.0", "", Kind::NoMinimum, false), + ( + "unreadable running", + "nightly", + "0.4.0", + Kind::Unreadable, + true, + ), + ( + "unreadable minimum", + "0.4.0", + "not a version", + Kind::Unreadable, + true, + ), + ]; + + for &(label, running, minimum, kind, expected_problem) in CASES { + let check = VersionCheck::compare(running, minimum); + let ok = match kind { + Kind::Satisfied => matches!(check, VersionCheck::Satisfied { .. }), + Kind::TooOld => matches!(check, VersionCheck::TooOld { .. }), + Kind::NoMinimum => matches!(check, VersionCheck::NoMinimumRecorded), + Kind::Unreadable => matches!(check, VersionCheck::Unreadable { .. }), + }; + assert!(ok, "{label}: got {check:?}"); + assert_eq!(check.is_problem(), expected_problem, "{label}"); + } } #[test] -fn an_unfilled_pin_stays_off_the_status_bar_in_a_debug_build() { - let (push, mut rx, _sink) = status_recorder(); - announce_for(&VersionCheck::NoMinimumRecorded, &push, Build::Debug); - assert!( - rx.try_recv().is_err(), - "a developer's checkout must not repeat this line on every launch" - ); -} +fn announce_pushes_expected_status_frames() { + type Expected = Option<(&'static str, &'static [&'static str])>; + type Case = (&'static str, &'static str, &'static str, Build, Expected); + const CASES: &[Case] = &[ + ( + "too old", + "0.3.9", + "0.4.0", + Build::Debug, + Some(("Gateway too old", &["0.3.9", "0.4.0"])), + ), + ( + "unreadable", + "nightly", + "0.4.0", + Build::Debug, + Some(("Gateway version unknown", &["nightly"])), + ), + ("satisfied", "0.4.0", "0.4.0", Build::Release, None), + ( + "unfilled release", + "0.1.0", + "", + Build::Release, + Some(( + "Gateway version unchecked", + &["no minimum version", "nothing checks"], + )), + ), + ("unfilled debug", "0.1.0", "", Build::Debug, None), + ]; + + for &(label, running, minimum, build, expected) in CASES { + let mut recorder = StatusRecorder::new(); + announce_for( + &VersionCheck::compare(running, minimum), + &recorder.push, + build, + ); + match expected { + Some((expected_label, fragments)) => { + let frame = recorder + .try_recv() + .unwrap_or_else(|_| panic!("{label}: expected status frame")); + assert_eq!(frame.label, expected_label, "{label}"); + for fragment in fragments { + assert!( + frame.description.contains(fragment), + "{label}: `{}` missing `{fragment}`", + frame.description + ); + } + } + None => assert!(recorder.try_recv().is_err(), "{label}: expected silence"), + } + } -#[test] -fn the_public_entry_point_follows_the_build_it_was_compiled_into() { - let (push, mut rx, _sink) = status_recorder(); - announce(&VersionCheck::NoMinimumRecorded, &push); + let mut recorder = StatusRecorder::new(); + announce(&VersionCheck::NoMinimumRecorded, &recorder.push); if cfg!(debug_assertions) { - assert!( - rx.try_recv().is_err(), - "this test build is a debug build, so the pin reaches the log only" - ); + assert!(recorder.try_recv().is_err(), "debug build logs only"); } else { - let frame = rx - .try_recv() - .expect("a release build shows the unfilled pin"); - assert_eq!(frame.label, "Gateway version unchecked"); + assert_eq!( + recorder.try_recv().expect("release build warns").label, + "Gateway version unchecked" + ); } } #[test] fn the_pin_minimum_is_the_compiled_default() { - // Whatever the pin holds, the constant is its value, never a guess. A - // placeholder becomes an empty minimum, which the comparison reads as - // "no minimum recorded" rather than as a version to enforce. - assert!( - MIN_GATEWAY.is_empty() || Version::parse(MIN_GATEWAY).is_some(), - "the compiled minimum is empty or a version: {MIN_GATEWAY}" - ); - assert!( - !MIN_GATEWAY.contains("PLACEHOLDER"), - "a placeholder must never become a minimum to compare against" - ); + assert!(MIN_GATEWAY.is_empty() || Version::parse(MIN_GATEWAY).is_some()); + assert!(!MIN_GATEWAY.contains("PLACEHOLDER")); assert_eq!( VersionCheck::against_pin("0.0.1"), VersionCheck::compare("0.0.1", MIN_GATEWAY) diff --git a/crates/workshop/menu/src/catalog-chat.rs b/crates/workshop/menu/src/catalog-chat.rs deleted file mode 100644 index f2754620..00000000 --- a/crates/workshop/menu/src/catalog-chat.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! Chat-capable catalog generation tracking. - -use std::sync::{Arc, Mutex, PoisonError}; - -use tokio::sync::watch; - -/// One immutable chat-capable catalog generation. -#[derive(Debug, Clone, Default)] -pub struct ChatCatalog { - /// Monotonically increasing whenever the chat-capable subset changes. - pub generation: u64, - /// The chat-capable entries for this generation. - pub models: Vec, -} - -/// Shared retained chat catalog and its generation notification. -#[derive(Debug, Clone)] -pub(super) struct ChatCatalogBus { - latest: Arc>, - generation: watch::Sender, -} - -impl ChatCatalogBus { - /// Creates an empty generation tracker. - pub(super) fn new() -> Self { - Self { - latest: Arc::new(Mutex::new(ChatCatalog::default())), - generation: watch::channel(0).0, - } - } - - /// Returns the current generation only when it can serve chat. - pub(super) fn latest(&self) -> Option { - let chat = self - .latest - .lock() - .unwrap_or_else(PoisonError::into_inner) - .clone(); - (!chat.models.is_empty()).then_some(chat) - } - - /// Subscribes to changes of the chat-capable subset. - pub(super) fn subscribe(&self) -> watch::Receiver { - self.generation.subscribe() - } - - /// Replaces the retained generation with `models`, which the catalog - /// bus has already filtered to chat-capable entries, advancing only - /// when they change. Transcription-only churn does not disturb chat - /// runs. - pub(super) fn publish(&self, models: &[serde_json::Value]) { - let changed = { - let mut latest = self.latest.lock().unwrap_or_else(PoisonError::into_inner); - if latest.models == models { - None - } else { - latest.generation = latest.generation.wrapping_add(1); - latest.models = models.to_vec(); - Some(latest.generation) - } - }; - if let Some(generation) = changed { - self.generation.send_replace(generation); - } - } -} diff --git a/crates/workshop/menu/src/catalog.rs b/crates/workshop/menu/src/catalog.rs index 9a98f76b..a0d9270b 100644 --- a/crates/workshop/menu/src/catalog.rs +++ b/crates/workshop/menu/src/catalog.rs @@ -11,15 +11,13 @@ //! current catalog immediately - the delivery contract's //! resend-on-reconnect for ephemeral frames. -use tokio::sync::{broadcast, watch}; +use std::sync::{Arc, Mutex, PoisonError}; +use serde_json::Value; +use tokio::sync::{broadcast, watch}; use workshop_protocol::CatalogPush; use workshop_support::RetainedBus; -#[path = "catalog-chat.rs"] -mod chat; -pub use chat::ChatCatalog; -use chat::ChatCatalogBus; pub use workshop_protocol::is_chat_capable; /// Ring capacity of the catalog bus. Pushes are rare (one per gateway @@ -27,12 +25,22 @@ pub use workshop_protocol::is_chat_capable; /// generous. const CATALOG_CHANNEL_CAPACITY: usize = 4; +/// One immutable chat-capable catalog generation. +#[derive(Debug, Clone, Default)] +pub struct ChatCatalog { + /// Monotonically increasing whenever the chat-capable subset changes. + pub generation: u64, + /// The chat-capable entries for this generation. + pub models: Vec, +} + /// The shared catalog bus: a cloneable handle onto the broadcast channel, /// mirroring the status subsystem's [`RetainedBus`]-backed status bus. #[derive(Debug, Clone)] pub struct CatalogBus { bus: RetainedBus, - chat: ChatCatalogBus, + chat_latest: Arc>, + chat_generation: watch::Sender, } impl CatalogBus { @@ -41,7 +49,8 @@ impl CatalogBus { pub fn new() -> Self { Self { bus: RetainedBus::new(CATALOG_CHANNEL_CAPACITY), - chat: ChatCatalogBus::new(), + chat_latest: Arc::new(Mutex::new(ChatCatalog::default())), + chat_generation: watch::channel(0).0, } } @@ -61,13 +70,17 @@ impl CatalogBus { /// The current non-empty chat-capable catalog generation. #[must_use] pub fn latest_chat(&self) -> Option { - self.chat.latest() + let chat = self + .chat_latest + .lock() + .unwrap_or_else(PoisonError::into_inner); + (!chat.models.is_empty()).then(|| chat.clone()) } /// Subscribes to chat-capable catalog generation changes. #[must_use] pub fn subscribe_chat_generation(&self) -> watch::Receiver { - self.chat.subscribe() + self.chat_generation.subscribe() } /// Broadcasts one catalog, keeping only its chat-capable entries. With @@ -76,11 +89,26 @@ impl CatalogBus { /// /// This is the catalog's only chat-capable filter: the chat /// generation and the menu read the filtered push as is. - pub fn publish(&self, models: Vec) { - let models = models.into_iter().filter(is_chat_capable).collect(); - let push = CatalogPush { models }; - self.chat.publish(&push.models); - self.bus.send(push); + /// Transcription-only churn does not disturb chat runs. + pub fn publish(&self, mut models: Vec) { + models.retain(is_chat_capable); + let changed = { + let mut latest = self + .chat_latest + .lock() + .unwrap_or_else(PoisonError::into_inner); + if latest.models == models { + None + } else { + latest.generation = latest.generation.wrapping_add(1); + latest.models.clone_from(&models); + Some(latest.generation) + } + }; + if let Some(generation) = changed { + self.chat_generation.send_replace(generation); + } + self.bus.send(CatalogPush { models }); } } diff --git a/crates/workshop/menu/src/menu.rs b/crates/workshop/menu/src/menu.rs index 433ab522..e29eed8a 100644 --- a/crates/workshop/menu/src/menu.rs +++ b/crates/workshop/menu/src/menu.rs @@ -19,20 +19,24 @@ //! layout is view state and persists through the UI-state buckets //! (`workshop-user-state` and the workspace file). -mod memory; - use std::collections::HashMap; -use std::path::Path; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use serde::Deserialize; +use serde_json::Value; +use tokio::runtime::Handle; use tokio::sync::broadcast; - use workshop_protocol::WorkbenchSnapshot; -use workshop_support::RetainedBus; +use workshop_support::{RetainedBus, write_atomic}; use crate::catalog::CatalogBus; -use self::memory::{MemoryWriter, PendingWrite, WORKSHOP_STATE_FILE, load_memory, store_pending}; +/// Name of the persisted server-state file, written in the server's +/// state directory. +const WORKSHOP_STATE_FILE: &str = "workshop-state.json"; /// Ring capacity of the menu bus. Pushes follow user interactions and /// heartbeat transitions, so a handful of slots is generous. @@ -101,39 +105,59 @@ fn describe_target(name: Option<&str>) -> String { } impl MenuState { - /// Applies the remembered-else-first selection rule for `profile`: - /// the remembered model when `models` still holds it, else the first - /// catalog model. Records the choice in per-profile memory and - /// returns its pending write when a model was selected. Shared by - /// [`MenuBus::finish_switch`] and [`MenuBus::restore_selection`]. + /// Applies the remembered-else-first selection rule for the active + /// profile: the remembered model when `models` still holds it, else + /// the first catalog model. Records the choice in per-profile memory + /// and returns its pending write when a profile is active and a model + /// was selected; with no active profile, selects the first catalog + /// model without touching memory. Shared by [`MenuBus::finish_switch`] + /// and [`MenuBus::restore_selection`]. #[must_use] - fn select_for_profile( - &mut self, - profile: String, - models: &[serde_json::Value], - ) -> Option { - self.selected_model = self - .last_selected - .get(&profile) + fn select_for_profile(&mut self, models: &[Value]) -> Option { + let Self { + active, + selected_model, + last_selected, + memory, + .. + } = self; + let Some(profile) = active.as_deref() else { + *selected_model = first_model_id(models); + return None; + }; + *selected_model = last_selected + .get(profile) .filter(|id| models_contain(models, id)) .cloned() .or_else(|| first_model_id(models)); - let id = self.selected_model.clone()?; - self.remember(profile, id) + let id = selected_model.as_deref()?; + remember(last_selected, memory, profile, id) } +} - /// Records `id` as the remembered model for `profile` and snapshots - /// the serialized memory as a [`PendingWrite`] for the caller to - /// perform once the state lock is released - the mutators run on the - /// async runtime, and file IO under the guard would block the - /// executor. `None` when persistence is disabled. - #[must_use] - fn remember(&mut self, profile: String, id: String) -> Option { - self.last_selected.insert(profile, id); - let memory = self.memory.as_mut()?; - let payload = serde_json::json!({ "last_selected": &self.last_selected }); - Some(memory.pending(payload.to_string().into_bytes())) +/// Records `id` as the remembered model for `profile` and snapshots +/// the serialized memory as a [`PendingWrite`] for the caller to +/// perform once the state lock is released - the mutators run on the +/// async runtime, and file IO under the guard would block the +/// executor. `None` when persistence is disabled. +#[must_use] +fn remember( + last_selected: &mut HashMap, + memory: &mut Option, + profile: &str, + id: &str, +) -> Option { + if let Some(entry) = last_selected.get_mut(profile) { + if entry != id { + entry.clear(); + entry.push_str(id); + } + } else { + last_selected.insert(profile.to_owned(), id.to_owned()); } + let memory = memory.as_mut()?; + let payload = serde_json::json!({ "last_selected": &*last_selected }); + Some(memory.pending(payload.to_string().into_bytes())) } /// A refused menu mutation. A refusal is a state to report, not an error @@ -216,14 +240,20 @@ impl MenuBus { /// current catalog; the refused selection is not applied. pub fn set_selected(&self, id: &str) -> Result<(), MenuRefusal> { if !self.catalog_has(id) { - return Err(MenuRefusal::UnknownModel { id: id.to_string() }); + return Err(MenuRefusal::UnknownModel { id: id.to_owned() }); } let mut state = self.lock_state(); - state.selected_model = Some(id.to_string()); - let pending = state - .active - .clone() - .and_then(|profile| state.remember(profile, id.to_string())); + let MenuState { + active, + selected_model, + last_selected, + memory, + .. + } = &mut *state; + *selected_model = Some(id.to_owned()); + let pending = active + .as_deref() + .and_then(|profile| remember(last_selected, memory, profile, id)); self.publish(&state); drop(state); store_pending(pending); @@ -268,20 +298,16 @@ impl MenuBus { tracing::warn!("finish_switch with no switch in flight; ignored"); return; }; - let mut pending = None; - if outcome == SwitchOutcome::Completed { + let pending = if outcome == SwitchOutcome::Completed { let models = self.catalog_models(); - match target { - SwitchTarget::Profile(profile) => { - state.active = Some(profile.clone()); - pending = state.select_for_profile(profile, &models); - } - SwitchTarget::NoProfile => { - state.active = None; - state.selected_model = first_model_id(&models); - } - } - } + state.active = match target { + SwitchTarget::Profile(profile) => Some(profile), + SwitchTarget::NoProfile => None, + }; + state.select_for_profile(&models) + } else { + None + }; self.publish(&state); drop(state); store_pending(pending); @@ -302,14 +328,7 @@ impl MenuBus { return; } let models = self.catalog_models(); - let pending = if let Some(profile) = state.active.clone() { - state.select_for_profile(profile, &models) - } else { - // No active profile means no memory to consult and none to - // record; fall straight back to the first catalog model. - state.selected_model = first_model_id(&models); - None - }; + let pending = state.select_for_profile(&models); if state.selected_model.is_none() { return; } @@ -406,7 +425,7 @@ impl MenuBus { } /// The current catalog's models array, empty before the first push. - fn catalog_models(&self) -> Vec { + fn catalog_models(&self) -> Vec { self.catalog .latest() .map_or_else(Vec::new, |push| push.models) @@ -414,20 +433,145 @@ impl MenuBus { } /// Whether the catalog `models` array holds an entry whose `id` is `id`. -fn models_contain(models: &[serde_json::Value], id: &str) -> bool { +fn models_contain(models: &[Value], id: &str) -> bool { models .iter() - .any(|model| model.get("id").and_then(serde_json::Value::as_str) == Some(id)) + .any(|model| model.get("id").and_then(Value::as_str) == Some(id)) } /// The `id` of the first catalog entry, when there is one. -fn first_model_id(models: &[serde_json::Value]) -> Option { - models.iter().find_map(|model| { - model - .get("id") - .and_then(serde_json::Value::as_str) - .map(str::to_string) - }) +fn first_model_id(models: &[Value]) -> Option { + models + .iter() + .find_map(|model| model.get("id").and_then(Value::as_str).map(str::to_owned)) +} + +/// The memory file's writer: where the memory persists, the sequence the +/// next snapshot takes, and the write gate its pending writes share. It +/// lives in the menu state, so snapshots take their sequences under the +/// state lock, in the order their contents were captured. +#[derive(Debug)] +struct MemoryWriter { + /// Where the memory persists. + path: PathBuf, + /// The sequence of the last snapshot taken; 0 before the first. + last_taken: u64, + /// Shared with every pending write; see [`PendingWrite`]. + gate: Arc>, +} + +impl MemoryWriter { + /// A writer for the memory file at `path`, with nothing taken or + /// written yet. + fn new(path: PathBuf) -> Self { + Self { + path, + last_taken: 0, + gate: Arc::default(), + } + } + + /// Takes `bytes` as the newest snapshot awaiting its write. + fn pending(&mut self, bytes: Vec) -> PendingWrite { + self.last_taken += 1; + PendingWrite { + path: self.path.clone(), + bytes, + sequence: self.last_taken, + gate: Arc::clone(&self.gate), + } + } +} + +/// One serialized memory snapshot awaiting its write: the bytes, path, +/// and sequence are captured under the state lock, and the write runs +/// after the guard drops, off the async executor. +#[derive(Debug)] +struct PendingWrite { + /// Where the memory persists. + path: PathBuf, + /// The serialized [`WORKSHOP_STATE_FILE`] contents. + bytes: Vec, + /// The snapshot's place in capture order, starting at 1. + sequence: u64, + /// The memory file's write gate: held across each write so writes + /// never interleave, it holds the sequence of the last snapshot + /// written, 0 before the first. + gate: Arc>, +} + +/// The persisted shape of [`WORKSHOP_STATE_FILE`]. Server state only: +/// the UI's panel layout is view state and persists through the UI-state +/// buckets (`workshop-user-state` and the workspace file), never here. +#[derive(Debug, Deserialize)] +struct StoredState { + /// Remembered model selection per profile name. + last_selected: HashMap, +} + +/// Loads the per-profile model memory. A missing, unreadable, or corrupt +/// file means "no memory yet": logged and tolerated. +fn load_memory(path: &Path) -> HashMap { + let raw = match fs::read_to_string(path) { + Ok(raw) => raw, + Err(error) => { + if error.kind() != io::ErrorKind::NotFound { + tracing::warn!( + %error, + path = %path.display(), + "workshop state unreadable; starting with no model memory" + ); + } + return HashMap::new(); + } + }; + match serde_json::from_str::(&raw) { + Ok(stored) => stored.last_selected, + Err(error) => { + tracing::warn!( + %error, + path = %path.display(), + "workshop state corrupt; starting with no model memory" + ); + HashMap::new() + } + } +} + +/// Performs a pending memory write off the async executor. On a runtime +/// the file IO moves to the blocking pool and completes in the +/// background - the memory file is a best-effort cache, so no caller +/// awaits it. Outside a runtime (the unit tests drive the mutators +/// synchronously) the write runs inline instead. +fn store_pending(pending: Option) { + let Some(pending) = pending else { return }; + match Handle::try_current() { + Ok(handle) => { + handle.spawn_blocking(move || store_memory(&pending)); + } + Err(_) => store_memory(&pending), + } +} + +/// Writes one per-profile model-memory snapshot through the shared +/// atomic-write helper, so a crash mid-write cannot leave a truncated +/// [`WORKSHOP_STATE_FILE`]. Pending writes reach the blocking pool in +/// no guaranteed order, so the gate serializes them and skips a snapshot +/// no newer than the last one written: the newest snapshot wins. A +/// failed write costs the memory, not the process: logged and tolerated. +fn store_memory(pending: &PendingWrite) { + let mut last_written = pending.gate.lock().unwrap_or_else(PoisonError::into_inner); + if pending.sequence <= *last_written { + return; + } + match write_atomic(&pending.path, &pending.bytes) { + Ok(()) => *last_written = pending.sequence, + Err(error) => tracing::warn!( + %error, + path = %pending.path.display(), + "workshop state write failed; model memory not persisted" + ), + } } #[cfg(test)] diff --git a/crates/workshop/menu/src/menu/memory.rs b/crates/workshop/menu/src/menu/memory.rs deleted file mode 100644 index 8c2f7959..00000000 --- a/crates/workshop/menu/src/menu/memory.rs +++ /dev/null @@ -1,138 +0,0 @@ -//! The per-profile model memory's file: its on-disk shape, the tolerant -//! load, and the off-executor atomic write. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, PoisonError}; - -/// Name of the persisted server-state file, written in the server's -/// state directory. -pub(super) const WORKSHOP_STATE_FILE: &str = "workshop-state.json"; - -/// The memory file's writer: where the memory persists, the sequence the -/// next snapshot takes, and the write gate its pending writes share. It -/// lives in the menu state, so snapshots take their sequences under the -/// state lock, in the order their contents were captured. -#[derive(Debug)] -pub(super) struct MemoryWriter { - /// Where the memory persists. - path: PathBuf, - /// The sequence of the last snapshot taken; 0 before the first. - last_taken: u64, - /// Shared with every pending write; see [`PendingWrite`]. - gate: Arc>, -} - -impl MemoryWriter { - /// A writer for the memory file at `path`, with nothing taken or - /// written yet. - pub(super) fn new(path: PathBuf) -> Self { - Self { - path, - last_taken: 0, - gate: Arc::default(), - } - } - - /// Takes `bytes` as the newest snapshot awaiting its write. - pub(super) fn pending(&mut self, bytes: Vec) -> PendingWrite { - self.last_taken += 1; - PendingWrite { - path: self.path.clone(), - bytes, - sequence: self.last_taken, - gate: Arc::clone(&self.gate), - } - } -} - -/// One serialized memory snapshot awaiting its write: the bytes, path, -/// and sequence are captured under the state lock, and the write runs -/// after the guard drops, off the async executor. -#[derive(Debug)] -pub(super) struct PendingWrite { - /// Where the memory persists. - path: PathBuf, - /// The serialized [`WORKSHOP_STATE_FILE`] contents. - bytes: Vec, - /// The snapshot's place in capture order, starting at 1. - sequence: u64, - /// The memory file's write gate: held across each write so writes - /// never interleave, it holds the sequence of the last snapshot - /// written, 0 before the first. - gate: Arc>, -} - -/// The persisted shape of [`WORKSHOP_STATE_FILE`]. Server state only: -/// the UI's panel layout is view state and persists through the UI-state -/// buckets (`workshop-user-state` and the workspace file), never here. -#[derive(Debug, serde::Deserialize)] -struct StoredState { - /// Remembered model selection per profile name. - last_selected: HashMap, -} - -/// Loads the per-profile model memory. A missing, unreadable, or corrupt -/// file means "no memory yet": logged and tolerated. -pub(super) fn load_memory(path: &Path) -> HashMap { - let raw = match std::fs::read_to_string(path) { - Ok(raw) => raw, - Err(error) => { - if error.kind() != std::io::ErrorKind::NotFound { - tracing::warn!( - %error, - path = %path.display(), - "workshop state unreadable; starting with no model memory" - ); - } - return HashMap::new(); - } - }; - match serde_json::from_str::(&raw) { - Ok(stored) => stored.last_selected, - Err(error) => { - tracing::warn!( - %error, - path = %path.display(), - "workshop state corrupt; starting with no model memory" - ); - HashMap::new() - } - } -} - -/// Performs a pending memory write off the async executor. On a runtime -/// the file IO moves to the blocking pool and completes in the -/// background - the memory file is a best-effort cache, so no caller -/// awaits it. Outside a runtime (the unit tests drive the mutators -/// synchronously) the write runs inline instead. -pub(super) fn store_pending(pending: Option) { - let Some(pending) = pending else { return }; - match tokio::runtime::Handle::try_current() { - Ok(handle) => { - handle.spawn_blocking(move || store_memory(&pending)); - } - Err(_) => store_memory(&pending), - } -} - -/// Writes one per-profile model-memory snapshot through the shared -/// atomic-write helper, so a crash mid-write cannot leave a truncated -/// [`WORKSHOP_STATE_FILE`]. Pending writes reach the blocking pool in -/// no guaranteed order, so the gate serializes them and skips a snapshot -/// no newer than the last one written: the newest snapshot wins. A -/// failed write costs the memory, not the process: logged and tolerated. -pub(super) fn store_memory(pending: &PendingWrite) { - let mut last_written = pending.gate.lock().unwrap_or_else(PoisonError::into_inner); - if pending.sequence <= *last_written { - return; - } - match workshop_support::write_atomic(&pending.path, &pending.bytes) { - Ok(()) => *last_written = pending.sequence, - Err(error) => tracing::warn!( - %error, - path = %pending.path.display(), - "workshop state write failed; model memory not persisted" - ), - } -} diff --git a/crates/workshop/menu/src/menu/tests-memory.rs b/crates/workshop/menu/src/menu/tests-memory.rs index 1ea0f4d0..4970a665 100644 --- a/crates/workshop/menu/src/menu/tests-memory.rs +++ b/crates/workshop/menu/src/menu/tests-memory.rs @@ -4,8 +4,6 @@ use super::*; -use super::super::memory::store_memory; - #[test] fn a_selection_is_remembered_per_profile_across_switches() { let menu = menu_of(&["model-a", "model-b", "model-c"]); @@ -51,45 +49,73 @@ fn model_memory_round_trips_through_the_state_file() { ); } -#[test] -fn a_missing_state_file_means_no_memory_yet() { - let dir = tempfile::TempDir::new().expect("tempdir"); - let menu = MenuBus::new(catalog_of(&["model-a"]), Some(dir.path())); - onto_profile(&menu, "main"); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-a"), - "no memory yet: the first catalog model is selected" - ); -} +const AB: &[&str] = &["model-a", "model-b"]; +const MEM_B: &str = r#"{"last_selected":{"main":"model-b"}}"#; +const MEM_STALE: &str = r#"{"last_selected":{"main":"retired"}}"#; +const MEM_OTHER: &str = r#"{"last_selected":{"coding":"model-b"}}"#; -#[test] -fn a_corrupt_state_file_means_no_memory_yet() { - let dir = tempfile::TempDir::new().expect("tempdir"); - std::fs::write(dir.path().join(WORKSHOP_STATE_FILE), "not json {").expect("write fixture"); - let menu = MenuBus::new(catalog_of(&["model-a"]), Some(dir.path())); - onto_profile(&menu, "main"); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-a"), - "corrupt memory degrades to no memory, never to a failure" - ); +#[derive(Clone, Copy)] +enum StateFixture { + Missing, + File(&'static str), + Directory, } +const DEGRADED_MEMORY_CASES: &[(&str, StateFixture)] = { + use StateFixture as F; + &[ + ("missing", F::Missing), + ("empty", F::File("")), + ("corrupt_json", F::File("not json {")), + ("wrong_shape", F::File(r#"{"last_selected":"bad"}"#)), + ("unreadable_dir", F::Directory), + ("retired_model", F::File(MEM_STALE)), + ] +}; + +/// Boot-time restore row: `(label, catalog, stored, active, preselected, publishes, expected)`. +type RestoreRow = ( + &'static str, + &'static [&'static str], + Option<&'static str>, + Option<&'static str>, + Option<&'static str>, + bool, + Option<&'static str>, +); + +const RESTORE_CASES: &[RestoreRow] = { + const A: Option<&str> = Some("model-a"); + const B: Option<&str> = Some("model-b"); + const M: Option<&str> = Some("main"); + &[ + ("remembered", AB, Some(MEM_B), M, None, true, B), + ("stale", AB, Some(MEM_STALE), M, None, true, A), + ("other_prof", AB, Some(MEM_OTHER), M, None, true, A), + ("no_active", AB, Some(MEM_B), None, None, true, A), + ("preselected", AB, None, None, B, false, B), + ("empty_cat", &[], Some(MEM_B), M, None, false, None), + ] +}; + #[test] -fn an_unreadable_state_file_means_no_memory_yet() { - let dir = tempfile::TempDir::new().expect("tempdir"); - // A directory in the file's place: reads and writes both fail for - // a reason other than NotFound, and both must degrade. - std::fs::create_dir(dir.path().join(WORKSHOP_STATE_FILE)) - .expect("directory in the file's place"); - let menu = MenuBus::new(catalog_of(&["model-a"]), Some(dir.path())); - onto_profile(&menu, "main"); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-a"), - "unreadable memory degrades to no memory, never to a failure" - ); +fn degraded_or_stale_state_files_fall_back_to_the_first_model() { + for &(label, fixture) in DEGRADED_MEMORY_CASES { + let dir = tempfile::TempDir::new().expect("tempdir"); + let path = dir.path().join(WORKSHOP_STATE_FILE); + match fixture { + StateFixture::Missing => {} + StateFixture::File(body) => std::fs::write(&path, body).expect("write fixture"), + StateFixture::Directory => std::fs::create_dir(&path).expect("create dir"), + } + let menu = MenuBus::new(catalog_of(&["model-a"]), Some(dir.path())); + onto_profile(&menu, "main"); + assert_eq!( + snapshot(&menu).selected_model.as_deref(), + Some("model-a"), + "{label}" + ); + } } #[test] @@ -102,105 +128,35 @@ fn writes_landing_newest_first_leave_the_newest_snapshot_on_disk() { store_memory(&newer); store_memory(&older); assert_eq!( - std::fs::read_to_string(&path).expect("the newer snapshot was written"), - r#"{"last_selected":{"main":"model-b"}}"#, - "an older snapshot landing last never overwrites the newest" + std::fs::read_to_string(&path).expect("newer snapshot written"), + r#"{"last_selected":{"main":"model-b"}}"# ); } #[test] -fn a_remembered_model_gone_from_the_catalog_falls_back_to_the_first() { - let dir = tempfile::TempDir::new().expect("tempdir"); - std::fs::write( - dir.path().join(WORKSHOP_STATE_FILE), - r#"{"last_selected":{"main":"retired-model"}}"#, - ) - .expect("write fixture"); - let menu = MenuBus::new(catalog_of(&["model-a"]), Some(dir.path())); - onto_profile(&menu, "main"); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-a"), - "a remembered model the catalog no longer holds falls back to the first" - ); -} +fn restore_selection_applies_memory_fallback_and_noop_rules() { + for &(label, catalog, stored, active, preselected, publishes, expected) in RESTORE_CASES { + let dir = tempfile::TempDir::new().expect("tempdir"); + if let Some(body) = stored { + std::fs::write(dir.path().join(WORKSHOP_STATE_FILE), body).expect("write fixture"); + } + let menu = MenuBus::new(catalog_of(catalog), Some(dir.path())); + if let Some(profile) = active { + menu.set_profiles(vec![profile.to_string()], Some(profile.to_string())); + } + if let Some(model) = preselected { + menu.set_selected(model).expect("in catalog"); + } + let mut receiver = menu.subscribe(); + menu.restore_selection(); -#[test] -fn restore_selection_picks_the_remembered_model_for_the_active_profile() { - let dir = tempfile::TempDir::new().expect("tempdir"); - std::fs::write( - dir.path().join(WORKSHOP_STATE_FILE), - r#"{"last_selected":{"main":"model-b"}}"#, - ) - .expect("write fixture"); - let menu = MenuBus::new(catalog_of(&["model-a", "model-b"]), Some(dir.path())); - menu.set_profiles(vec!["main".to_string()], Some("main".to_string())); - menu.restore_selection(); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-b"), - "boot restores the remembered model for the active profile" - ); -} - -#[test] -fn restore_selection_falls_back_to_the_first_model_when_memory_is_stale() { - let dir = tempfile::TempDir::new().expect("tempdir"); - std::fs::write( - dir.path().join(WORKSHOP_STATE_FILE), - r#"{"last_selected":{"main":"retired-model"}}"#, - ) - .expect("write fixture"); - let menu = MenuBus::new(catalog_of(&["model-a", "model-b"]), Some(dir.path())); - menu.set_profiles(vec!["main".to_string()], Some("main".to_string())); - menu.restore_selection(); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-a"), - "a remembered model the catalog lacks falls back to the first" - ); -} - -#[test] -fn restore_selection_without_an_active_profile_picks_the_first_model() { - let menu = menu_of(&["model-a", "model-b"]); - menu.restore_selection(); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-a"), - "with no active profile there is no memory; the first model serves" - ); -} - -#[test] -fn restore_selection_with_a_selection_applied_publishes_nothing() { - let menu = menu_of(&["model-a", "model-b"]); - menu.set_selected("model-b") - .expect("the id is in the catalog"); - let mut receiver = menu.subscribe(); - menu.restore_selection(); - assert!( - matches!(receiver.try_recv(), Err(TryRecvError::Empty)), - "an existing selection makes the restore a no-op" - ); - assert_eq!( - snapshot(&menu).selected_model.as_deref(), - Some("model-b"), - "the surviving selection is untouched" - ); -} - -#[test] -fn restore_selection_with_an_empty_catalog_publishes_nothing() { - let menu = menu_of(&[]); - let mut receiver = menu.subscribe(); - menu.restore_selection(); - assert!( - matches!(receiver.try_recv(), Err(TryRecvError::Empty)), - "an empty catalog leaves nothing to restore" - ); - assert!( - menu.latest().is_none(), - "a no-op restore retains no snapshot" - ); + assert_eq!(receiver.try_recv().is_ok(), publishes, "{label}: publish"); + assert_eq!( + menu.latest() + .and_then(|snap| snap.selected_model) + .as_deref(), + expected, + "{label}: selected" + ); + } } diff --git a/crates/workshop/menu/src/menu/tests.rs b/crates/workshop/menu/src/menu/tests.rs index 076683d0..d0428c1a 100644 --- a/crates/workshop/menu/src/menu/tests.rs +++ b/crates/workshop/menu/src/menu/tests.rs @@ -62,139 +62,114 @@ fn an_unknown_model_is_refused_and_not_applied() { ); } -#[test] -fn a_switch_publishes_its_begin_and_its_finish() { - let menu = menu_of(&["model-a"]); - menu.set_gateway_reachable(true); - menu.begin_switch(Some("coding")) - .expect("no switch is running"); - let during = snapshot(&menu); - assert_eq!(during.switching.as_deref(), Some("coding")); - assert!(during.switch_in_flight, "a named switch is in flight"); - assert!(!during.chat_ready, "a switch in flight blocks chat"); - menu.finish_switch(SwitchOutcome::Completed); - let after = snapshot(&menu); - assert_eq!(after.active.as_deref(), Some("coding")); - assert_eq!(after.switching, None); - assert!( - !after.switch_in_flight, - "the finish clears the in-flight mark" - ); - assert_eq!( - after.selected_model.as_deref(), - Some("model-a"), - "with no memory for the profile the first catalog model is selected" - ); - assert!(after.chat_ready); -} +/// Profile-switch row: `(label, initial, target, outcome, active_after, selected_after)`. +type SwitchRow = ( + &'static str, + Option<&'static str>, + Option<&'static str>, + SwitchOutcome, + Option<&'static str>, + &'static str, +); -#[test] -fn a_failed_switch_keeps_the_previous_profile() { - let menu = menu_of(&["model-a"]); - onto_profile(&menu, "main"); - menu.begin_switch(Some("coding")) - .expect("no switch is running"); - menu.finish_switch(SwitchOutcome::Failed); - let after = snapshot(&menu); - assert_eq!(after.active.as_deref(), Some("main")); - assert_eq!(after.switching, None); - assert!(after.chat_ready, "the previous profile still serves"); -} +const SWITCH_CASES: &[SwitchRow] = { + const OK: SwitchOutcome = SwitchOutcome::Completed; + const FAIL: SwitchOutcome = SwitchOutcome::Failed; + const DEFER: SwitchOutcome = SwitchOutcome::Deferred; + const M: Option<&str> = Some("m"); + const C: Option<&str> = Some("c"); + &[ + ("boot_named_ok", None, C, OK, C, "model-a"), + ("named_named_ok", M, C, OK, C, "model-a"), + ("named_none_ok", M, None, OK, None, "model-a"), + ("named_named_fail", M, C, FAIL, M, "model-b"), + ("named_named_defer", M, C, DEFER, M, "model-b"), + ("named_none_fail", M, None, FAIL, M, "model-b"), + ("named_none_defer", M, None, DEFER, M, "model-b"), + ] +}; + +/// `set_profiles` cases: `(label, seed_ready, profiles, active)`. +const SET_PROFILES_CASES: &[(&str, bool, &[&str], Option<&str>)] = &[ + ("populate", false, &["main", "coding"], Some("main")), + ("refresh_ready", true, &["main"], Some("main")), + ("clear_empty", true, &[], None), + ("no_active", false, &["main", "coding"], None), + ("gateway_order", false, &["coding", "main"], Some("coding")), +]; #[test] -fn a_second_switch_while_one_runs_is_refused() { - let menu = menu_of(&["model-a"]); - menu.begin_switch(Some("coding")) - .expect("no switch is running"); - let refusal = menu - .begin_switch(Some("writing")) - .expect_err("switches are single-flight"); - assert_eq!( - refusal, - MenuRefusal::SwitchInProgress { - name: Some("coding".to_string()) +fn profile_switches_enforce_single_flight_and_apply_each_outcome() { + for &(label, initial, target, outcome, exp_active, exp_selected) in SWITCH_CASES { + let menu = menu_of(&["model-a", "model-b"]); + if let Some(profile) = initial { + onto_profile(&menu, profile); + menu.set_selected("model-b").expect("model-b in catalog"); + } else { + menu.set_gateway_reachable(true); } - ); - assert_eq!( - refusal.to_string(), - "a switch to \"coding\" is already in progress", - "the refusal names the running switch's target" - ); - assert_eq!( - snapshot(&menu).switching.as_deref(), - Some("coding"), - "the refused switch is not applied" - ); -} -#[test] -fn a_switch_to_no_profile_blocks_chat_and_settles_with_no_active_profile() { - let menu = menu_of(&["model-a", "model-b"]); - onto_profile(&menu, "main"); - menu.set_selected("model-b") - .expect("the id is in the catalog"); - menu.begin_switch(None).expect("no switch is running"); - let during = snapshot(&menu); - assert_eq!( - during.switching, None, - "the wire frame names no target while no profile is being selected" - ); - assert!( - during.switch_in_flight, - "the frame still reports a switch to no profile as in flight" - ); - assert!(!during.chat_ready, "a switch in flight blocks chat"); - assert_eq!( - during.active.as_deref(), - Some("main"), - "the previous profile still serves while the switch runs" - ); - let refusal = menu - .begin_switch(Some("coding")) - .expect_err("switches are single-flight even toward no profile"); - assert_eq!(refusal, MenuRefusal::SwitchInProgress { name: None }); - assert_eq!( - refusal.to_string(), - "a switch to no profile is already in progress" - ); - menu.finish_switch(SwitchOutcome::Completed); - let after = snapshot(&menu); - assert_eq!(after.active, None, "no profile is active once it settles"); - assert_eq!(after.switching, None); - assert!( - !after.switch_in_flight, - "the finish clears the in-flight mark" - ); - assert_eq!( - after.selected_model.as_deref(), - Some("model-a"), - "with no profile there is no memory; the first catalog model serves" - ); - assert!(after.chat_ready, "chat is usable with no profile selected"); -} + menu.begin_switch(target) + .unwrap_or_else(|err| panic!("{label}: begin: {err}")); + let during = snapshot(&menu); + assert_eq!(during.switching.as_deref(), target, "{label}: switching"); + assert!( + during.switch_in_flight && !during.chat_ready, + "{label}: in-flight blocks chat" + ); + assert_eq!(during.active.as_deref(), initial, "{label}: active during"); -#[test] -fn a_deferred_switch_keeps_the_previous_profile_and_clears_the_switch() { - let menu = menu_of(&["model-a"]); - onto_profile(&menu, "main"); - menu.begin_switch(Some("coding")) - .expect("no switch is running"); - menu.finish_switch(SwitchOutcome::Deferred); - let after = snapshot(&menu); - assert_eq!( - after.active.as_deref(), - Some("main"), - "the selection persisted but the running profile is unchanged" - ); - assert_eq!(after.switching, None); - assert!(after.chat_ready, "the previous profile still serves"); + let refusal = menu + .begin_switch(Some("writing")) + .expect_err(&format!("{label}: concurrent")); + assert_eq!( + refusal, + MenuRefusal::SwitchInProgress { + name: target.map(str::to_owned) + }, + "{label}: refusal" + ); + let expected_msg = target.map_or_else( + || "a switch to no profile is already in progress".to_string(), + |name| format!("a switch to {name:?} is already in progress"), + ); + assert_eq!(refusal.to_string(), expected_msg, "{label}: refusal msg"); + assert_eq!( + snapshot(&menu).switching.as_deref(), + target, + "{label}: target untouched" + ); + + menu.finish_switch(outcome); + let after = snapshot(&menu); + assert_eq!(after.active.as_deref(), exp_active, "{label}: active after"); + assert_eq!(after.switching, None, "{label}: switching cleared"); + assert!( + !after.switch_in_flight && after.chat_ready, + "{label}: settled ready" + ); + assert_eq!( + after.selected_model.as_deref(), + Some(exp_selected), + "{label}: selected" + ); + } } #[test] fn finishing_with_no_switch_in_flight_is_tolerated() { - let menu = menu_of(&[]); - menu.finish_switch(SwitchOutcome::Completed); - assert!(menu.latest().is_none(), "a no-op finish publishes nothing"); + for outcome in [ + SwitchOutcome::Completed, + SwitchOutcome::Deferred, + SwitchOutcome::Failed, + ] { + let menu = menu_of(&[]); + menu.finish_switch(outcome); + assert!( + menu.latest().is_none(), + "{outcome:?}: no-op publishes nothing" + ); + } } #[test] @@ -314,40 +289,27 @@ fn chat_ready_is_false_before_the_heartbeat_reports_reachability() { } #[test] -fn set_profiles_publishes_the_list_and_the_active_profile() { - let menu = menu_of(&["model-a"]); - menu.set_profiles( - vec!["main".to_string(), "coding".to_string()], - Some("main".to_string()), - ); - let published = snapshot(&menu); - assert_eq!(published.profiles, ["main", "coding"]); - assert_eq!(published.active.as_deref(), Some("main")); -} - -#[test] -fn set_profiles_leaves_the_selection_and_readiness_alone() { - let menu = menu_of(&["model-a"]); - onto_profile(&menu, "main"); - menu.set_profiles(vec!["main".to_string()], Some("main".to_string())); - let after = snapshot(&menu); - assert_eq!( - after.selected_model.as_deref(), - Some("model-a"), - "the profile list does not own selection validity" - ); - assert!(after.chat_ready, "readiness survives a profile refresh"); -} - -#[test] -fn an_empty_profile_list_replaces_a_populated_one() { - let menu = menu_of(&[]); - menu.set_profiles(vec!["main".to_string()], Some("main".to_string())); - menu.set_profiles(Vec::new(), None); - let after = snapshot(&menu); - assert!( - after.profiles.is_empty(), - "a failed or declined profile fetch publishes an empty list" - ); - assert_eq!(after.active, None); +fn set_profiles_updates_list_and_active_without_disturbing_selection() { + for &(label, seed_ready, profiles, active) in SET_PROFILES_CASES { + let menu = menu_of(&["model-a"]); + if seed_ready { + onto_profile(&menu, "main"); + menu.set_profiles(vec!["main".to_string()], Some("main".to_string())); + } + menu.set_profiles( + profiles.iter().map(|p| (*p).to_string()).collect(), + active.map(str::to_string), + ); + let after = snapshot(&menu); + assert_eq!(after.profiles, profiles, "{label}: profiles"); + assert_eq!(after.active.as_deref(), active, "{label}: active"); + if seed_ready { + assert_eq!( + after.selected_model.as_deref(), + Some("model-a"), + "{label}: selection survives" + ); + assert!(after.chat_ready, "{label}: readiness survives"); + } + } } diff --git a/crates/workshop/protocol/src/catalog.rs b/crates/workshop/protocol/src/catalog.rs deleted file mode 100644 index 64cbe233..00000000 --- a/crates/workshop/protocol/src/catalog.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Catalog frames: the `{"type":"models",...}` pushes. - -use serde::Serialize; - -/// One pushed model catalog. -#[derive(Debug, Clone, PartialEq)] -pub struct CatalogPush { - /// The chat-capable subset of the gateway's model array. - pub models: Vec, -} - -impl CatalogPush { - /// The push as a wire frame: `"type": "models"` beside the array. - #[must_use] - pub fn frame(&self) -> CatalogFrame<'_> { - CatalogFrame { - kind: "models", - models: &self.models, - } - } -} - -/// The serialized shape of a catalog push on the socket, matching the -/// workshop protocol's frame taxonomy. -/// -/// Delivery: ephemeral - the newest push holds the whole catalog and -/// supersedes every older one; the catalog is resent on reconnect. -#[derive(Debug, Serialize)] -pub struct CatalogFrame<'a> { - #[serde(rename = "type")] - kind: &'static str, - models: &'a [serde_json::Value], -} - -/// Whether one gateway catalog row can back a chat model binding. -/// -/// This is wire semantics - it interprets the gateway's catalog shape - -/// so it sits here rather than in any one subsystem: the menu filters -/// its picker by it, and the gateway subsystem's catalog refresh reads -/// readiness from it. -#[must_use] -pub fn is_chat_capable(model: &serde_json::Value) -> bool { - let has_id = model - .get("id") - .and_then(serde_json::Value::as_str) - .is_some_and(|id| !id.is_empty()); - let chat_kind = match model.get("kind") { - None => true, - Some(serde_json::Value::String(kind)) => kind == "chat", - Some(_) => false, - }; - has_id && chat_kind -} diff --git a/crates/workshop/protocol/src/error.rs b/crates/workshop/protocol/src/error.rs deleted file mode 100644 index d1941011..00000000 --- a/crates/workshop/protocol/src/error.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Error shapes on the wire: the socket `error` frame and the HTTP error -//! envelope. - -use serde::Serialize; - -/// A failure report answered to one inbound frame - a malformed frame, a -/// refused menu event, or an agent-session failure: -/// `{"type":"error","message":"..."}` plus the echoed request `id`. -/// -/// Delivery: durable on the workshop socket - a direct per-request reply -/// sent by the loop that owns the socket. The agent-session socket -/// additionally pushes id-less error frames for session-level failures; -/// that delivery is ephemeral and documented in `workshop-server`'s -/// `agents::wire` module. -#[derive(Debug, Serialize)] -pub struct ErrorFrame { - #[serde(rename = "type")] - kind: &'static str, - message: String, - /// The request's `id`, echoed verbatim when the request had one and - /// omitted from the wire when it did not. - #[serde(skip_serializing_if = "Option::is_none")] - id: Option, -} - -impl ErrorFrame { - /// Builds an error frame holding `message`, echoing `id` when present. - #[must_use] - pub fn new(message: String, id: Option<&serde_json::Value>) -> Self { - Self { - kind: "error", - message, - id: id.cloned(), - } - } -} - -/// The opaque wire error envelope every HTTP failure answers with: -/// `{"error":{"message":"...","code":"..."}}`. -/// -/// The server maps its per-crate error types onto status codes and renders -/// this envelope; the shape is pinned here so the wire contract sits in -/// one place. Failures rendered as plain text (the asset 404) never take -/// this shape. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -pub struct ErrorEnvelope { - error: EnvelopeBody, -} - -/// The envelope payload: the user-visible message and the -/// machine-readable code. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -struct EnvelopeBody { - message: String, - code: String, -} - -impl ErrorEnvelope { - /// Builds the envelope holding `message` under the machine-readable - /// `code`. - #[must_use] - pub fn new(message: impl Into, code: impl Into) -> Self { - Self { - error: EnvelopeBody { - message: message.into(), - code: code.into(), - }, - } - } -} diff --git a/crates/workshop/protocol/src/frames.rs b/crates/workshop/protocol/src/frames.rs new file mode 100644 index 00000000..3f2333f9 --- /dev/null +++ b/crates/workshop/protocol/src/frames.rs @@ -0,0 +1,315 @@ +//! The workshop socket frame vocabulary: inbound frames (client to +//! server) first, outbound frames (server to client) and HTTP error +//! envelopes second. + +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +/// The inbound model selection: `{"type":"select_model","model":"..."}`. +/// +/// `model` is the retained catalog id to select; the key itself is +/// required, so a frame that omits it is malformed rather than an empty +/// selection. The session routes on the envelope's `type` and +/// deserializes the body with serde, which ignores the envelope tag and +/// the optional `id` the session echoes on a refusal. Like every inbound +/// frame it takes no delivery classification, because the server pushes +/// none. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[non_exhaustive] +pub struct SelectModelFrame { + /// The catalog id to select for chat. + pub model: String, +} + +/// The inbound profile selection: `{"type":"switch_profile","name":...}`. +/// +/// `name` is a profile name, or `null` to select no profile; the key +/// itself is required, so a frame that omits it is malformed rather than +/// a no-profile selection. The session routes on the envelope's `type` +/// and deserializes the body with serde, which ignores the envelope tag +/// and the optional `id` the session echoes on a refusal. Like every +/// inbound frame it takes no delivery classification, because the server +/// pushes none. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[non_exhaustive] +pub struct SwitchProfileFrame { + /// The profile to select, or `None` (`null` on the wire) for no + /// profile. + #[serde(deserialize_with = "required_nullable")] + pub name: Option, +} + +/// Deserializes a nullable string whose key must be present: serde's +/// derive treats a missing `Option` field as `None` unless the field +/// names its own deserializer, and this field names one, so an absent +/// `name` fails instead of selecting no profile. +fn required_nullable<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + Option::::deserialize(deserializer) +} + +/// The operator's message, sent at any time. Wire type `input_response`. +/// +/// `{"type":"input_response","text":"..."}` goes to the session's run +/// whenever the operator sends it: it answers the agent while the agent +/// waits on its inbox, and steers the turn while the agent works. +/// +/// The session routes on the envelope's `type` and deserializes the body +/// with serde, which ignores the envelope tag itself. `text` is the +/// operator's input, byte-exact as typed. Like every inbound frame it +/// takes no delivery classification, because the server pushes none. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct InputResponse { + /// The operator's text, byte-exact as typed. + pub text: String, +} + +/// One status bar update: what the bar should show right now. +/// +/// Every update is a complete snapshot, so a lagging receiver loses nothing +/// by skipping intermediates. `label` is the short text rendered in the +/// status bar; `description` is the longer tooltip shown on hover. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct StatusBarUpdate { + /// Short text rendered in the status bar. + pub label: String, + /// Longer text shown as the bar's tooltip. + pub description: String, + /// Whether work is in flight: the status bar shows its indeterminate + /// barberpole while this is set. The text in `label` says what the + /// work is; there is no fraction on the wire. + pub busy: bool, + /// How loudly the update speaks; the UI ignores `Debug` updates. + pub severity: Severity, + /// Which subsystem is active, driving the bar's activity indicator. + pub activity: Activity, +} + +impl StatusBarUpdate { + /// The update as a wire frame: its own fields plus `"type": "status"`. + #[must_use] + pub fn frame(&self) -> StatusFrame<'_> { + StatusFrame { + kind: "status", + update: self, + } + } +} + +/// How loudly a status update speaks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Severity { + /// User-visible status text. + Info, + /// Internal instrumentation; the UI ignores it for display. + Debug, + /// A failure the user should see. + Error, +} + +/// The subsystem an update belongs to, driving the activity indicator. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Activity { + /// No specific subsystem; the activity LED stays dark. + General, + /// A model turn in flight: amber on the activity LED. + Thinking, + /// Output tokens arriving: green on the activity LED. + Generating, +} + +/// The serialized shape of one update on the socket: the update's fields +/// flattened beside `"type": "status"`, matching the workshop protocol's frame +/// taxonomy. +/// +/// Delivery: ephemeral - every update is a complete snapshot, so a +/// lagging client skips intermediates and the current status is resent +/// on reconnect. +#[derive(Debug, Serialize)] +pub struct StatusFrame<'a> { + #[serde(rename = "type")] + kind: &'static str, + #[serde(flatten)] + update: &'a StatusBarUpdate, +} + +/// One pushed model catalog. +#[derive(Debug, Clone, PartialEq)] +pub struct CatalogPush { + /// The chat-capable subset of the gateway's model array. + pub models: Vec, +} + +impl CatalogPush { + /// The push as a wire frame: `"type": "models"` beside the array. + #[must_use] + pub fn frame(&self) -> CatalogFrame<'_> { + CatalogFrame { + kind: "models", + models: &self.models, + } + } +} + +/// The serialized shape of a catalog push on the socket, matching the +/// workshop protocol's frame taxonomy. +/// +/// Delivery: ephemeral - the newest push holds the whole catalog and +/// supersedes every older one; the catalog is resent on reconnect. +#[derive(Debug, Serialize)] +pub struct CatalogFrame<'a> { + #[serde(rename = "type")] + kind: &'static str, + models: &'a [Value], +} + +/// Whether one gateway catalog row can back a chat model binding. +/// +/// This is wire semantics - it interprets the gateway's catalog shape - +/// so it sits here rather than in any one subsystem: the menu filters +/// its picker by it, and the gateway subsystem's catalog refresh reads +/// readiness from it. +#[must_use] +pub fn is_chat_capable(model: &Value) -> bool { + let has_id = model + .get("id") + .and_then(Value::as_str) + .is_some_and(|id| !id.is_empty()); + let chat_kind = match model.get("kind") { + None => true, + Some(Value::String(kind)) => kind == "chat", + Some(_) => false, + }; + has_id && chat_kind +} + +/// One pushed workbench snapshot: the server-owned Model-menu state. +/// +/// The server computes `chat_ready` - a chat-capable model available, one +/// selected, no switch in flight, gateway reachable - and the UI never +/// derives it. +/// +/// `switching` names the target when it is a profile; `switch_in_flight` +/// is true for any in-flight target, including no profile. +#[derive(Debug, Clone, PartialEq)] +pub struct WorkbenchSnapshot { + /// Every gateway profile name, in gateway order. + pub profiles: Vec, + /// The profile the gateway is serving, once known. + pub active: Option, + /// The profile a switch is loading, while one is in flight. `None` + /// when no switch runs and when the in-flight switch selects no + /// profile. + pub switching: Option, + /// Whether a switch is in flight, whatever its target. + pub switch_in_flight: bool, + /// The model chat requests go to, once one is selected. + pub selected_model: Option, + /// Whether a chat can be submitted right now. + pub chat_ready: bool, +} + +impl WorkbenchSnapshot { + /// The snapshot as a wire frame: `"type": "workbench"` beside the + /// fields, with `selected_model` shortened to `selected` on the wire. + #[must_use] + pub fn frame(&self) -> WorkbenchFrame<'_> { + WorkbenchFrame { + kind: "workbench", + profiles: &self.profiles, + active: self.active.as_deref(), + switching: self.switching.as_deref(), + switch_in_flight: self.switch_in_flight, + selected: self.selected_model.as_deref(), + chat_ready: self.chat_ready, + } + } +} + +/// The serialized shape of a workbench push on the socket, matching the +/// workshop protocol's frame taxonomy. Absent options serialize as `null`, +/// never as omitted keys: every push is the complete menu state. +/// +/// Delivery: ephemeral - every push is a complete snapshot of the menu +/// state, retained and resent on reconnect, like the catalog frame. +#[derive(Debug, Serialize)] +pub struct WorkbenchFrame<'a> { + #[serde(rename = "type")] + kind: &'static str, + profiles: &'a [String], + active: Option<&'a str>, + switching: Option<&'a str>, + switch_in_flight: bool, + selected: Option<&'a str>, + chat_ready: bool, +} + +/// A failure report answered to one inbound frame - a malformed frame, a +/// refused menu event, or an agent-session failure: +/// `{"type":"error","message":"..."}` plus the echoed request `id`. +/// +/// Delivery: durable on the workshop socket - a direct per-request reply +/// sent by the loop that owns the socket. The agent-session socket +/// additionally pushes id-less error frames for session-level failures; +/// that delivery is ephemeral and documented in `workshop-server`'s +/// `agents::wire` module. +#[derive(Debug, Serialize)] +pub struct ErrorFrame { + #[serde(rename = "type")] + kind: &'static str, + message: String, + /// The request's `id`, echoed verbatim when the request had one and + /// omitted from the wire when it did not. + #[serde(skip_serializing_if = "Option::is_none")] + id: Option, +} + +impl ErrorFrame { + /// Builds an error frame holding `message`, echoing `id` when present. + #[must_use] + pub fn new(message: String, id: Option<&Value>) -> Self { + Self { + kind: "error", + message, + id: id.cloned(), + } + } +} + +/// The opaque wire error envelope every HTTP failure answers with: +/// `{"error":{"message":"...","code":"..."}}`. +/// +/// The server maps its per-crate error types onto status codes and renders +/// this envelope; the shape is pinned here so the wire contract sits in +/// one place. Failures rendered as plain text (the asset 404) never take +/// this shape. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ErrorEnvelope { + error: EnvelopeBody, +} + +/// The envelope payload: the user-visible message and the +/// machine-readable code. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +struct EnvelopeBody { + message: String, + code: String, +} + +impl ErrorEnvelope { + /// Builds the envelope holding `message` under the machine-readable + /// `code`. + #[must_use] + pub fn new(message: impl Into, code: impl Into) -> Self { + Self { + error: EnvelopeBody { + message: message.into(), + code: code.into(), + }, + } + } +} diff --git a/crates/workshop/protocol/src/input.rs b/crates/workshop/protocol/src/input.rs deleted file mode 100644 index 9502bac9..00000000 --- a/crates/workshop/protocol/src/input.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! The agent-session input frame: the operator's message. - -use serde::Deserialize; - -/// The operator's message, sent at any time. Wire type `input_response`. -/// -/// `{"type":"input_response","text":"..."}` goes to the session's run -/// whenever the operator sends it: it answers the agent while the agent -/// waits on its inbox, and steers the turn while the agent works. -/// -/// The session routes on the envelope's `type` and deserializes the body -/// with serde, which ignores the envelope tag itself. `text` is the -/// operator's input, byte-exact as typed. Like every inbound frame it -/// takes no delivery classification, because the server pushes none. -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub struct InputResponse { - /// The operator's text, byte-exact as typed. - pub text: String, -} diff --git a/crates/workshop/protocol/src/lib.rs b/crates/workshop/protocol/src/lib.rs index 45412ea7..7ef39d22 100644 --- a/crates/workshop/protocol/src/lib.rs +++ b/crates/workshop/protocol/src/lib.rs @@ -92,16 +92,10 @@ //! every new session, so the UI boots with zero HTTP state fetches - //! is that resend promise, not a third delivery class. -mod catalog; -mod error; -mod input; -mod menu; -mod status; -mod workbench; +mod frames; -pub use catalog::{CatalogFrame, CatalogPush, is_chat_capable}; -pub use error::{ErrorEnvelope, ErrorFrame}; -pub use input::InputResponse; -pub use menu::{SelectModelFrame, SwitchProfileFrame}; -pub use status::{Activity, Severity, StatusBarUpdate, StatusFrame}; -pub use workbench::{WorkbenchFrame, WorkbenchSnapshot}; +pub use frames::{ + Activity, CatalogFrame, CatalogPush, ErrorEnvelope, ErrorFrame, InputResponse, + SelectModelFrame, Severity, StatusBarUpdate, StatusFrame, SwitchProfileFrame, WorkbenchFrame, + WorkbenchSnapshot, is_chat_capable, +}; diff --git a/crates/workshop/protocol/src/menu.rs b/crates/workshop/protocol/src/menu.rs deleted file mode 100644 index 0bb9edc3..00000000 --- a/crates/workshop/protocol/src/menu.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Inbound Model-menu frames: the model and profile selection events. - -use serde::{Deserialize, Deserializer}; - -/// The inbound model selection: `{"type":"select_model","model":"..."}`. -/// -/// `model` is the retained catalog id to select; the key itself is -/// required, so a frame that omits it is malformed rather than an empty -/// selection. The session routes on the envelope's `type` and -/// deserializes the body with serde, which ignores the envelope tag and -/// the optional `id` the session echoes on a refusal. Like every inbound -/// frame it takes no delivery classification, because the server pushes -/// none. -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -#[non_exhaustive] -pub struct SelectModelFrame { - /// The catalog id to select for chat. - pub model: String, -} - -/// The inbound profile selection: `{"type":"switch_profile","name":...}`. -/// -/// `name` is a profile name, or `null` to select no profile; the key -/// itself is required, so a frame that omits it is malformed rather than -/// a no-profile selection. The session routes on the envelope's `type` -/// and deserializes the body with serde, which ignores the envelope tag -/// and the optional `id` the session echoes on a refusal. Like every -/// inbound frame it takes no delivery classification, because the server -/// pushes none. -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -#[non_exhaustive] -pub struct SwitchProfileFrame { - /// The profile to select, or `None` (`null` on the wire) for no - /// profile. - #[serde(deserialize_with = "required_nullable")] - pub name: Option, -} - -/// Deserializes a nullable string whose key must be present: serde's -/// derive treats a missing `Option` field as `None` unless the field -/// names its own deserializer, and this field names one, so an absent -/// `name` fails instead of selecting no profile. -fn required_nullable<'de, D>(deserializer: D) -> Result, D::Error> -where - D: Deserializer<'de>, -{ - Option::::deserialize(deserializer) -} diff --git a/crates/workshop/protocol/src/status.rs b/crates/workshop/protocol/src/status.rs deleted file mode 100644 index dc9eea32..00000000 --- a/crates/workshop/protocol/src/status.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! Status-bar frames: the `{"type":"status",...}` updates. - -use serde::Serialize; - -/// One status bar update: what the bar should show right now. -/// -/// Every update is a complete snapshot, so a lagging receiver loses nothing -/// by skipping intermediates. `label` is the short text rendered in the -/// status bar; `description` is the longer tooltip shown on hover. -#[derive(Debug, Clone, PartialEq, Serialize)] -pub struct StatusBarUpdate { - /// Short text rendered in the status bar. - pub label: String, - /// Longer text shown as the bar's tooltip. - pub description: String, - /// Whether work is in flight: the status bar shows its indeterminate - /// barberpole while this is set. The text in `label` says what the - /// work is; there is no fraction on the wire. - pub busy: bool, - /// How loudly the update speaks; the UI ignores `Debug` updates. - pub severity: Severity, - /// Which subsystem is active, driving the bar's activity indicator. - pub activity: Activity, -} - -impl StatusBarUpdate { - /// The update as a wire frame: its own fields plus `"type": "status"`. - #[must_use] - pub fn frame(&self) -> StatusFrame<'_> { - StatusFrame { - kind: "status", - update: self, - } - } -} - -/// How loudly a status update speaks. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum Severity { - /// User-visible status text. - Info, - /// Internal instrumentation; the UI ignores it for display. - Debug, - /// A failure the user should see. - Error, -} - -/// The subsystem an update belongs to, driving the activity indicator. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum Activity { - /// No specific subsystem; the activity LED stays dark. - General, - /// A model turn in flight: amber on the activity LED. - Thinking, - /// Output tokens arriving: green on the activity LED. - Generating, -} - -/// The serialized shape of one update on the socket: the update's fields -/// flattened beside `"type": "status"`, matching the workshop protocol's frame -/// taxonomy. -/// -/// Delivery: ephemeral - every update is a complete snapshot, so a -/// lagging client skips intermediates and the current status is resent -/// on reconnect. -#[derive(Debug, Serialize)] -pub struct StatusFrame<'a> { - #[serde(rename = "type")] - kind: &'static str, - #[serde(flatten)] - update: &'a StatusBarUpdate, -} diff --git a/crates/workshop/protocol/src/workbench.rs b/crates/workshop/protocol/src/workbench.rs deleted file mode 100644 index aa11ede6..00000000 --- a/crates/workshop/protocol/src/workbench.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! Workbench frames: the `{"type":"workbench",...}` menu snapshots. - -use serde::Serialize; - -/// One pushed workbench snapshot: the server-owned Model-menu state. -/// -/// The server computes `chat_ready` - a chat-capable model available, one -/// selected, no switch in flight, gateway reachable - and the UI never -/// derives it. -/// -/// `switching` names the target when it is a profile; `switch_in_flight` -/// is true for any in-flight target, including no profile. -#[derive(Debug, Clone, PartialEq)] -pub struct WorkbenchSnapshot { - /// Every gateway profile name, in gateway order. - pub profiles: Vec, - /// The profile the gateway is serving, once known. - pub active: Option, - /// The profile a switch is loading, while one is in flight. `None` - /// when no switch runs and when the in-flight switch selects no - /// profile. - pub switching: Option, - /// Whether a switch is in flight, whatever its target. - pub switch_in_flight: bool, - /// The model chat requests go to, once one is selected. - pub selected_model: Option, - /// Whether a chat can be submitted right now. - pub chat_ready: bool, -} - -impl WorkbenchSnapshot { - /// The snapshot as a wire frame: `"type": "workbench"` beside the - /// fields, with `selected_model` shortened to `selected` on the wire. - #[must_use] - pub fn frame(&self) -> WorkbenchFrame<'_> { - WorkbenchFrame { - kind: "workbench", - profiles: &self.profiles, - active: self.active.as_deref(), - switching: self.switching.as_deref(), - switch_in_flight: self.switch_in_flight, - selected: self.selected_model.as_deref(), - chat_ready: self.chat_ready, - } - } -} - -/// The serialized shape of a workbench push on the socket, matching the -/// workshop protocol's frame taxonomy. Absent options serialize as `null`, -/// never as omitted keys: every push is the complete menu state. -/// -/// Delivery: ephemeral - every push is a complete snapshot of the menu -/// state, retained and resent on reconnect, like the catalog frame. -#[derive(Debug, Serialize)] -pub struct WorkbenchFrame<'a> { - #[serde(rename = "type")] - kind: &'static str, - profiles: &'a [String], - active: Option<&'a str>, - switching: Option<&'a str>, - switch_in_flight: bool, - selected: Option<&'a str>, - chat_ready: bool, -} diff --git a/crates/workshop/protocol/tests/it/frames.rs b/crates/workshop/protocol/tests/it/frames.rs index 6e47416b..70a3426a 100644 --- a/crates/workshop/protocol/tests/it/frames.rs +++ b/crates/workshop/protocol/tests/it/frames.rs @@ -1,221 +1,169 @@ -//! Per-frame wire-shape pins: each test asserts one frame against an -//! exact `serde_json::json!` literal, so a field rename, retype, or -//! optionality change fails here before it reaches a socket. +//! Non-baseline wire-shape pins and inbound parse refusals. Baseline +//! frame shapes are pinned against `tests/fixtures/workshop-frames.json` +//! in `workshop_frames.rs`. use workshop_protocol::{ - Activity, CatalogPush, ErrorEnvelope, ErrorFrame, InputResponse, Severity, StatusBarUpdate, - SwitchProfileFrame, WorkbenchSnapshot, + Activity, ErrorEnvelope, ErrorFrame, InputResponse, SelectModelFrame, Severity, + StatusBarUpdate, SwitchProfileFrame, WorkbenchSnapshot, }; -/// Builds a minimal update with the given label. -fn stub(label: impl Into) -> StatusBarUpdate { - StatusBarUpdate { - label: label.into(), - description: String::new(), - busy: false, - severity: Severity::Info, - activity: Activity::General, - } -} - -#[test] -fn a_status_update_serializes_as_a_status_frame() { - let frame = serde_json::to_value(stub("Ready").frame()).expect("the frame serializes"); - assert_eq!( - frame, - serde_json::json!({ - "type": "status", - "label": "Ready", - "description": "", - "busy": false, - "severity": "info", - "activity": "general", - }), - "the wire shape matches the workshop protocol's frame taxonomy" - ); -} - -#[test] -fn busy_and_the_remaining_variants_serialize() { - let update = StatusBarUpdate { - busy: true, - severity: Severity::Error, - activity: Activity::Thinking, - ..stub("Working") - }; - let frame = serde_json::to_value(update.frame()).expect("the frame serializes"); - assert_eq!( - frame["busy"], - serde_json::json!(true), - "the busy flag appears on the frame as a plain boolean, never a progress object" - ); - assert!( - frame.get("progress").is_none(), - "the determinate progress object is gone from the wire" - ); - assert_eq!(frame["severity"], "error"); - assert_eq!(frame["activity"], "thinking"); - // Debug serializes too; the UI, not the bus, ignores it. - let debug = serde_json::to_value( - StatusBarUpdate { - severity: Severity::Debug, - activity: Activity::Generating, - ..stub("x") - } - .frame(), - ) - .expect("the frame serializes"); - assert_eq!(debug["severity"], "debug"); - assert_eq!(debug["activity"], "generating"); -} +/// Non-baseline `StatusBarUpdate` variants. +const STATUS_VARIANT_CASES: &[(&str, bool, Severity, Activity, &str, &str)] = { + use Activity as A; + use Severity as S; + &[ + ( + "err_think", + true, + S::Error, + A::Thinking, + "error", + "thinking", + ), + ( + "dbg_gen", + false, + S::Debug, + A::Generating, + "debug", + "generating", + ), + ("info_think", true, S::Info, A::Thinking, "info", "thinking"), + ( + "err_gen", + false, + S::Error, + A::Generating, + "error", + "generating", + ), + ("dbg_busy", true, S::Debug, A::General, "debug", "general"), + ] +}; -#[test] -fn a_catalog_push_serializes_as_a_models_frame() { - let push = CatalogPush { - models: vec![serde_json::json!({"id": "test-model", "object": "model"})], - }; - let frame = serde_json::to_value(push.frame()).expect("the frame serializes"); - assert_eq!( - frame, - serde_json::json!({ - "type": "models", - "models": [{"id": "test-model", "object": "model"}], - }), - "the wire shape matches the workshop protocol's frame taxonomy" - ); -} +/// Malformed inbound payloads: `(label, frame_kind, raw_json)`. +const INBOUND_REFUSAL_CASES: &[(&str, &str, &str)] = &[ + ("input_no_text", "input", r#"{"type":"input_response"}"#), + ( + "input_int_text", + "input", + r#"{"type":"input_response","text":42}"#, + ), + ("switch_no_name", "switch", r#"{"type":"switch_profile"}"#), + ( + "switch_int_name", + "switch", + r#"{"type":"switch_profile","name":7}"#, + ), + ("select_no_model", "select", r#"{"type":"select_model"}"#), + ( + "select_null", + "select", + r#"{"type":"select_model","model":null}"#, + ), + ( + "select_int", + "select", + r#"{"type":"select_model","model":7}"#, + ), +]; #[test] -fn a_workbench_snapshot_serializes_as_a_workbench_frame() { - let snapshot = WorkbenchSnapshot { - profiles: vec!["main".to_string(), "coding".to_string()], - active: Some("main".to_string()), - switching: None, - switch_in_flight: false, - selected_model: Some("claude-sonnet-4-6".to_string()), - chat_ready: true, - }; - let frame = serde_json::to_value(snapshot.frame()).expect("the frame serializes"); - assert_eq!( - frame, - serde_json::json!({ - "type": "workbench", - "profiles": ["main", "coding"], - "active": "main", - "switching": null, - "switch_in_flight": false, - "selected": "claude-sonnet-4-6", - "chat_ready": true, - }), - "the wire shape matches the workshop protocol's frame taxonomy" - ); +fn status_frame_variants_serialize_busy_severity_and_activity() { + for &(label, busy, severity, activity, wire_severity, wire_activity) in STATUS_VARIANT_CASES { + let update = StatusBarUpdate { + label: label.to_string(), + description: String::new(), + busy, + severity, + activity, + }; + let frame = serde_json::to_value(update.frame()).expect("status frame serializes"); + assert_eq!(frame["busy"], serde_json::json!(busy), "{label}: busy"); + assert!(frame.get("progress").is_none(), "{label}: no progress"); + assert_eq!(frame["severity"], wire_severity, "{label}: severity"); + assert_eq!(frame["activity"], wire_activity, "{label}: activity"); + } } #[test] -fn a_switch_to_no_profile_is_visible_on_the_workbench_frame() { - let snapshot = WorkbenchSnapshot { - profiles: vec!["main".to_string()], - active: Some("main".to_string()), - switching: None, - switch_in_flight: true, - selected_model: Some("claude-sonnet-4-6".to_string()), - chat_ready: false, - }; - let frame = serde_json::to_value(snapshot.frame()).expect("the frame serializes"); - assert_eq!( - frame["switching"], - serde_json::Value::Null, - "a switch to no profile names no target" - ); - assert_eq!( - frame["switch_in_flight"], true, - "the frame still reports the switch in flight, independent of the target name" - ); +fn workbench_in_flight_switches_preserve_target_and_flag() { + for (label, switching) in [ + ("to_no_profile", None), + ("to_named_profile", Some("coding")), + ] { + let snapshot = WorkbenchSnapshot { + profiles: vec!["main".to_string()], + active: Some("main".to_string()), + switching: switching.map(str::to_string), + switch_in_flight: true, + selected_model: Some("claude-sonnet-4-6".to_string()), + chat_ready: false, + }; + let frame = serde_json::to_value(snapshot.frame()).expect("workbench frame serializes"); + assert_eq!( + frame["switching"], + switching.map_or(serde_json::Value::Null, serde_json::Value::from), + "{label}: switching" + ); + assert_eq!(frame["switch_in_flight"], true, "{label}: switch_in_flight"); + assert_eq!(frame["chat_ready"], false, "{label}: chat_ready"); + } } #[test] -fn an_input_response_parses_its_body_byte_exact_ignoring_the_envelope() { +fn inbound_frames_accept_valid_variants_and_refuse_malformed_payloads() { let gnarly = "line1\r\nline2 \"quoted\" {\"text\":\"decoy\"} \\slash 🦀"; - let response: InputResponse = serde_json::from_value(serde_json::json!({ - "type": "input_response", - "text": gnarly, - })) - .expect("the frame parses with its envelope tag present"); - assert_eq!( - response.text, gnarly, - "the operator's text survives the wire byte-exact" - ); -} + let response: InputResponse = + serde_json::from_value(serde_json::json!({"type": "input_response", "text": gnarly})) + .expect("input_response parses"); + assert_eq!(response.text, gnarly); -#[test] -fn an_input_response_without_text_is_refused() { - assert!( - serde_json::from_value::(serde_json::json!({ - "type": "input_response", - })) - .is_err(), - "a message must carry its text" - ); -} - -#[test] -fn a_switch_profile_frame_accepts_a_name_or_null_and_refuses_the_rest() { - let named: SwitchProfileFrame = serde_json::from_value(serde_json::json!({ - "type": "switch_profile", - "name": "beta", - "id": 4, - })) - .expect("a named selection parses with its envelope present"); + let named: SwitchProfileFrame = serde_json::from_value( + serde_json::json!({"type": "switch_profile", "name": "beta", "id": 4}), + ) + .expect("named switch_profile parses"); assert_eq!(named.name.as_deref(), Some("beta")); let none: SwitchProfileFrame = serde_json::from_value(serde_json::json!({"type": "switch_profile", "name": null})) .expect("null selects no profile"); - assert_eq!(none.name, None, "a null name is the no-profile selection"); + assert_eq!(none.name, None); - assert!( - serde_json::from_value::(serde_json::json!({ - "type": "switch_profile" - })) - .is_err(), - "an absent name is a malformed frame, not a no-profile selection" - ); - assert!( - serde_json::from_value::(serde_json::json!({ - "type": "switch_profile", - "name": 7, - })) - .is_err(), - "a non-string name is refused" - ); + for &(label, kind, raw) in INBOUND_REFUSAL_CASES { + let refused = match kind { + "input" => serde_json::from_str::(raw).is_err(), + "switch" => serde_json::from_str::(raw).is_err(), + "select" => serde_json::from_str::(raw).is_err(), + _ => unreachable!("unknown kind {kind}"), + }; + assert!(refused, "{label}: malformed payload must be refused"); + } } #[test] -fn an_error_frame_serializes_with_and_without_the_echoed_id() { +fn error_frame_omits_absent_id_and_error_envelope_wraps_message_and_code() { let untagged = serde_json::to_value(ErrorFrame::new("Gateway unreachable".to_string(), None)) - .expect("the frame serializes"); + .expect("untagged error frame serializes"); assert_eq!( untagged, serde_json::json!({"type": "error", "message": "Gateway unreachable"}) ); + let id = serde_json::json!(7); let tagged = serde_json::to_value(ErrorFrame::new( "Gateway unreachable".to_string(), Some(&id), )) - .expect("the frame serializes"); + .expect("tagged error frame serializes"); assert_eq!( tagged, serde_json::json!({"type": "error", "message": "Gateway unreachable", "id": 7}) ); -} -#[test] -fn an_error_envelope_serializes_as_message_and_code_under_error() { let envelope = ErrorEnvelope::new("file cannot be read", "read_file"); assert_eq!( - serde_json::to_value(&envelope).expect("the envelope serializes"), - serde_json::json!({"error": {"message": "file cannot be read", "code": "read_file"}}), - "the wire shape matches the envelope the server has always answered with" + serde_json::to_value(&envelope).expect("envelope serializes"), + serde_json::json!({"error": {"message": "file cannot be read", "code": "read_file"}}) ); } diff --git a/crates/workshop/registry/src/push-tests.rs b/crates/workshop/registry/src/push-tests.rs index a2ae67ac..7c48a63d 100644 --- a/crates/workshop/registry/src/push-tests.rs +++ b/crates/workshop/registry/src/push-tests.rs @@ -7,13 +7,13 @@ use std::sync::{Arc, Mutex, PoisonError}; use tokio::sync::broadcast; +use workshop_protocol::StatusBarUpdate; use super::*; use crate::{ CatalogSinkAdapter, MenuSinkAdapter, Registration, StatusSink, StatusSinkAdapter, traits::{CatalogSink, MenuSink}, }; -use workshop_protocol::StatusBarUpdate; /// A registry wired with recording sinks: status and catalog frames go /// to broadcast receivers, menu mutator calls to a shared log. @@ -89,121 +89,77 @@ fn menu_calls(recording: &Recording) -> Vec { .clone() } -#[tokio::test] -async fn a_status_update_reaches_the_sink_at_info_severity() { - let mut recording = wired(); - recording.push.push_status_update( - "Connected to gateway", - "the probe answered", - Activity::General, - ); - let update = recording - .status_rx - .recv() - .await - .expect("the update reaches the sink"); - assert_eq!( - update, - StatusBarUpdate { - label: "Connected to gateway".to_string(), - description: "the probe answered".to_string(), - busy: false, - severity: Severity::Info, - activity: Activity::General, - } - ); -} - -#[tokio::test] -async fn a_failure_reaches_the_sink_at_error_severity() { - let mut recording = wired(); - recording - .push - .push_failure("Connection lost", "the gateway hung up", Activity::General); - let update = recording - .status_rx - .recv() - .await - .expect("the update reaches the sink"); - assert_eq!( - update, - StatusBarUpdate { - label: "Connection lost".to_string(), - description: "the gateway hung up".to_string(), - busy: false, - severity: Severity::Error, - activity: Activity::General, - } - ); -} - -#[tokio::test] -async fn an_activity_pulse_reaches_the_sink_at_debug_severity() { - let mut recording = wired(); - recording.push.push_activity( - "Streaming response...", - "a gateway response chunk", - Activity::Generating, - ); - let update = recording - .status_rx - .recv() - .await - .expect("the update reaches the sink"); - assert_eq!( - update, - StatusBarUpdate { - label: "Streaming response...".to_string(), - description: "a gateway response chunk".to_string(), - busy: false, - severity: Severity::Debug, - activity: Activity::Generating, - } - ); +/// Status-push intent under test. +#[derive(Clone, Copy)] +enum StatusIntent { + Update, + Failure, + Activity, + Busy, + Idle, } -#[tokio::test] -async fn busy_reaches_the_sink_as_an_info_frame_with_the_busy_flag_set() { - let mut recording = wired(); - recording - .push - .push_busy("Downloading model", "ggml-large-v3.bin", Activity::General); - let update = recording - .status_rx - .recv() - .await - .expect("the update reaches the sink"); - assert_eq!( - update, - StatusBarUpdate { - label: "Downloading model".to_string(), - description: "ggml-large-v3.bin".to_string(), - busy: true, - severity: Severity::Info, - activity: Activity::General, - } - ); -} +/// `(case_label, intent, activity, expected_busy, expected_severity)`. +const STATUS_INTENT_CASES: &[(&str, StatusIntent, Activity, bool, Severity)] = { + use Activity as A; + use Severity as S; + use StatusIntent as I; + &[ + ("update_general", I::Update, A::General, false, S::Info), + ("failure_general", I::Failure, A::General, false, S::Error), + ("activity_gen", I::Activity, A::Generating, false, S::Debug), + ("activity_think", I::Activity, A::Thinking, false, S::Debug), + ("busy_general", I::Busy, A::General, true, S::Info), + ("busy_thinking", I::Busy, A::Thinking, true, S::Info), + ("idle_resting", I::Idle, A::General, false, S::Info), + ] +}; #[tokio::test] -async fn idle_reaches_the_sink_as_the_resting_update() { +async fn every_status_intent_reaches_the_sink_with_its_wire_fields() { let mut recording = wired(); - recording.push.push_idle(); - let update = recording - .status_rx - .recv() - .await - .expect("the update reaches the sink"); - assert_eq!( - update, - StatusBarUpdate { - label: "Ready".to_string(), - description: "idle".to_string(), - busy: false, - severity: Severity::Info, - activity: Activity::General, - } - ); + for &(case_label, intent, activity, busy, severity) in STATUS_INTENT_CASES { + let (exp_label, exp_desc) = match intent { + StatusIntent::Update => { + recording + .push + .push_status_update(case_label, "detail", activity); + (case_label, "detail") + } + StatusIntent::Failure => { + recording.push.push_failure(case_label, "detail", activity); + (case_label, "detail") + } + StatusIntent::Activity => { + recording.push.push_activity(case_label, "detail", activity); + (case_label, "detail") + } + StatusIntent::Busy => { + recording.push.push_busy(case_label, "detail", activity); + (case_label, "detail") + } + StatusIntent::Idle => { + recording.push.push_idle(); + ("Ready", "idle") + } + }; + let update = recording + .status_rx + .recv() + .await + .unwrap_or_else(|err| panic!("{case_label}: update reaches sink: {err}")); + assert_eq!( + update, + StatusBarUpdate { + label: exp_label.to_string(), + description: exp_desc.to_string(), + busy, + severity, + activity, + }, + "{case_label}" + ); + } } #[tokio::test] diff --git a/crates/workshop/registry/src/push.rs b/crates/workshop/registry/src/push.rs index 6529cfc9..db24f52a 100644 --- a/crates/workshop/registry/src/push.rs +++ b/crates/workshop/registry/src/push.rs @@ -14,6 +14,7 @@ //! Every intent degrades to a no-op while its sink slot is empty, so a //! producer spawned before its subsystem registers never fails. +use serde_json::Value; use workshop_protocol::{Activity, Severity, StatusBarUpdate}; use crate::Registry; @@ -96,7 +97,7 @@ impl Push { /// entries. The single choke point for catalog publishes: the menu /// revalidates its selection against the new catalog and republishes /// the workbench snapshot when it changed. - pub fn push_models_catalog(&self, models: Vec) { + pub fn push_models_catalog(&self, models: Vec) { if let Some(catalog) = self.registry.sink::() { catalog.publish(models); } diff --git a/crates/workshop/registry/src/registry.rs b/crates/workshop/registry/src/registry.rs index 5675e827..a210da62 100644 --- a/crates/workshop/registry/src/registry.rs +++ b/crates/workshop/registry/src/registry.rs @@ -3,8 +3,10 @@ //! and push sinks as maps keyed by `TypeId`. The single downcast lives //! here; callers see typed `Option`s. -use std::any::{Any, TypeId}; +use std::any::{Any, TypeId, type_name}; use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::error::Error; use std::fmt; use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard}; @@ -37,7 +39,7 @@ impl TypeMap { self.entries .get(&TypeId::of::())? .downcast_ref::>() - .cloned() + .map(Arc::clone) } /// Registers `contribution` under `T`, replacing any previous @@ -50,13 +52,13 @@ impl TypeMap { /// Removes `contribution` from `T`'s key when it is still the /// occupant, so a stale guard never evicts a newer registration. fn remove(&mut self, contribution: &Arc) { - let current = self - .entries - .get(&TypeId::of::()) - .and_then(|entry| entry.downcast_ref::>()) - .is_some_and(|current| Arc::ptr_eq(current, contribution)); - if current { - self.entries.remove(&TypeId::of::()); + if let Entry::Occupied(entry) = self.entries.entry(TypeId::of::()) + && entry + .get() + .downcast_ref::>() + .is_some_and(|current| Arc::ptr_eq(current, contribution)) + { + entry.remove(); } } } @@ -95,6 +97,38 @@ impl fmt::Debug for Registry { } } +/// Appends `item` to an ordered contribution vector and returns the guard +/// that removes it by `Arc` identity on drop. +fn register_ordered( + slot: &Arc>>>, + item: Arc, +) -> Registration { + write(slot).push(Arc::clone(&item)); + let weak = Arc::downgrade(slot); + Registration::new(move || { + let Some(slot) = weak.upgrade() else { + return; + }; + write(&slot).retain(|current| !Arc::ptr_eq(current, &item)); + }) +} + +/// Inserts `item` into a type-keyed contribution map and returns the guard +/// that removes it on drop unless a newer occupant replaced it. +fn register_typed( + slot: &Arc>, + item: Arc, +) -> Registration { + write(slot).insert(&item); + let weak = Arc::downgrade(slot); + Registration::new(move || { + let Some(slot) = weak.upgrade() else { + return; + }; + write(&slot).remove(&item); + }) +} + impl Registry { /// An empty registry: every collection empty until its subsystems /// register. @@ -108,28 +142,14 @@ impl Registry { /// returned guard keeps the contribution alive: dropping it removes /// the registrant. pub fn register_routes(&self, registrar: Arc) -> Registration { - write(&self.routes).push(Arc::clone(®istrar)); - let routes = Arc::downgrade(&self.routes); - Registration::new(move || { - let Some(routes) = routes.upgrade() else { - return; - }; - write(&routes).retain(|current| !Arc::ptr_eq(current, ®istrar)); - }) + register_ordered(&self.routes, registrar) } /// Registers a background task; the server spawns every registrant /// with serving and stops each through its [`ShutdownHandle`](crate::ShutdownHandle) /// in the graceful-shutdown closure. pub fn register_task(&self, task: Arc) -> Registration { - write(&self.tasks).push(Arc::clone(&task)); - let tasks = Arc::downgrade(&self.tasks); - Registration::new(move || { - let Some(tasks) = tasks.upgrade() else { - return; - }; - write(&tasks).retain(|current| !Arc::ptr_eq(current, &task)); - }) + register_ordered(&self.tasks, task) } /// Registers a state handle set under its type; consumers read it @@ -139,14 +159,7 @@ impl Registry { where T: ?Sized + Send + Sync + 'static, { - write(&self.state).insert(&handles); - let state = Arc::downgrade(&self.state); - Registration::new(move || { - let Some(state) = state.upgrade() else { - return; - }; - write(&state).remove(&handles); - }) + register_typed(&self.state, handles) } /// Registers a producer sink under its trait type; the [`Push`] @@ -155,14 +168,7 @@ impl Registry { where T: ?Sized + Send + Sync + 'static, { - write(&self.sinks).insert(&sink); - let sinks = Arc::downgrade(&self.sinks); - Registration::new(move || { - let Some(sinks) = sinks.upgrade() else { - return; - }; - write(&sinks).remove(&sink); - }) + register_typed(&self.sinks, sink) } /// Every registered route contribution, in registration order. @@ -209,7 +215,7 @@ impl Registry { T: ?Sized + Send + Sync + 'static, { self.state::().ok_or(MissingContribution { - contribution: std::any::type_name::(), + contribution: type_name::(), }) } @@ -243,7 +249,7 @@ impl fmt::Display for MissingContribution { } } -impl std::error::Error for MissingContribution {} +impl Error for MissingContribution {} /// The registration guard: keeps the contribution registered while /// held. @@ -282,58 +288,7 @@ impl fmt::Debug for Registration { #[cfg(test)] mod tests { use super::*; - use crate::traits::{ - BackgroundTaskAdapter, RouteRegistrarAdapter, ShutdownHandle, StatusSink, StatusSinkAdapter, - }; - - #[test] - fn registered_state_is_served_by_type() { - let registry = Registry::new(); - let _registration = registry.register_state(Arc::new("handles".to_string())); - let handles = registry - .state::() - .expect("the registered handle set is served"); - assert_eq!(handles.as_str(), "handles"); - } - - #[test] - fn state_of_an_unregistered_type_is_none() { - let registry = Registry::new(); - let _registration = registry.register_state(Arc::new("handles".to_string())); - assert!( - registry.state::().is_none(), - "a type no subsystem registered serves nothing" - ); - } - - #[test] - fn dropping_the_registration_empties_the_key() { - let registry = Registry::new(); - let registration = registry.register_state(Arc::new("handles".to_string())); - assert!(registry.state::().is_some()); - drop(registration); - assert!( - registry.state::().is_none(), - "the key empties when the guard drops" - ); - } - - #[test] - fn route_registrants_are_served_in_registration_order() { - let registry = Registry::new(); - let first: Arc = - Arc::new(RouteRegistrarAdapter::new(axum::Router::new)); - let second: Arc = - Arc::new(RouteRegistrarAdapter::new(axum::Router::new)); - let _first_guard = registry.register_routes(Arc::clone(&first)); - let _second_guard = registry.register_routes(Arc::clone(&second)); - let routes = registry.routes(); - assert_eq!(routes.len(), 2, "both registrants are served"); - assert!( - Arc::ptr_eq(&routes[0], &first) && Arc::ptr_eq(&routes[1], &second), - "registrants are served in registration order" - ); - } + use crate::traits::{BackgroundTaskAdapter, ShutdownHandle, StatusSink, StatusSinkAdapter}; #[test] fn a_registered_task_is_served_until_its_guard_drops() { @@ -343,39 +298,44 @@ mod tests { })); let registration = registry.register_task(Arc::clone(&task)); let tasks = registry.tasks(); - assert_eq!(tasks.len(), 1, "the registered task is served"); - assert!( - Arc::ptr_eq(&tasks[0], &task), - "the served task is the registered one" - ); + assert_eq!(tasks.len(), 1); + assert!(Arc::ptr_eq(&tasks[0], &task)); drop(registration); - assert!( - registry.tasks().is_empty(), - "dropping the guard removes the task" - ); + assert!(registry.tasks().is_empty()); } #[test] - fn require_on_a_missing_key_names_the_missing_type() { + fn require_returns_a_registered_handle_and_names_a_missing_type() { let registry = Registry::new(); let error = registry .require::() - .expect_err("an unregistered type fails require"); - assert_eq!(error.contribution(), std::any::type_name::()); + .expect_err("unregistered type fails"); + assert_eq!(error.contribution(), type_name::()); assert!( error.to_string().contains("String"), - "the error message names the missing type: {error}" + "missing type: {error}" + ); + let _registration = registry.register_state(Arc::new("handles".to_string())); + assert_eq!( + registry.require::().expect("registered").as_str(), + "handles" ); } #[test] - fn a_sink_round_trips_through_its_trait_type() { + fn a_sink_round_trips_and_a_stale_guard_does_not_evict_its_replacement() { let registry = Registry::new(); - let _registration = + let first = + registry.register_sink::(Arc::new(StatusSinkAdapter::new(|_| {}))); + assert!(registry.sink::().is_some()); + let second = registry.register_sink::(Arc::new(StatusSinkAdapter::new(|_| {}))); + drop(first); assert!( registry.sink::().is_some(), - "the sink collection serves the registered trait object" + "stale guard keeps replacement" ); + drop(second); + assert!(registry.sink::().is_none()); } } diff --git a/crates/workshop/registry/src/traits.rs b/crates/workshop/registry/src/traits.rs index ff615fc1..16262df2 100644 --- a/crates/workshop/registry/src/traits.rs +++ b/crates/workshop/registry/src/traits.rs @@ -11,8 +11,8 @@ use std::fmt; use std::pin::Pin; use axum::Router; +use serde_json::Value; use tokio::sync::broadcast; - use workshop_protocol::StatusBarUpdate; /// The sealing boundary: a private empty supertrait no downstream crate @@ -84,7 +84,7 @@ impl fmt::Debug for ShutdownHandle { /// The status-bar push channel: the retained snapshot plus live /// subscription every `/ws` session forwards. Registered by -/// `workshop-status`'s `handles.rs`. +/// `workshop-status`'s `status.rs`. pub trait StatusChannel: Sealed + Send + Sync { /// Subscribes to every update sent from this call onward. fn subscribe(&self) -> broadcast::Receiver; @@ -97,7 +97,7 @@ pub trait StatusChannel: Sealed + Send + Sync { /// [`StatusBarUpdate`]s emitted by subsystems in other crates. The /// [`Push`](crate::Push) facade builds the frames; the sink only /// accepts them, so a producer in a same-tier crate never names the -/// status bus's type. Registered by `workshop-status`'s `handles.rs`. +/// status bus's type. Registered by `workshop-status`'s `status.rs`. pub trait StatusSink: Sealed + Send + Sync { /// Emits one update onto the status bus. fn emit(&self, update: StatusBarUpdate); @@ -108,7 +108,7 @@ pub trait StatusSink: Sealed + Send + Sync { /// Registered by `workshop-menu`'s `handles.rs`. pub trait CatalogSink: Sealed + Send + Sync { /// Publishes one complete model catalog snapshot. - fn publish(&self, models: Vec); + fn publish(&self, models: Vec); } /// The menu producer sink: the menu subsystem's receiving end for the @@ -218,7 +218,7 @@ pub struct CatalogSinkAdapter

{ impl

CatalogSinkAdapter

where - P: Fn(Vec) + Send + Sync, + P: Fn(Vec) + Send + Sync, { /// Builds the adapter from the bus's publish closure. #[must_use] @@ -227,13 +227,13 @@ where } } -impl

Sealed for CatalogSinkAdapter

where P: Fn(Vec) + Send + Sync {} +impl

Sealed for CatalogSinkAdapter

where P: Fn(Vec) + Send + Sync {} impl

CatalogSink for CatalogSinkAdapter

where - P: Fn(Vec) + Send + Sync, + P: Fn(Vec) + Send + Sync, { - fn publish(&self, models: Vec) { + fn publish(&self, models: Vec) { (self.publish)(models); } } diff --git a/crates/workshop/run-log/src/append.rs b/crates/workshop/run-log/src/append.rs deleted file mode 100644 index 69db0dd6..00000000 --- a/crates/workshop/run-log/src/append.rs +++ /dev/null @@ -1,236 +0,0 @@ -//! The write path: open a log, begin a run, append records, end the run. - -use std::fmt; -use std::io; -use std::path::Path; -use std::time::{SystemTime, UNIX_EPOCH}; - -use runvil::Error; - -use crate::error::LogError; -use crate::record::{Record, RunId, RunMeta, Seq}; -use crate::schema; - -/// An open run log: one connection to one Turso database holding the -/// `runs` and `records` tables. -/// -/// Every method takes `&mut self`: the effect loop is the log's one -/// writer, and exclusive access is what lets `append` read the next `seq` -/// and insert under it without a transaction. [`TursoRecorder`](crate::TursoRecorder) -/// serves several tasks and wraps the log in its own lock. -pub struct RunLog { - conn: turso::Connection, -} - -impl fmt::Debug for RunLog { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RunLog").finish_non_exhaustive() - } -} - -impl RunLog { - /// Opens the log at `path`, creating the file and the schema when - /// absent. The parent directory must already exist: this creates the - /// file, never a directory. - /// - /// # Errors - /// Returns [`LogError::Io`] when `path` is not UTF-8 (Turso addresses - /// databases by string), and [`LogError::Database`] when the database - /// cannot open the file or apply the schema. - pub async fn open(path: &Path) -> Result { - let name = path.to_str().ok_or_else(|| { - LogError::io( - format!("open {}", path.display()), - io::Error::new(io::ErrorKind::InvalidInput, "run log path must be utf-8"), - ) - })?; - Self::open_str(name).await - } - - /// Opens a log that lives only as long as this value: for tests and - /// for Hosts that keep no history. - /// - /// # Errors - /// Returns [`LogError::Database`] when the database cannot build the - /// database or apply the schema. - pub async fn in_memory() -> Result { - Self::open_str(":memory:").await - } - - async fn open_str(path: &str) -> Result { - Self::over(connect(path).await?).await - } - - /// The log over `conn`, with the schema applied. - async fn over(conn: turso::Connection) -> Result { - conn.execute_batch(schema::SCHEMA).await?; - Ok(Self { conn }) - } - - /// Opens a run of `agent`, the agent the Host launched, and returns its - /// identity. `meta.started_at` is stored as its UTC milliseconds since - /// the Unix epoch; the log stamps nothing at begin. - /// - /// # Errors - /// Returns [`LogError::Database`] when the row cannot be written. - pub async fn begin_run(&mut self, meta: RunMeta, agent: &str) -> Result { - self.conn - .execute( - schema::INSERT_RUN, - ( - agent, - meta.seed.to_string(), - i64::from(meta.flags), - meta.started_at.unix_millis(), - ), - ) - .await?; - Ok(RunId::from_raw(self.conn.last_insert_rowid())) - } - - /// Appends one record to `run` and returns the position the log - /// assigned it: one past the run's last, `0` for the first. The record - /// is stamped with the wall clock at append. - /// - /// # Errors - /// Returns [`LogError::UnknownRun`] when `run` was never begun here, - /// [`LogError::RunEnded`] when it has ended, [`LogError::Payload`] - /// when the payload does not serialize, and [`LogError::Database`] - /// when the database refuses the write. - pub async fn append(&mut self, run: RunId, record: Record) -> Result { - self.require_open(run).await?; - let seq = self.next_seq(run).await?; - let payload = serde_json::to_string(&record.payload)?; - self.conn - .execute( - schema::INSERT_RECORD, - ( - run.get(), - signed(seq.get()), - record.task_id, - i64::from(record.task_seq), - record.kind.as_str(), - record.effect_id.map(signed), - payload, - now_ms(), - ), - ) - .await?; - Ok(seq) - } - - /// Closes `run` with its `result`, stamping `ended_at` with the wall - /// clock. A run closes exactly once. `Ok` stores the final text under - /// the status `completed`. `Err` stores the error's code tag and its - /// located message under the status `canceled` when the error is a - /// cancel, and `failed` otherwise. - /// - /// # Errors - /// Returns [`LogError::UnknownRun`] when `run` was never begun here, - /// [`LogError::RunEnded`] when it has already closed, and - /// [`LogError::Database`] when the database refuses the write. - pub async fn end_run( - &mut self, - run: RunId, - result: Result, - ) -> Result<(), LogError> { - self.require_open(run).await?; - let (status, final_text, error_code, error_message) = match result { - Ok(final_text) => ("completed", Some(final_text), None, None), - Err(error) => { - let status = if error.is_canceled() { - "canceled" - } else { - "failed" - }; - let message = error.located_message(); - (status, None, Some(error.code.tag()), Some(message)) - } - }; - let changed = self - .conn - .execute( - schema::UPDATE_RUN_ENDED, - ( - run.get(), - now_ms(), - status, - final_text, - error_code, - error_message, - ), - ) - .await?; - // `require_open` saw the row open a moment ago and this value has - // the only connection, so zero changes cannot happen; the check - // keeps the exactly-once rule honest against a shared file. - if changed == 0 { - return Err(LogError::RunEnded(run)); - } - Ok(()) - } - - /// The connection, for the read side. - pub(crate) const fn conn(&self) -> &turso::Connection { - &self.conn - } - - /// Fails unless `run` exists and has not ended. - async fn require_open(&self, run: RunId) -> Result<(), LogError> { - let mut rows = self - .conn - .query(schema::SELECT_RUN_ENDED_AT, (run.get(),)) - .await?; - match rows.next().await? { - None => Err(LogError::UnknownRun(run)), - Some(row) => match row.get::>(0)? { - None => Ok(()), - Some(_) => Err(LogError::RunEnded(run)), - }, - } - } - - /// One past `run`'s last `seq`; `0` when it has no records. - async fn next_seq(&self, run: RunId) -> Result { - let mut rows = self - .conn - .query(schema::SELECT_NEXT_SEQ, (run.get(),)) - .await?; - let next = match rows.next().await? { - Some(row) => row.get::(0)?, - None => 0, - }; - u64::try_from(next) - .map(Seq::from_raw) - .map_err(|_| LogError::Corrupt(format!("expected a non-negative seq, found {next}"))) - } -} - -/// One connection to the database at `path`, which Turso creates when -/// absent. -async fn connect(path: &str) -> Result { - let database = turso::Builder::new_local(path).build().await?; - Ok(database.connect()?) -} - -/// A `u64` as the `i64` SQLite stores: the same bits, so the round trip -/// through [`unsigned`] is lossless. Values past `i64::MAX` read as -/// negative in raw SQL, which nothing here does. -const fn signed(value: u64) -> i64 { - i64::from_le_bytes(value.to_le_bytes()) -} - -/// The inverse of [`signed`]. -pub(crate) const fn unsigned(value: i64) -> u64 { - u64::from_le_bytes(value.to_le_bytes()) -} - -/// The wall clock as UTC milliseconds since the Unix epoch; `0` on a clock -/// set before the epoch, which is a display column's problem. -fn now_ms() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .ok() - .and_then(|elapsed| i64::try_from(elapsed.as_millis()).ok()) - .unwrap_or(0) -} diff --git a/crates/workshop/run-log/src/lib.rs b/crates/workshop/run-log/src/lib.rs index cf796033..957f2205 100644 --- a/crates/workshop/run-log/src/lib.rs +++ b/crates/workshop/run-log/src/lib.rs @@ -47,14 +47,12 @@ //! `AgentRecorder` a launch gets from `TursoRecorder::for_agent` is the //! only `RunRecorder` here, and it writes its agent at `begin_run`. -mod append; mod error; -mod read; +mod log; mod record; mod recorder; -mod schema; -pub use append::RunLog; pub use error::LogError; +pub use log::RunLog; pub use record::{Record, RecordFilter, RecordKind, RunId, RunMeta, RunRow, Seq, StoredRecord}; pub use recorder::{AgentRecorder, TursoRecorder}; diff --git a/crates/workshop/run-log/src/log.rs b/crates/workshop/run-log/src/log.rs new file mode 100644 index 00000000..a223f59d --- /dev/null +++ b/crates/workshop/run-log/src/log.rs @@ -0,0 +1,441 @@ +//! The run log: its Turso tables, the write path (open a log, begin a +//! run, append records, end the run), and the read path (one run's row +//! and its records, whole or sliced by kind). +//! +//! Two tables. `runs` holds one row per run: written at `begin_run`, +//! closed exactly once at `end_run` when `ended_at` and the result +//! columns fill. `status` is `completed`, `failed`, or `canceled`. A +//! completed run fills `final_text`; a failed or canceled run fills +//! `error_code` with its error's `ErrorCode::tag` and `error_message` +//! with its located message. `records` holds, per run, every effect, +//! answer, and event in effect-loop order. `seq` is the loop's order, +//! not the clock's; `at` is the wall clock at append, kept for display +//! only. `(task_id, task_seq)` is the record's `Provenance`, stored +//! beside the payload. +//! +//! Every integer that is a `u64` in Rust (`effect_id`) is stored as its +//! two's-complement `i64` reinterpretation, since SQLite integers are +//! signed; see [`signed`] and [`unsigned`]. `seed` is the run's 32-byte +//! seed as 64 lowercase hex characters. `task_id` is the Engine's +//! hierarchical task path (`0`, `0.2`, `0.2.1`) stored as text, since a +//! path of unbounded depth has no integer form. Timestamps are UTC +//! milliseconds since the Unix epoch. + +use std::fmt; +use std::io; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +use runvil::{Error, ErrorCode, Timestamp}; + +use crate::error::LogError; +use crate::record::{Record, RecordFilter, RecordKind, RunId, RunMeta, RunRow, Seq, StoredRecord}; + +/// The DDL, idempotent so an existing file opens without change. +const SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS runs ( + run_id INTEGER PRIMARY KEY, + agent TEXT NOT NULL, + seed TEXT NOT NULL, + flags INTEGER NOT NULL, + started_at INTEGER NOT NULL, + ended_at INTEGER, + status TEXT CHECK (status IN ('completed', 'failed', 'canceled')), + final_text TEXT, + error_code TEXT, + error_message TEXT +); + +CREATE TABLE IF NOT EXISTS records ( + run_id INTEGER NOT NULL REFERENCES runs (run_id), + seq INTEGER NOT NULL, + task_id TEXT NOT NULL, + task_seq INTEGER NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('effect', 'answer', 'event')), + effect_id INTEGER, + payload TEXT NOT NULL, + at INTEGER NOT NULL, + PRIMARY KEY (run_id, seq) +); +"; + +/// Opens a run: every column of `runs` that `begin_run` knows. +const INSERT_RUN: &str = "INSERT INTO runs \ + (agent, seed, flags, started_at) \ + VALUES (?1, ?2, ?3, ?4)"; + +/// Whether a run exists and whether it has ended: one row with `ended_at`. +const SELECT_RUN_ENDED_AT: &str = "SELECT ended_at FROM runs WHERE run_id = ?1"; + +/// The next `seq` for a run: one past its maximum, `0` when it has none. +const SELECT_NEXT_SEQ: &str = "SELECT COALESCE(MAX(seq), -1) + 1 FROM records WHERE run_id = ?1"; + +/// Appends one record. +const INSERT_RECORD: &str = "INSERT INTO records \ + (run_id, seq, task_id, task_seq, kind, effect_id, payload, at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)"; + +/// Closes a run. The `ended_at IS NULL` guard makes a second close a +/// no-op the caller detects through the change count. +const UPDATE_RUN_ENDED: &str = "UPDATE runs SET \ + ended_at = ?2, status = ?3, final_text = ?4, error_code = ?5, error_message = ?6 \ + WHERE run_id = ?1 AND ended_at IS NULL"; + +/// One run row, columns in [`RunLog::run`]'s order. +const SELECT_RUN: &str = "SELECT \ + agent, seed, flags, started_at, \ + ended_at, status, final_text, error_code, error_message \ + FROM runs WHERE run_id = ?1"; + +/// A run's records, newest first by `seq`, optionally one kind only +/// (`?2` null means every kind), at most `?3` of them (`-1` means all). +/// Newest first so `LIMIT` keeps the final records; the reader reverses. +/// Columns in [`RunLog::records`]'s order. +const SELECT_RECORDS: &str = "SELECT \ + seq, task_id, task_seq, kind, effect_id, payload, at \ + FROM records WHERE run_id = ?1 AND (?2 IS NULL OR kind = ?2) \ + ORDER BY seq DESC LIMIT ?3"; + +/// An open run log: one connection to one Turso database holding the +/// `runs` and `records` tables. +/// +/// Every method takes `&mut self`: the effect loop is the log's one +/// writer, and exclusive access is what lets `append` read the next `seq` +/// and insert under it without a transaction. [`TursoRecorder`](crate::TursoRecorder) +/// serves several tasks and wraps the log in its own lock. +pub struct RunLog { + conn: turso::Connection, +} + +impl fmt::Debug for RunLog { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RunLog").finish_non_exhaustive() + } +} + +impl RunLog { + /// Opens the log at `path`, creating the file and the schema when + /// absent. The parent directory must already exist: this creates the + /// file, never a directory. + /// + /// # Errors + /// Returns [`LogError::Io`] when `path` is not UTF-8 (Turso addresses + /// databases by string), and [`LogError::Database`] when the database + /// cannot open the file or apply the schema. + pub async fn open(path: &Path) -> Result { + let name = path.to_str().ok_or_else(|| { + LogError::io( + format!("open {}", path.display()), + io::Error::new(io::ErrorKind::InvalidInput, "run log path must be utf-8"), + ) + })?; + Self::open_str(name).await + } + + /// Opens a log that lives only as long as this value: for tests and + /// for Hosts that keep no history. + /// + /// # Errors + /// Returns [`LogError::Database`] when the database cannot build the + /// database or apply the schema. + pub async fn in_memory() -> Result { + Self::open_str(":memory:").await + } + + async fn open_str(path: &str) -> Result { + let database = turso::Builder::new_local(path).build().await?; + let conn = database.connect()?; + conn.execute_batch(SCHEMA).await?; + Ok(Self { conn }) + } + + /// Opens a run of `agent`, the agent the Host launched, and returns its + /// identity. `meta.started_at` is stored as its UTC milliseconds since + /// the Unix epoch; the log stamps nothing at begin. + /// + /// # Errors + /// Returns [`LogError::Database`] when the row cannot be written. + pub async fn begin_run(&mut self, meta: RunMeta, agent: &str) -> Result { + self.conn + .execute( + INSERT_RUN, + ( + agent, + meta.seed.to_string(), + i64::from(meta.flags), + meta.started_at.unix_millis(), + ), + ) + .await?; + Ok(RunId::from_raw(self.conn.last_insert_rowid())) + } + + /// Appends one record to `run` and returns the position the log + /// assigned it: one past the run's last, `0` for the first. The record + /// is stamped with the wall clock at append. + /// + /// # Errors + /// Returns [`LogError::UnknownRun`] when `run` was never begun here, + /// [`LogError::RunEnded`] when it has ended, [`LogError::Payload`] + /// when the payload does not serialize, and [`LogError::Database`] + /// when the database refuses the write. + pub async fn append(&mut self, run: RunId, record: Record) -> Result { + self.require_open(run).await?; + let seq = { + let mut rows = self.conn.query(SELECT_NEXT_SEQ, (run.get(),)).await?; + let next = match rows.next().await? { + Some(row) => row.get::(0)?, + None => 0, + }; + u64::try_from(next).map(Seq::from_raw).map_err(|_| { + LogError::Corrupt(format!("expected a non-negative seq, found {next}")) + })? + }; + let payload = serde_json::to_string(&record.payload)?; + self.conn + .execute( + INSERT_RECORD, + ( + run.get(), + signed(seq.get()), + record.task_id, + i64::from(record.task_seq), + record.kind.as_str(), + record.effect_id.map(signed), + payload, + now_ms(), + ), + ) + .await?; + Ok(seq) + } + + /// Closes `run` with its `result`, stamping `ended_at` with the wall + /// clock. A run closes exactly once. `Ok` stores the final text under + /// the status `completed`. `Err` stores the error's code tag and its + /// located message under the status `canceled` when the error is a + /// cancel, and `failed` otherwise. + /// + /// # Errors + /// Returns [`LogError::UnknownRun`] when `run` was never begun here, + /// [`LogError::RunEnded`] when it has already closed, and + /// [`LogError::Database`] when the database refuses the write. + pub async fn end_run( + &mut self, + run: RunId, + result: Result, + ) -> Result<(), LogError> { + self.require_open(run).await?; + let (status, final_text, error_code, error_message) = match result { + Ok(final_text) => ("completed", Some(final_text), None, None), + Err(error) => { + let status = if error.is_canceled() { + "canceled" + } else { + "failed" + }; + let message = error.located_message(); + (status, None, Some(error.code.tag()), Some(message)) + } + }; + let changed = self + .conn + .execute( + UPDATE_RUN_ENDED, + ( + run.get(), + now_ms(), + status, + final_text, + error_code, + error_message, + ), + ) + .await?; + // `require_open` saw the row open a moment ago and this value has + // the only connection, so zero changes cannot happen; the check + // keeps the exactly-once rule honest against a shared file. + if changed == 0 { + return Err(LogError::RunEnded(run)); + } + Ok(()) + } + + /// Reads `run`'s row. + /// + /// # Errors + /// Returns [`LogError::UnknownRun`] when `run` was never begun here, + /// [`LogError::Corrupt`] when the row does not fit the schema, and + /// [`LogError::Database`] when the database cannot read it. + pub async fn run(&self, run: RunId) -> Result { + let mut rows = self.conn.query(SELECT_RUN, (run.get(),)).await?; + let Some(row) = rows.next().await? else { + return Err(LogError::UnknownRun(run)); + }; + let seed = serde_json::from_value(serde_json::Value::String(row.get(1)?)) + .map_err(|error| LogError::Corrupt(format!("seed: {error}")))?; + let meta = RunMeta { + seed, + flags: to_u32(row.get(2)?, "flags")?, + started_at: Timestamp::from_unix_millis(row.get(3)?), + }; + let agent = row.get(0)?; + let ended_at: Option = row.get(4)?; + let result = match row.get::>(5)? { + None => None, + Some(status) => { + let final_text: Option = row.get(6)?; + let error_code: Option = row.get(7)?; + let error_message: Option = row.get(8)?; + if !matches!(status.as_str(), "completed" | "failed" | "canceled") { + return Err(LogError::Corrupt(format!( + "expected status completed, failed, or canceled, found {status:?}" + ))); + } + let code = error_code.as_deref().map(to_code).transpose()?; + // Three shapes read back: `completed` with its final text + // and no error columns, `failed` with a code other than + // `canceled` and a message, and `canceled` with the code + // `canceled` and a message. The rebuilt error has its + // code's default prose and no location or facts, since + // the stored message already ends with any location. + let outcome = match (status.as_str(), final_text, code, error_message) { + ("completed", Some(final_text), None, None) => Ok(final_text), + ("failed", None, Some(code), Some(message)) if code != ErrorCode::Canceled => { + Err(Error::new(code, message, code.prose())) + } + ("canceled", None, Some(code @ ErrorCode::Canceled), Some(message)) => { + Err(Error::new(code, message, code.prose())) + } + (status, final_text, _, error_message) => { + return Err(LogError::Corrupt(format!( + "expected result columns to match {status:?}, found final_text={final_text:?} \ + error_code={error_code:?} error_message={error_message:?}" + ))); + } + }; + Some(outcome) + } + }; + Ok(RunRow { + id: run, + meta, + agent, + ended_at, + result, + }) + } + + /// Reads the records of `run` that `filter` selects, in the order + /// [`RecordFilter`] documents. A run with nothing selected reads as + /// empty; an unknown run is refused. + /// + /// # Errors + /// Returns [`LogError::UnknownRun`] when `run` was never begun here, + /// [`LogError::Corrupt`] when a row does not fit the schema, + /// [`LogError::Payload`] when a payload does not parse, and + /// [`LogError::Database`] when the database cannot read. + pub async fn records( + &self, + run: RunId, + filter: RecordFilter, + ) -> Result, LogError> { + self.run(run).await?; + let kind = filter.kind.map(RecordKind::as_str); + let limit = filter.last.map_or(-1, i64::from); + let mut rows = self + .conn + .query(SELECT_RECORDS, (run.get(), kind, limit)) + .await?; + // The query reads newest first so `LIMIT` keeps the final + // records; oldest first is the order callers expect. + let mut records = Vec::new(); + while let Some(row) = rows.next().await? { + let kind: String = row.get(3)?; + let kind = RecordKind::parse(&kind).ok_or_else(|| { + LogError::Corrupt(format!( + "expected kind effect, answer, or event, found {kind:?}" + )) + })?; + let payload: String = row.get(5)?; + records.push(StoredRecord { + seq: Seq::from_raw(unsigned(row.get(0)?)), + at: row.get(6)?, + record: Record { + task_id: row.get(1)?, + task_seq: to_u32(row.get(2)?, "task_seq")?, + kind, + effect_id: row.get::>(4)?.map(unsigned), + payload: serde_json::from_str(&payload)?, + }, + }); + } + records.reverse(); + Ok(records) + } + + /// Every `event` record of `run` in `seq` order, the loop's order: + /// what a session view renders. + /// + /// # Errors + /// Returns [`LogError::UnknownRun`] when `run` was never begun here, + /// [`LogError::Corrupt`] when a row does not fit the schema, + /// [`LogError::Payload`] when a payload does not parse, and + /// [`LogError::Database`] when the database cannot read. + pub async fn transcript(&self, run: RunId) -> Result, LogError> { + let filter = RecordFilter { + kind: Some(RecordKind::Event), + last: None, + }; + self.records(run, filter).await + } + + /// Fails unless `run` exists and has not ended. + async fn require_open(&self, run: RunId) -> Result<(), LogError> { + let mut rows = self.conn.query(SELECT_RUN_ENDED_AT, (run.get(),)).await?; + let Some(row) = rows.next().await? else { + return Err(LogError::UnknownRun(run)); + }; + if row.get::>(0)?.is_some() { + return Err(LogError::RunEnded(run)); + } + Ok(()) + } +} + +/// A `u64` as the `i64` SQLite stores: the same bits, so the round trip +/// through [`unsigned`] is lossless. Values past `i64::MAX` read as +/// negative in raw SQL, which nothing here does. +const fn signed(value: u64) -> i64 { + i64::from_le_bytes(value.to_le_bytes()) +} + +/// The inverse of [`signed`]. +const fn unsigned(value: i64) -> u64 { + u64::from_le_bytes(value.to_le_bytes()) +} + +/// The wall clock as UTC milliseconds since the Unix epoch; `0` on a clock +/// set before the epoch, which is a display column's problem. +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|elapsed| i64::try_from(elapsed.as_millis()).ok()) + .unwrap_or(0) +} + +/// A stored `u32` column, refusing anything outside the type. +fn to_u32(value: i64, column: &str) -> Result { + u32::try_from(value) + .map_err(|_| LogError::Corrupt(format!("expected {column} to fit u32, found {value}"))) +} + +/// A stored `error_code` column, parsed as [`ErrorCode::from_tag`] reads it. +fn to_code(tag: &str) -> Result { + ErrorCode::from_tag(tag).ok_or_else(|| { + LogError::Corrupt(format!( + "expected error_code to be an ErrorCode tag, found {tag:?}" + )) + }) +} diff --git a/crates/workshop/run-log/src/read.rs b/crates/workshop/run-log/src/read.rs deleted file mode 100644 index 26151764..00000000 --- a/crates/workshop/run-log/src/read.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! The read side: one run's row and its records, whole or sliced by kind. - -use runvil::{Error, ErrorCode, RunSeed, Timestamp}; - -use crate::append::{RunLog, unsigned}; -use crate::error::LogError; -use crate::record::{Record, RecordFilter, RecordKind, RunId, RunMeta, RunRow, Seq, StoredRecord}; -use crate::schema; - -impl RunLog { - /// Reads `run`'s row. - /// - /// # Errors - /// Returns [`LogError::UnknownRun`] when `run` was never begun here, - /// [`LogError::Corrupt`] when the row does not fit the schema, and - /// [`LogError::Database`] when the database cannot read it. - pub async fn run(&self, run: RunId) -> Result { - let mut rows = self.conn().query(schema::SELECT_RUN, (run.get(),)).await?; - let Some(row) = rows.next().await? else { - return Err(LogError::UnknownRun(run)); - }; - let meta = RunMeta { - seed: to_seed(row.get::(1)?)?, - flags: to_u32(row.get(2)?, "flags")?, - started_at: Timestamp::from_unix_millis(row.get(3)?), - }; - let agent = row.get(0)?; - let ended_at: Option = row.get(4)?; - let result = match row.get::>(5)? { - None => None, - Some(status) => { - let error_code: Option = row.get(7)?; - Some(parse_result( - &status, - row.get(6)?, - error_code.as_deref(), - row.get(8)?, - )?) - } - }; - Ok(RunRow { - id: run, - meta, - agent, - ended_at, - result, - }) - } - - /// Reads the records of `run` that `filter` selects, in the order - /// [`RecordFilter`] documents. A run with nothing selected reads as - /// empty; an unknown run is refused. - /// - /// # Errors - /// Returns [`LogError::UnknownRun`] when `run` was never begun here, - /// [`LogError::Corrupt`] when a row does not fit the schema, - /// [`LogError::Payload`] when a payload does not parse, and - /// [`LogError::Database`] when the database cannot read. - pub async fn records( - &self, - run: RunId, - filter: RecordFilter, - ) -> Result, LogError> { - self.run(run).await?; - let kind = filter.kind.map(RecordKind::as_str); - let limit = filter.last.map_or(-1, i64::from); - let mut rows = self - .conn() - .query(schema::SELECT_RECORDS, (run.get(), kind, limit)) - .await?; - // The query reads newest first so `LIMIT` keeps the final - // records; oldest first is the order callers expect. - let mut records = Vec::new(); - while let Some(row) = rows.next().await? { - let kind: String = row.get(3)?; - let kind = RecordKind::parse(&kind).ok_or_else(|| { - LogError::Corrupt(format!( - "expected kind effect, answer, or event, found {kind:?}" - )) - })?; - let payload: String = row.get(5)?; - records.push(StoredRecord { - seq: Seq::from_raw(unsigned(row.get(0)?)), - at: row.get(6)?, - record: Record { - task_id: row.get(1)?, - task_seq: to_u32(row.get(2)?, "task_seq")?, - kind, - effect_id: row.get::>(4)?.map(unsigned), - payload: serde_json::from_str(&payload)?, - }, - }); - } - records.reverse(); - Ok(records) - } - - /// Every `event` record of `run` in `seq` order, the loop's order: - /// what a session view renders. - /// - /// # Errors - /// Returns [`LogError::UnknownRun`] when `run` was never begun here, - /// [`LogError::Corrupt`] when a row does not fit the schema, - /// [`LogError::Payload`] when a payload does not parse, and - /// [`LogError::Database`] when the database cannot read. - pub async fn transcript(&self, run: RunId) -> Result, LogError> { - let filter = RecordFilter { - kind: Some(RecordKind::Event), - last: None, - }; - self.records(run, filter).await - } -} - -/// A stored `u32` column, refusing anything outside the type. -fn to_u32(value: i64, column: &str) -> Result { - u32::try_from(value) - .map_err(|_| LogError::Corrupt(format!("expected {column} to fit u32, found {value}"))) -} - -/// A stored `seed` column, parsed as `RunSeed`'s serde form defines it. -fn to_seed(text: String) -> Result { - serde_json::from_value(serde_json::Value::String(text)) - .map_err(|error| LogError::Corrupt(format!("seed: {error}"))) -} - -/// A stored `error_code` column, parsed as [`ErrorCode::from_tag`] reads it. -fn to_code(tag: &str) -> Result { - ErrorCode::from_tag(tag).ok_or_else(|| { - LogError::Corrupt(format!( - "expected error_code to be an ErrorCode tag, found {tag:?}" - )) - }) -} - -/// Rebuilds a run's result from its four result columns. -/// -/// Three shapes read back: `completed` with its final text and no error -/// columns, `failed` with a code other than `canceled` and a message, and -/// `canceled` with the code `canceled` and a message. The rebuilt error -/// has its code's default prose and no location or facts, since the -/// stored message is the located message and already ends with any -/// location. -fn parse_result( - status: &str, - final_text: Option, - error_code: Option<&str>, - error_message: Option, -) -> Result, LogError> { - if !matches!(status, "completed" | "failed" | "canceled") { - return Err(LogError::Corrupt(format!( - "expected status completed, failed, or canceled, found {status:?}" - ))); - } - let code = error_code.map(to_code).transpose()?; - match (status, final_text, code, error_message) { - ("completed", Some(final_text), None, None) => Ok(Ok(final_text)), - ("failed", None, Some(code), Some(message)) if code != ErrorCode::Canceled => { - Ok(Err(Error::new(code, message, code.prose()))) - } - ("canceled", None, Some(code @ ErrorCode::Canceled), Some(message)) => { - Ok(Err(Error::new(code, message, code.prose()))) - } - (status, final_text, _, error_message) => Err(LogError::Corrupt(format!( - "expected result columns to match {status:?}, found final_text={final_text:?} \ - error_code={error_code:?} error_message={error_message:?}" - ))), - } -} diff --git a/crates/workshop/run-log/src/schema.rs b/crates/workshop/run-log/src/schema.rs deleted file mode 100644 index d05ad08e..00000000 --- a/crates/workshop/run-log/src/schema.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! The run log's tables. -//! -//! Two tables. `runs` holds one row per run: written at `begin_run`, closed -//! exactly once at `end_run` when `ended_at` and the result columns fill. -//! `status` is `completed`, `failed`, or `canceled`. A completed run fills -//! `final_text`; a failed or canceled run fills `error_code` with its -//! error's `ErrorCode::tag` and `error_message` with its located message. -//! `records` holds, per run, every effect, answer, and event in effect-loop -//! order. `seq` is the loop's order, not the clock's; `at` is the wall -//! clock at append, kept for display only. `(task_id, task_seq)` is the -//! record's `Provenance`, stored beside the payload. -//! -//! Every integer that is a `u64` in Rust (`effect_id`) is stored -//! as its two's-complement `i64` reinterpretation, since SQLite integers -//! are signed; see `append::signed` and `append::unsigned`. `seed` is the -//! run's 32-byte seed as 64 lowercase hex characters. `task_id` is the -//! Engine's hierarchical task path (`0`, `0.2`, `0.2.1`) stored as text, -//! since a path of unbounded depth has no integer form. Timestamps are UTC -//! milliseconds since the Unix epoch. - -/// The DDL, idempotent so an existing file opens without change. -pub(crate) const SCHEMA: &str = " -CREATE TABLE IF NOT EXISTS runs ( - run_id INTEGER PRIMARY KEY, - agent TEXT NOT NULL, - seed TEXT NOT NULL, - flags INTEGER NOT NULL, - started_at INTEGER NOT NULL, - ended_at INTEGER, - status TEXT CHECK (status IN ('completed', 'failed', 'canceled')), - final_text TEXT, - error_code TEXT, - error_message TEXT -); - -CREATE TABLE IF NOT EXISTS records ( - run_id INTEGER NOT NULL REFERENCES runs (run_id), - seq INTEGER NOT NULL, - task_id TEXT NOT NULL, - task_seq INTEGER NOT NULL, - kind TEXT NOT NULL CHECK (kind IN ('effect', 'answer', 'event')), - effect_id INTEGER, - payload TEXT NOT NULL, - at INTEGER NOT NULL, - PRIMARY KEY (run_id, seq) -); -"; - -/// Opens a run: every column of `runs` that `begin_run` knows. -pub(crate) const INSERT_RUN: &str = "INSERT INTO runs \ - (agent, seed, flags, started_at) \ - VALUES (?1, ?2, ?3, ?4)"; - -/// Whether a run exists and whether it has ended: one row with `ended_at`. -pub(crate) const SELECT_RUN_ENDED_AT: &str = "SELECT ended_at FROM runs WHERE run_id = ?1"; - -/// The next `seq` for a run: one past its maximum, `0` when it has none. -pub(crate) const SELECT_NEXT_SEQ: &str = - "SELECT COALESCE(MAX(seq), -1) + 1 FROM records WHERE run_id = ?1"; - -/// Appends one record. -pub(crate) const INSERT_RECORD: &str = "INSERT INTO records \ - (run_id, seq, task_id, task_seq, kind, effect_id, payload, at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)"; - -/// Closes a run. The `ended_at IS NULL` guard makes a second close a -/// no-op the caller detects through the change count. -pub(crate) const UPDATE_RUN_ENDED: &str = "UPDATE runs SET \ - ended_at = ?2, status = ?3, final_text = ?4, error_code = ?5, error_message = ?6 \ - WHERE run_id = ?1 AND ended_at IS NULL"; - -/// One run row, columns in [`crate::read`]'s order. -pub(crate) const SELECT_RUN: &str = "SELECT \ - agent, seed, flags, started_at, \ - ended_at, status, final_text, error_code, error_message \ - FROM runs WHERE run_id = ?1"; - -/// A run's records, newest first by `seq`, optionally one kind only -/// (`?2` null means every kind), at most `?3` of them (`-1` means all). -/// Newest first so `LIMIT` keeps the final records; the reader reverses. -/// Columns in [`crate::read`]'s order. -pub(crate) const SELECT_RECORDS: &str = "SELECT \ - seq, task_id, task_seq, kind, effect_id, payload, at \ - FROM records WHERE run_id = ?1 AND (?2 IS NULL OR kind = ?2) \ - ORDER BY seq DESC LIMIT ?3"; diff --git a/crates/workshop/run-log/tests/it/append.rs b/crates/workshop/run-log/tests/it/append.rs index 53289134..58c3ea00 100644 --- a/crates/workshop/run-log/tests/it/append.rs +++ b/crates/workshop/run-log/tests/it/append.rs @@ -2,38 +2,40 @@ use std::num::NonZeroU32; -use runvil::{Error, ErrorCode, ErrorFact, RunSeed, SourceLoc, Timestamp}; +use runvil::{Error, ErrorCode, ErrorFact, RunSeed, SourceLoc}; use serde_json::json; -use workshop_run_log::{LogError, Record, RecordFilter, RecordKind, RunId, RunLog, RunMeta}; - -/// Every record of a run, in loop order. -const ALL: RecordFilter = RecordFilter { - kind: None, - last: None, -}; - -/// The agent the Host launched, stored beside the Harness's metadata. -const AGENT: &str = "chat"; - -/// A run's opening row as the Harness would write it. -fn meta() -> RunMeta { - RunMeta { - seed: RunSeed::from_bytes([0xfe; 32]), - flags: 0, - started_at: Timestamp::from_unix_millis(1_700_000_000_000), - } -} - -/// One record of `kind` on task 0 at `task_seq`. -fn record(kind: RecordKind, task_seq: u32, effect_id: Option) -> Record { - Record { - task_id: "0".to_owned(), - task_seq, - kind, - effect_id, - payload: json!({ "task_seq": task_seq }), - } -} +use workshop_run_log::{LogError, RecordFilter, RecordKind, RunId, RunLog, RunMeta}; + +use crate::support::{AGENT, ALL, connect, meta, record, record_with, reopen}; + +use RecordKind::{Answer, Effect, Event}; + +type FilterCase = ( + &'static str, + Option, + Option, + &'static [(&'static str, u32)], +); + +const FILTER_CASES: &[FilterCase] = &[ + ( + "all_events", + Some(Event), + None, + &[("0", 0), ("0.0", 1), ("0.0", 0), ("0", 2)], + ), + ("all_effects", Some(Effect), None, &[("0", 1)]), + ("absent_answer", Some(Answer), None, &[]), + ("last_two_any", None, Some(2), &[("0.0", 0), ("0", 2)]), + ("last_one_event", Some(Event), Some(1), &[("0", 2)]), + ("last_zero", None, Some(0), &[]), + ( + "last_over_total", + None, + Some(10), + &[("0", 0), ("0.0", 1), ("0", 1), ("0.0", 0), ("0", 2)], + ), +]; #[tokio::test] async fn a_new_log_has_neither_a_name_nor_a_prompt_hash_column() { @@ -41,25 +43,19 @@ async fn a_new_log_has_neither_a_name_nor_a_prompt_hash_column() { let path = dir.path().join("runs.db"); drop(RunLog::open(&path).await.unwrap()); - let database = turso::Builder::new_local(path.to_str().unwrap()) - .build() - .await - .unwrap(); - let conn = database.connect().unwrap(); + let conn = connect(&path).await; let mut rows = conn.query("PRAGMA table_info(runs)", ()).await.unwrap(); let mut columns = Vec::new(); while let Some(row) = rows.next().await.unwrap() { columns.push(row.get::(1).unwrap()); } assert!( - columns.iter().any(|column| column == "agent"), - "the pragma lists the runs table's columns: {columns:?}" + columns.iter().any(|c| c == "agent"), + "runs columns: {columns:?}" ); assert!( - !columns - .iter() - .any(|column| column == "name" || column == "prompt_hash"), - "the runs table holds neither the run's name nor a prompt hash: {columns:?}" + !columns.iter().any(|c| c == "name" || c == "prompt_hash"), + "no name or prompt_hash column: {columns:?}" ); } @@ -68,15 +64,15 @@ async fn a_run_with_three_records_round_trips_through_an_in_memory_log() { let mut log = RunLog::in_memory().await.unwrap(); let run = log.begin_run(meta(), AGENT).await.unwrap(); - log.append(run, record(RecordKind::Effect, 0, Some(7))) - .await - .unwrap(); - log.append(run, record(RecordKind::Answer, 1, Some(7))) - .await - .unwrap(); - log.append(run, record(RecordKind::Event, 2, None)) - .await - .unwrap(); + for (kind, task_seq, effect_id) in [ + (RecordKind::Effect, 0, Some(7)), + (RecordKind::Answer, 1, Some(7)), + (RecordKind::Event, 2, None), + ] { + log.append(run, record(kind, task_seq, effect_id)) + .await + .unwrap(); + } let row = log.run(run).await.unwrap(); assert_eq!(row.id, run); @@ -87,16 +83,16 @@ async fn a_run_with_three_records_round_trips_through_an_in_memory_log() { let records = log.records(run, ALL).await.unwrap(); assert_eq!(records.len(), 3); - let kinds: Vec = records.iter().map(|stored| stored.record.kind).collect(); - assert_eq!( - kinds, - [RecordKind::Effect, RecordKind::Answer, RecordKind::Event] + assert!( + records + .iter() + .map(|stored| (stored.record.kind, stored.record.effect_id)) + .eq([ + (RecordKind::Effect, Some(7)), + (RecordKind::Answer, Some(7)), + (RecordKind::Event, None), + ]) ); - let effect_ids: Vec> = records - .iter() - .map(|stored| stored.record.effect_id) - .collect(); - assert_eq!(effect_ids, [Some(7), Some(7), None]); for (index, stored) in records.iter().enumerate() { let task_seq = u32::try_from(index).unwrap(); assert_eq!(stored.record.task_id, "0"); @@ -113,23 +109,22 @@ async fn seq_is_assigned_in_call_order_and_strictly_increases() { let mut seqs = Vec::new(); for task_seq in 0..5 { - let seq = log - .append(run, record(RecordKind::Event, task_seq, None)) - .await - .unwrap(); - seqs.push(seq); + seqs.push( + log.append(run, record(RecordKind::Event, task_seq, None)) + .await + .unwrap() + .get(), + ); } - let raw: Vec = seqs.iter().map(|seq| seq.get()).collect(); - assert_eq!(raw, [0, 1, 2, 3, 4]); - - let stored: Vec = log - .records(run, ALL) - .await - .unwrap() - .iter() - .map(|stored| stored.seq.get()) - .collect(); - assert_eq!(stored, raw); + assert_eq!(seqs, [0, 1, 2, 3, 4]); + assert!( + log.records(run, ALL) + .await + .unwrap() + .iter() + .map(|s| s.seq.get()) + .eq(seqs) + ); } #[tokio::test] @@ -155,66 +150,32 @@ async fn seq_is_per_run_so_two_runs_each_start_at_zero() { async fn a_filter_selects_by_kind_and_keeps_the_last_n() { let mut log = RunLog::in_memory().await.unwrap(); let run = log.begin_run(meta(), AGENT).await.unwrap(); - // Two tasks interleaved (the main walk and its first child); records - // come back in loop order, not in any one task's `task_seq` order. - let appended = [ + // Two tasks interleaved; records come back in loop order. + for (task_id, task_seq, kind) in [ ("0", 0, RecordKind::Event), ("0.0", 1, RecordKind::Event), ("0", 1, RecordKind::Effect), ("0.0", 0, RecordKind::Event), ("0", 2, RecordKind::Event), - ]; - for (task_id, task_seq, kind) in appended { - let mut record = record(kind, task_seq, None); - record.task_id = task_id.to_owned(); - log.append(run, record).await.unwrap(); + ] { + let rec = record_with( + task_id, + task_seq, + kind, + None, + json!({ "task_seq": task_seq }), + ); + log.append(run, rec).await.unwrap(); } - let positions = |records: Vec| -> Vec<(String, u32)> { - records - .into_iter() - .map(|stored| (stored.record.task_id, stored.record.task_seq)) - .collect() - }; - let expected = |positions: &[(&str, u32)]| -> Vec<(String, u32)> { - positions - .iter() - .map(|(task, seq)| ((*task).to_owned(), *seq)) - .collect() - }; - - let events = RecordFilter { - kind: Some(RecordKind::Event), - ..ALL - }; - let all_events = log.records(run, events.clone()).await.unwrap(); - assert_eq!( - positions(all_events), - expected(&[("0", 0), ("0.0", 1), ("0.0", 0), ("0", 2)]) - ); - let last_two = log - .records( - run, - RecordFilter { - last: Some(2), - ..ALL - }, - ) - .await - .unwrap(); - assert_eq!(positions(last_two), expected(&[("0.0", 0), ("0", 2)])); - - let last_event = log - .records( - run, - RecordFilter { - last: Some(1), - ..events - }, - ) - .await - .unwrap(); - assert_eq!(positions(last_event), expected(&[("0", 2)])); + for &(label, kind, last, expected) in FILTER_CASES { + let records = log.records(run, RecordFilter { kind, last }).await.unwrap(); + let actual: Vec<(&str, u32)> = records + .iter() + .map(|s| (s.record.task_id.as_str(), s.record.task_seq)) + .collect(); + assert_eq!(actual, expected, "{label}"); + } } #[tokio::test] @@ -251,7 +212,7 @@ async fn a_failed_run_keeps_its_code_and_located_message() { assert_eq!(read.located_message(), error.located_message()); assert!( read.located_message().ends_with("(at prompt.md:7)"), - "the location reads back inside the message: {read:?}" + "location in message: {read:?}" ); assert_eq!( read.prose, @@ -284,11 +245,12 @@ async fn a_run_ends_exactly_once() { let run = log.begin_run(meta(), AGENT).await.unwrap(); log.end_run(run, Err(Error::canceled())).await.unwrap(); - let again = log.end_run(run, Err(Error::canceled())).await; - assert!(matches!(again, Err(LogError::RunEnded(id)) if id == run)); - - let late = log.append(run, record(RecordKind::Event, 0, None)).await; - assert!(matches!(late, Err(LogError::RunEnded(id)) if id == run)); + assert!( + matches!(log.end_run(run, Err(Error::canceled())).await, Err(LogError::RunEnded(id)) if id == run) + ); + assert!( + matches!(log.append(run, record(RecordKind::Event, 0, None)).await, Err(LogError::RunEnded(id)) if id == run) + ); } #[tokio::test] @@ -296,40 +258,35 @@ async fn an_unknown_run_is_refused() { let mut log = RunLog::in_memory().await.unwrap(); let ghost = RunId::from_raw(41); - let appended = log.append(ghost, record(RecordKind::Event, 0, None)).await; - assert!(matches!(appended, Err(LogError::UnknownRun(id)) if id == ghost)); - - let ended = log.end_run(ghost, Err(Error::canceled())).await; - assert!(matches!(ended, Err(LogError::UnknownRun(id)) if id == ghost)); - - let read = log.run(ghost).await; - assert!(matches!(read, Err(LogError::UnknownRun(id)) if id == ghost)); + assert!( + matches!(log.append(ghost, record(RecordKind::Event, 0, None)).await, Err(LogError::UnknownRun(id)) if id == ghost) + ); + assert!( + matches!(log.end_run(ghost, Err(Error::canceled())).await, Err(LogError::UnknownRun(id)) if id == ghost) + ); + assert!(matches!(log.run(ghost).await, Err(LogError::UnknownRun(id)) if id == ghost)); } #[tokio::test] async fn a_32_byte_seed_survives_a_run_log_round_trip() { - // Distinct bytes from a leading `07` to a trailing `ff`, so a dropped - // leading zero, a swapped pair, or a sign bit shows. + // Distinct bytes from leading `07` to trailing `ff`. let seed = RunSeed::from_bytes(std::array::from_fn(|i| u8::try_from(i * 8 + 7).unwrap())); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("runs.db"); - let run = { - let mut log = RunLog::open(&path).await.unwrap(); - let meta = RunMeta { seed, ..meta() }; - log.begin_run(meta, AGENT).await.unwrap() - }; + let run = reopen(&path) + .await + .begin_run(RunMeta { seed, ..meta() }, AGENT) + .await + .unwrap(); - let log = RunLog::open(&path).await.unwrap(); - let read = log.run(run).await.unwrap().meta.seed; - assert_eq!(read.as_bytes(), seed.as_bytes()); + let log = reopen(&path).await; + assert_eq!( + log.run(run).await.unwrap().meta.seed.as_bytes(), + seed.as_bytes() + ); drop(log); - let raw = turso::Builder::new_local(path.to_str().unwrap()) - .build() - .await - .unwrap() - .connect() - .unwrap(); + let raw = connect(&path).await; let mut rows = raw .query("SELECT seed FROM runs WHERE run_id = ?1", (run.get(),)) .await @@ -349,8 +306,7 @@ async fn a_32_byte_seed_survives_a_run_log_round_trip() { .unwrap(); drop(raw); - let log = RunLog::open(&path).await.unwrap(); - let refused = log.run(run).await; + let refused = reopen(&path).await.run(run).await; assert!( matches!(&refused, Err(LogError::Corrupt(message)) if message.contains("seed")), "a malformed seed is a read error naming the column: {refused:?}" @@ -363,7 +319,7 @@ async fn a_log_on_disk_keeps_its_rows_across_reopen() { let path = dir.path().join("runs.db"); let run = { - let mut log = RunLog::open(&path).await.unwrap(); + let mut log = reopen(&path).await; let run = log.begin_run(meta(), AGENT).await.unwrap(); log.append(run, record(RecordKind::Event, 0, None)) .await @@ -372,7 +328,7 @@ async fn a_log_on_disk_keeps_its_rows_across_reopen() { run }; - let log = RunLog::open(&path).await.unwrap(); + let log = reopen(&path).await; let row = log.run(run).await.unwrap(); assert!(matches!(row.result, Some(Err(error)) if error.is_canceled())); assert_eq!(log.records(run, ALL).await.unwrap().len(), 1); diff --git a/crates/workshop/run-log/tests/it/fidelity.rs b/crates/workshop/run-log/tests/it/fidelity.rs index 2f73153b..ec637f37 100644 --- a/crates/workshop/run-log/tests/it/fidelity.rs +++ b/crates/workshop/run-log/tests/it/fidelity.rs @@ -1,128 +1,21 @@ //! Payload fidelity: a stored payload reads back as the identical value. -//! -//! The log writes a record's payload as JSON text and parses it back on -//! read; replay compares the parsed value against the one that produced it, -//! so a float whose text does not parse exactly, or an object whose key -//! order changes, would make a replayed run differ from the run that ran. use runvil::event::{Event, ReplyOrigin}; use runvil::ids::{Provenance, RoundId, TaskId}; use runvil::metrics::{CallMetrics, ClientTiming, LlamaTimings, Usage, VllmMetrics}; -use runvil::{Error, RunSeed, Timestamp}; use serde_json::{Map, Value, json}; -use workshop_run_log::{Record, RecordFilter, RecordKind, RunLog, RunMeta}; +use workshop_run_log::{RecordKind, RunLog}; -/// A double whose shortest decimal text a plain parser reads back as the -/// neighbour `3.9078`: the defect exact parsing removes. -const AWKWARD: f64 = 3.907_800_000_000_000_4; - -/// Every record of a run, in loop order. -const ALL: RecordFilter = RecordFilter { - kind: None, - last: None, -}; - -/// A run's opening row, as the Harness would write it. -fn meta() -> RunMeta { - RunMeta { - seed: RunSeed::from_bytes([3; 32]), - flags: 0, - started_at: Timestamp::from_unix_millis(1_700_000_000_000), - } -} - -/// The replay key every fidelity event carries. -fn provenance() -> Result { - Ok(Provenance::new("0".parse::()?, 0)) -} - -/// Appends `payload` as the one event of a fresh run and asserts the log -/// returns the identical value and the identical text. -async fn round_trips(payload: Value) -> Result<(), Box> { - let mut log = RunLog::in_memory().await?; - let run = log.begin_run(meta(), "chat").await?; - log.append( - run, - Record { - task_id: "0".to_owned(), - task_seq: 0, - kind: RecordKind::Event, - effect_id: None, - payload: payload.clone(), - }, - ) - .await?; - - let stored = log.records(run, ALL).await?; - assert_eq!( - stored.len(), - 1, - "the run holds exactly the one event appended" - ); - let returned = &stored[0].record.payload; - assert_eq!(returned, &payload, "the value survives the round trip"); - assert_eq!( - serde_json::to_string(returned)?, - serde_json::to_string(&payload)?, - "the stored text is canonical for the value" - ); - Ok(()) -} - -#[tokio::test] -async fn awkward_floats_round_trip_through_the_log() { - // Each of these is a double whose shortest decimal text a plain - // parser does not reproduce; without exact parsing the value read - // back is a neighbour of the one written. - round_trips(json!({ - "sum": 0.1 + 0.2, - "noise": AWKWARD, - "tiny": 1e-7, - "huge": 1e21, - "max": f64::MAX, - "negative_zero": -0.0, - })) - .await - .unwrap(); -} - -#[tokio::test] -async fn nested_objects_round_trip_with_canonical_key_order() { - // Insertion order is deliberately not sorted; a `Value` object is a - // `BTreeMap`, so the stored text orders keys by byte value whatever - // the insertion order, and that canonical order must survive the read. - let mut inner = Map::new(); - inner.insert("zulu".to_owned(), json!(1)); - inner.insert("alpha".to_owned(), json!({ "yankee": 2, "bravo": 3 })); - inner.insert("mike".to_owned(), json!([{ "delta": 4, "charlie": 5 }])); - - let mut outer = Map::new(); - outer.insert("second".to_owned(), Value::Object(inner)); - outer.insert("first".to_owned(), json!(true)); - - let payload = Value::Object(outer); - assert_eq!( - serde_json::to_string(&payload).unwrap(), - r#"{"first":true,"second":{"alpha":{"bravo":3,"yankee":2},"mike":[{"charlie":5,"delta":4}],"zulu":1}}"# - ); - round_trips(payload).await.unwrap(); -} +use crate::support::{AGENT, ALL, meta, record_with}; -#[tokio::test] -async fn arrays_of_mixed_numbers_round_trip_through_the_log() { - round_trips(json!({ - "mixed": [0, -1, 1.5, 0.1 + 0.2, AWKWARD, 1e21, i64::MIN, u64::MAX], - "nested": [[1.25, 2], [3.5]], - })) - .await - .unwrap(); -} +/// A double whose shortest decimal text a plain parser reads back as `3.9078`. +const AWKWARD: f64 = 3.907_800_000_000_000_4; -#[tokio::test] -async fn a_real_assistant_reply_with_metrics_round_trips_through_the_log() { +fn assistant_reply_payload() -> Value { + let provenance = Provenance::new("0".parse::().unwrap_or_else(|_| unreachable!()), 0); let event = Event::AssistantReply { section: "chat".to_owned(), - provenance: provenance().unwrap(), + provenance, turn: 2, round: RoundId::new(1), text: "hello".to_owned(), @@ -151,12 +44,84 @@ async fn a_real_assistant_reply_with_metrics_round_trips_through_the_log() { )) .with_client(Some( ClientTiming::new(0.1 + 0.2) - .with_ttft_ms(Some(3.907_800_000_000_000_4)) + .with_ttft_ms(Some(AWKWARD)) .with_mean_itl_ms(Some(8.25)), )), ), }; - round_trips(serde_json::to_value(&event).unwrap()) - .await - .unwrap(); + serde_json::to_value(&event).unwrap_or_else(|_| unreachable!()) +} + +#[tokio::test] +async fn payloads_round_trip_with_exact_values_and_canonical_text() { + // Deliberately unsorted insertion order: `Value` is a `BTreeMap`, so canonical + // key order must survive serialization and read-back. + let inner = Map::from_iter([ + ("zulu".to_owned(), json!(1)), + ("alpha".to_owned(), json!({ "yankee": 2, "bravo": 3 })), + ("mike".to_owned(), json!([{ "delta": 4, "charlie": 5 }])), + ]); + let nested_object = Value::Object(Map::from_iter([ + ("second".to_owned(), Value::Object(inner)), + ("first".to_owned(), json!(true)), + ])); + + let cases: [(&str, Value, Option<&str>); 6] = [ + ( + "awkward_floats", + json!({ "sum": 0.1 + 0.2, "noise": AWKWARD, "tiny": 1e-7, "huge": 1e21, "max": f64::MAX, "negative_zero": -0.0 }), + None, + ), + ( + "nested_objects_canonical_key_order", + nested_object, + Some( + r#"{"first":true,"second":{"alpha":{"bravo":3,"yankee":2},"mike":[{"charlie":5,"delta":4}],"zulu":1}}"#, + ), + ), + ( + "arrays_of_mixed_numbers", + json!({ "mixed": [0, -1, 1.5, 0.1 + 0.2, AWKWARD, 1e21, i64::MIN, u64::MAX], "nested": [[1.25, 2], [3.5]] }), + None, + ), + ( + "assistant_reply_with_metrics", + assistant_reply_payload(), + None, + ), + ( + "empty_containers_and_scalars", + json!({ "obj": {}, "arr": [], "str": "", "null": null, "bools": [false, true], "nested": [{}, [], ""] }), + None, + ), + ( + "unicode_and_escapes", + json!({ "cjk": "日本語テスト", "emoji": "🦀🚀", "escapes": "a\nb\tc\"d\\e\u{0000}", "clé": "café" }), + None, + ), + ]; + + let mut log = RunLog::in_memory().await.unwrap(); + for (label, payload, expected_json) in cases { + let written_json = serde_json::to_string(&payload).unwrap(); + if let Some(canonical) = expected_json { + assert_eq!( + written_json, canonical, + "{label}: pre-write canonical order" + ); + } + let run = log.begin_run(meta(), AGENT).await.unwrap(); + let rec = record_with("0", 0, RecordKind::Event, None, payload.clone()); + log.append(run, rec).await.unwrap(); + + let stored = log.records(run, ALL).await.unwrap(); + assert_eq!(stored.len(), 1, "{label}: one event stored"); + let returned = &stored[0].record.payload; + assert_eq!(returned, &payload, "{label}: value survives round trip"); + assert_eq!( + serde_json::to_string(returned).unwrap(), + written_json, + "{label}: canonical JSON text survives round trip" + ); + } } diff --git a/crates/workshop/run-log/tests/it/main.rs b/crates/workshop/run-log/tests/it/main.rs index 07a2d1c5..bdb12eea 100644 --- a/crates/workshop/run-log/tests/it/main.rs +++ b/crates/workshop/run-log/tests/it/main.rs @@ -5,3 +5,4 @@ mod fidelity; mod read; mod recorder; mod result; +mod support; diff --git a/crates/workshop/run-log/tests/it/read.rs b/crates/workshop/run-log/tests/it/read.rs index 7c5aa223..dd084b5c 100644 --- a/crates/workshop/run-log/tests/it/read.rs +++ b/crates/workshop/run-log/tests/it/read.rs @@ -1,39 +1,17 @@ //! The read path: the whole transcript for session views. -use runvil::{RunSeed, Timestamp}; use serde_json::json; -use workshop_run_log::{LogError, Record, RecordKind, RunId, RunLog, RunMeta}; +use workshop_run_log::{LogError, RecordKind, RunId, RunLog}; -/// The agent the Host launched. -const AGENT: &str = "chat"; - -/// A run's opening row. -fn meta() -> RunMeta { - RunMeta { - seed: RunSeed::from_bytes([3; 32]), - flags: 0, - started_at: Timestamp::from_unix_millis(1_700_000_000_000), - } -} - -/// One record with the given provenance and kind and an empty payload. -fn record(task_id: &str, task_seq: u32, kind: RecordKind) -> Record { - Record { - task_id: task_id.to_owned(), - task_seq, - kind, - effect_id: (kind != RecordKind::Event).then_some(u64::from(task_seq)), - payload: json!({}), - } -} +use crate::support::{AGENT, meta, record_with}; /// Two tasks interleaved in loop order (the main walk `0` and its first /// child `0.0`), each task's events arriving out of `task_seq` order, with /// an effect and its answer mixed in so the event-only transcript has -/// something to exclude. Returns the run. +/// something to exclude. async fn interleaved_run(log: &mut RunLog) -> Result { let run = log.begin_run(meta(), AGENT).await?; - let appended = [ + for (task_id, task_seq, kind) in [ ("0", 0, RecordKind::Event), ("0.0", 2, RecordKind::Event), ("0", 1, RecordKind::Effect), @@ -42,9 +20,13 @@ async fn interleaved_run(log: &mut RunLog) -> Result { ("0", 3, RecordKind::Event), ("0.0", 1, RecordKind::Event), ("0", 4, RecordKind::Event), - ]; - for (task_id, task_seq, kind) in appended { - log.append(run, record(task_id, task_seq, kind)).await?; + ] { + let effect_id = (kind != RecordKind::Event).then_some(u64::from(task_seq)); + log.append( + run, + record_with(task_id, task_seq, kind, effect_id, json!({})), + ) + .await?; } Ok(run) } @@ -55,22 +37,24 @@ async fn transcript_returns_every_event_in_seq_order_and_nothing_else() { let run = interleaved_run(&mut log).await.unwrap(); let transcript = log.transcript(run).await.unwrap(); - let seqs: Vec = transcript.iter().map(|stored| stored.seq.get()).collect(); - assert_eq!(seqs, [0, 1, 3, 5, 6, 7]); - let provenance: Vec<(&str, u32)> = transcript - .iter() - .map(|stored| (stored.record.task_id.as_str(), stored.record.task_seq)) - .collect(); - assert_eq!( - provenance, - [ - ("0", 0), - ("0.0", 2), - ("0.0", 0), - ("0", 3), - ("0.0", 1), - ("0", 4) - ] + assert!( + transcript + .iter() + .map(|stored| stored.seq.get()) + .eq([0, 1, 3, 5, 6, 7]) + ); + assert!( + transcript + .iter() + .map(|stored| (stored.record.task_id.as_str(), stored.record.task_seq)) + .eq([ + ("0", 0), + ("0.0", 2), + ("0.0", 0), + ("0", 3), + ("0.0", 1), + ("0", 4), + ]) ); assert!( transcript @@ -83,9 +67,12 @@ async fn transcript_returns_every_event_in_seq_order_and_nothing_else() { async fn transcript_of_a_run_with_no_events_is_empty() { let mut log = RunLog::in_memory().await.unwrap(); let run = log.begin_run(meta(), AGENT).await.unwrap(); - log.append(run, record("0", 0, RecordKind::Effect)) - .await - .unwrap(); + log.append( + run, + record_with("0", 0, RecordKind::Effect, Some(0), json!({})), + ) + .await + .unwrap(); assert!(log.transcript(run).await.unwrap().is_empty()); } diff --git a/crates/workshop/run-log/tests/it/recorder.rs b/crates/workshop/run-log/tests/it/recorder.rs index c1666973..7cedece2 100644 --- a/crates/workshop/run-log/tests/it/recorder.rs +++ b/crates/workshop/run-log/tests/it/recorder.rs @@ -1,65 +1,30 @@ //! `TursoRecorder`: a whole run goes in through a per-run handle's //! recorder trait and comes back out through `RunLog`. -// clippy.toml's allow-unwrap-in-tests covers #[test] functions only, not -// the helpers they share; failing a test by panicking is what these are for. -#![expect( - clippy::unwrap_used, - reason = "test helpers fail by panicking with the failure shown" -)] +#![expect(clippy::unwrap_used, reason = "test helpers fail by panicking")] use std::fs; -use std::path::Path; use std::sync::Arc; -use runvil::harness::{Record, RecordKind, RunId, RunMeta, RunRecorder}; -use runvil::{Error, ErrorCode, RunSeed, Timestamp}; +use runvil::harness::{Record, RecordKind, RunId, RunRecorder}; +use runvil::{Error, ErrorCode, Timestamp}; use serde_json::json; -use workshop_run_log::{LogError, RecordFilter, RunLog, TursoRecorder}; +use workshop_run_log::{LogError, TursoRecorder}; -/// Every record of a run, in loop order. -const ALL: RecordFilter = RecordFilter { - kind: None, - last: None, -}; +use crate::support::{AGENT, ALL, STARTED_AT, meta, meta_at, record_with, reopen}; -/// The agent the Host launched. -const AGENT: &str = "chat"; - -/// When a test's first run starts. -const FIRST: Timestamp = Timestamp::from_unix_millis(1_700_000_000_000); - -/// When a test's second run starts, so a read tells the two runs apart. const SECOND: Timestamp = Timestamp::from_unix_millis(1_700_000_000_001); -/// A run's opening row as the Harness would write it, starting at -/// `started_at`. -fn meta(started_at: Timestamp) -> RunMeta { - RunMeta { - seed: RunSeed::from_bytes([0xfe; 32]), - flags: 0, - started_at, - } -} - -/// One record of `kind` on task 0 at `task_seq`, tagged with `owner` so a -/// read can tell whose it is. -fn record(kind: RecordKind, task_seq: u32, effect_id: Option, owner: &str) -> Record { - Record { - task_id: "0".to_owned(), +fn tagged(kind: RecordKind, task_seq: u32, effect_id: Option, owner: &str) -> Record { + record_with( + "0", task_seq, kind, effect_id, - payload: json!({ "owner": owner, "task_seq": task_seq }), - } -} - -/// Opens the file a recorder wrote, once the recorder is gone. -async fn read_back(path: &Path) -> RunLog { - RunLog::open(path).await.unwrap() + json!({ "owner": owner, "task_seq": task_seq }), + ) } -/// The text of the log failure behind a recorder error. fn log_failure(error: &Error) -> &str { assert_eq!(error.code, ErrorCode::RecorderFailed); let Some(cause) = error.message.strip_prefix("the run recorder failed: ") else { @@ -76,52 +41,39 @@ async fn a_whole_run_goes_in_through_the_recorder_and_reads_back_through_the_log let path = turso.path().to_path_buf(); assert_eq!(path.parent(), Some(state.as_path())); let recorder = turso.for_agent(AGENT); - assert!( - !state.exists(), - "building the recorder and its handle touches no file; the first run does" - ); - - let run = recorder.begin_run(meta(FIRST)).await.unwrap(); - recorder - .append(run, record(RecordKind::Effect, 0, Some(7), "a")) - .await - .unwrap(); - recorder - .append(run, record(RecordKind::Answer, 1, Some(7), "a")) - .await - .unwrap(); - recorder - .append(run, record(RecordKind::Event, 2, None, "a")) - .await - .unwrap(); + assert!(!state.exists(), "building the recorder touches no file"); + + let run = recorder.begin_run(meta()).await.unwrap(); + for (kind, task_seq, effect_id) in [ + (RecordKind::Effect, 0, Some(7)), + (RecordKind::Answer, 1, Some(7)), + (RecordKind::Event, 2, None), + ] { + recorder + .append(run, tagged(kind, task_seq, effect_id, "a")) + .await + .unwrap(); + } recorder.end_run(run, Ok("done".to_owned())).await.unwrap(); drop((recorder, turso)); - let log = read_back(&path).await; + let log = reopen(&path).await; let row = log.run(run).await.unwrap(); - assert_eq!(row.meta, meta(FIRST)); + assert_eq!(row.meta, meta()); assert_eq!(row.agent, AGENT, "the handle writes its agent"); assert_eq!(row.result, Some(Ok("done".to_owned()))); assert!(row.ended_at.is_some()); let records = log.records(run, ALL).await.unwrap(); - let stored: Vec<(RecordKind, u32, Option)> = records - .iter() - .map(|stored| { - ( - stored.record.kind, - stored.record.task_seq, - stored.record.effect_id, - ) - }) - .collect(); - assert_eq!( - stored, - [ - (RecordKind::Effect, 0, Some(7)), - (RecordKind::Answer, 1, Some(7)), - (RecordKind::Event, 2, None), - ] + assert!( + records + .iter() + .map(|s| (s.record.kind, s.record.task_seq, s.record.effect_id)) + .eq([ + (RecordKind::Effect, 0, Some(7)), + (RecordKind::Answer, 1, Some(7)), + (RecordKind::Event, 2, None), + ]) ); for (index, stored) in records.iter().enumerate() { let task_seq = u32::try_from(index).unwrap(); @@ -140,15 +92,15 @@ async fn each_handle_writes_its_own_agent_into_the_shared_log() { let chat = turso.for_agent("chat"); let echo = turso.for_agent("echo"); - let first = chat.begin_run(meta(FIRST)).await.unwrap(); - let second = echo.begin_run(meta(SECOND)).await.unwrap(); + let first = chat.begin_run(meta()).await.unwrap(); + let second = echo.begin_run(meta_at(SECOND)).await.unwrap(); assert_ne!(first, second, "both handles write one log"); chat.end_run(first, Err(Error::canceled())).await.unwrap(); echo.end_run(second, Err(Error::canceled())).await.unwrap(); drop((chat, echo, turso)); - let log = read_back(&path).await; - for (run, started_at, agent) in [(first, FIRST, "chat"), (second, SECOND, "echo")] { + let log = reopen(&path).await; + for (run, started_at, agent) in [(first, STARTED_AT, "chat"), (second, SECOND, "echo")] { let row = log.run(run).await.unwrap(); assert_eq!(row.meta.started_at, started_at); assert_eq!(row.agent, agent, "run {run} names its own handle's agent"); @@ -163,27 +115,24 @@ async fn a_failed_open_is_retried_by_the_next_call() { let turso = Arc::new(TursoRecorder::new(&state)); let recorder = turso.for_agent(AGENT); - let error = recorder.begin_run(meta(FIRST)).await.unwrap_err(); + let error = recorder.begin_run(meta()).await.unwrap_err(); assert!( log_failure(&error).starts_with("run log file: "), - "the directory cannot be created: {error:?}" + "{error:?}" ); fs::remove_file(&state).unwrap(); - let run = recorder.begin_run(meta(FIRST)).await.unwrap(); + let run = recorder.begin_run(meta()).await.unwrap(); recorder - .append(run, record(RecordKind::Event, 0, None, "a")) + .append(run, tagged(RecordKind::Event, 0, None, "a")) .await .unwrap(); recorder.end_run(run, Err(Error::canceled())).await.unwrap(); let path = turso.path().to_path_buf(); drop((recorder, turso)); - let log = read_back(&path).await; - assert!(matches!( - log.run(run).await.unwrap().result, - Some(Err(error)) if error.is_canceled() - )); + let log = reopen(&path).await; + assert!(matches!(log.run(run).await.unwrap().result, Some(Err(e)) if e.is_canceled())); assert_eq!(log.records(run, ALL).await.unwrap().len(), 1); } @@ -194,9 +143,9 @@ async fn the_same_file_reopens_with_its_rows() { let first = Arc::new(TursoRecorder::new(&state)); let handle = first.for_agent(AGENT); - let earlier = handle.begin_run(meta(FIRST)).await.unwrap(); + let earlier = handle.begin_run(meta()).await.unwrap(); handle - .append(earlier, record(RecordKind::Event, 0, None, "first")) + .append(earlier, tagged(RecordKind::Event, 0, None, "first")) .await .unwrap(); handle @@ -208,17 +157,17 @@ async fn the_same_file_reopens_with_its_rows() { let second = Arc::new(TursoRecorder::new(&state)); let later = second .for_agent(AGENT) - .begin_run(meta(SECOND)) + .begin_run(meta_at(SECOND)) .await .unwrap(); assert_ne!(later, earlier, "a reopened file issues a fresh run id"); let path = second.path().to_path_buf(); drop(second); - let log = read_back(&path).await; + let log = reopen(&path).await; let kept = log.run(earlier).await.unwrap(); - assert_eq!(kept.meta.started_at, FIRST); - assert!(matches!(kept.result, Some(Err(error)) if error.is_canceled())); + assert_eq!(kept.meta.started_at, STARTED_AT); + assert!(matches!(kept.result, Some(Err(e)) if e.is_canceled())); assert_eq!(log.records(earlier, ALL).await.unwrap().len(), 1); let open = log.run(later).await.unwrap(); assert_eq!(open.meta.started_at, SECOND); @@ -232,32 +181,33 @@ async fn a_write_the_log_refuses_reaches_the_caller_as_a_recorder_error() { let unknown = RunId::from_raw(41); let error = recorder - .append(unknown, record(RecordKind::Event, 0, None, "a")) + .append(unknown, tagged(RecordKind::Event, 0, None, "a")) .await .unwrap_err(); - assert!( - log_failure(&error) == LogError::UnknownRun(unknown).to_string(), + assert_eq!( + log_failure(&error), + LogError::UnknownRun(unknown).to_string(), "{error:?}" ); - let run = recorder.begin_run(meta(FIRST)).await.unwrap(); + let run = recorder.begin_run(meta()).await.unwrap(); recorder.end_run(run, Err(Error::canceled())).await.unwrap(); let error = recorder .end_run(run, Err(Error::canceled())) .await .unwrap_err(); - assert!( - log_failure(&error) == LogError::RunEnded(run).to_string(), + assert_eq!( + log_failure(&error), + LogError::RunEnded(run).to_string(), "{error:?}" ); } -/// Begins a run for `owner`, appends three events, and ends it. async fn whole_run(recorder: &impl RunRecorder, owner: &str) -> RunId { - let run = recorder.begin_run(meta(FIRST)).await.unwrap(); + let run = recorder.begin_run(meta()).await.unwrap(); for task_seq in 0..3 { recorder - .append(run, record(RecordKind::Event, task_seq, None, owner)) + .append(run, tagged(RecordKind::Event, task_seq, None, owner)) .await .unwrap(); } @@ -276,18 +226,15 @@ async fn runs_that_overlap_keep_their_own_records() { let path = turso.path().to_path_buf(); drop((recorder, turso)); - let log = read_back(&path).await; + let log = reopen(&path).await; for (run, owner) in [(one, "one"), (two, "two")] { let records = log.records(run, ALL).await.unwrap(); - let owners: Vec<&str> = records - .iter() - .map(|stored| stored.record.payload["owner"].as_str().unwrap()) - .collect(); - assert_eq!(owners, [owner; 3]); - let task_seqs: Vec = records - .iter() - .map(|stored| stored.record.task_seq) - .collect(); - assert_eq!(task_seqs, [0, 1, 2]); + assert!( + records + .iter() + .map(|s| s.record.payload["owner"].as_str().unwrap()) + .eq([owner; 3]) + ); + assert!(records.iter().map(|s| s.record.task_seq).eq([0, 1, 2])); } } diff --git a/crates/workshop/run-log/tests/it/result.rs b/crates/workshop/run-log/tests/it/result.rs index d239b5ef..506630c7 100644 --- a/crates/workshop/run-log/tests/it/result.rs +++ b/crates/workshop/run-log/tests/it/result.rs @@ -1,61 +1,61 @@ //! The stored form of a run's result: the raw columns `end_run` writes, //! and the rows `run` refuses because they fit no result. -// clippy.toml's allow-unwrap-in-tests covers #[test] functions only, not -// the helpers they share; failing a test by panicking is what these are for. -#![expect( - clippy::unwrap_used, - reason = "test helpers fail by panicking with the failure shown" -)] - use std::num::NonZeroU32; -use std::path::Path; - -use runvil::{Error, ErrorCode, RunSeed, SourceLoc, Timestamp}; -use workshop_run_log::{LogError, RunId, RunLog, RunMeta, RunRow}; - -/// The agent the Host launched. -const AGENT: &str = "chat"; - -/// A run's opening row. -fn meta() -> RunMeta { - RunMeta { - seed: RunSeed::from_bytes([5; 32]), - flags: 0, - started_at: Timestamp::from_unix_millis(1_700_000_000_000), - } -} - -/// A failure that is not a cancel. -fn failure() -> Error { - let code = ErrorCode::ToolBackend; - Error::new(code, "expected a reply, got nothing", code.prose()) -} - -/// Begins a run in the log file at `path`, ends it with `result`, and -/// closes the log. -async fn ended(path: &Path, result: Result) -> RunId { - let mut log = RunLog::open(path).await.unwrap(); - let run = log.begin_run(meta(), AGENT).await.unwrap(); - log.end_run(run, result).await.unwrap(); - run -} - -/// A direct connection to the log file at `path`, past the log's own -/// reads and writes. -async fn connect(path: &Path) -> turso::Connection { - turso::Builder::new_local(path.to_str().unwrap()) - .build() - .await - .unwrap() - .connect() - .unwrap() -} -/// Reopens the log file at `path` and reads `run`'s row. -async fn reread(path: &Path, run: RunId) -> Result { - let log = RunLog::open(path).await.unwrap(); - log.run(run).await +use runvil::{Error, ErrorCode, SourceLoc}; +use workshop_run_log::{LogError, RunId, RunLog}; + +use crate::support::{AGENT, connect, meta, reopen}; + +const DONE: Option<&str> = Some("done"); +const TB: Option<&str> = Some("tool_backend"); +const CAN: Option<&str> = Some("canceled"); +const MSG: Option<&str> = Some("failed"); + +type BadShape = ( + &'static str, + &'static str, + Option<&'static str>, + Option<&'static str>, + Option<&'static str>, +); + +/// Every result-column combination that fits no valid outcome. +const CORRUPT_SHAPES: &[BadShape] = &[ + ("completed_no_text", "completed", None, None, None), + ("completed_with_err", "completed", DONE, TB, MSG), + ("completed_with_msg", "completed", DONE, None, MSG), + ("failed_no_msg", "failed", None, TB, None), + ("failed_no_code", "failed", None, None, MSG), + ("failed_with_text", "failed", DONE, TB, MSG), + ("failed_canceled", "failed", None, CAN, CAN), + ("canceled_bad_code", "canceled", None, TB, MSG), + ("canceled_no_code", "canceled", None, None, CAN), + ("canceled_no_msg", "canceled", None, CAN, None), + ("canceled_with_text", "canceled", DONE, CAN, CAN), +]; + +/// Corrupt scalar columns, ordered so each triggers its own validation check. +const CORRUPT_COLUMNS: &[(&str, &str, &[&str])] = &[ + ( + "unknown_code", + "status = 'failed', final_text = NULL, error_code = 'exploded', error_message = 'failed'", + &["error_code", "exploded"], + ), + ( + "unknown_status", + "status = 'exploded'", + &["status", "exploded"], + ), + ("negative_flags", "flags = -1", &["flags", "-1"]), + ("overflow_flags", "flags = 4294967296", &["flags"]), +]; + +async fn record_ended(log: &mut RunLog, result: Result) -> Result { + let run = log.begin_run(meta(), AGENT).await?; + log.end_run(run, result).await?; + Ok(run) } #[tokio::test] @@ -68,128 +68,92 @@ async fn the_status_and_error_code_columns_hold_the_status_and_the_code_tag() { ErrorCode::NotFound.prose(), ); located.at = Some(SourceLoc::line("prompt.md", NonZeroU32::new(3).unwrap())); - let failed = ended(&path, Err(located.clone())).await; - let canceled = ended(&path, Err(Error::canceled())).await; - let completed = ended(&path, Ok("done".to_owned())).await; + + let mut log = reopen(&path).await; + let failed = record_ended(&mut log, Err(located.clone())).await.unwrap(); + let canceled = record_ended(&mut log, Err(Error::canceled())) + .await + .unwrap(); + let completed = record_ended(&mut log, Ok("done".to_owned())).await.unwrap(); + drop(log); let raw = connect(&path).await; let expected = [ ( + "failed", failed, "failed", None, - Some(ErrorCode::NotFound.tag().to_owned()), + Some(ErrorCode::NotFound.tag()), Some(located.located_message()), ), ( + "canceled", canceled, "canceled", None, - Some(ErrorCode::Canceled.tag().to_owned()), + Some(ErrorCode::Canceled.tag()), Some(Error::canceled().located_message()), ), - (completed, "completed", Some("done".to_owned()), None, None), + ( + "completed", + completed, + "completed", + Some("done"), + None, + None, + ), ]; - for (run, status, final_text, error_code, error_message) in expected { + for (label, run, status, final_text, error_code, error_message) in expected { let mut rows = raw .query( - "SELECT status, final_text, error_code, error_message FROM runs \ - WHERE run_id = ?1", + "SELECT status, final_text, error_code, error_message FROM runs WHERE run_id = ?1", (run.get(),), ) .await .unwrap(); let row = rows.next().await.unwrap().unwrap(); - assert_eq!(row.get::(0).unwrap(), status, "run {run}'s status"); + assert_eq!(row.get::(0).unwrap(), status, "{label}: status"); assert_eq!( - row.get::>(1).unwrap(), + row.get::>(1).unwrap().as_deref(), final_text, - "run {run}'s final_text" + "{label}: final_text" ); assert_eq!( - row.get::>(2).unwrap(), + row.get::>(2).unwrap().as_deref(), error_code, - "run {run}'s error_code is its code's tag" + "{label}: error_code" ); assert_eq!( row.get::>(3).unwrap(), error_message, - "run {run}'s error_message is its located message" + "{label}: error_message" ); } } #[tokio::test] -async fn an_unknown_code_tag_in_error_code_reads_as_corrupt() { +async fn corrupt_run_rows_read_as_corrupt() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("runs.db"); - let run = ended(&path, Err(failure())).await; - let raw = connect(&path).await; - raw.execute( - "UPDATE runs SET error_code = 'exploded' WHERE run_id = ?1", - (run.get(),), - ) - .await - .unwrap(); - drop(raw); + let mut log = reopen(&path).await; + let run = record_ended(&mut log, Ok("done".to_owned())).await.unwrap(); - let refused = reread(&path, run).await; - assert!( - matches!(&refused, Err(LogError::Corrupt(message)) - if message.contains("error_code") && message.contains("exploded")), - "an unknown code tag is a read error naming the column and the tag: {refused:?}" - ); -} - -#[tokio::test] -async fn an_unknown_status_reads_as_corrupt() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("runs.db"); - let run = ended(&path, Ok("done".to_owned())).await; let raw = connect(&path).await; - let update = "UPDATE runs SET status = 'exploded' WHERE run_id = ?1"; assert!( - raw.execute(update, (run.get(),)).await.is_err(), + raw.execute( + "UPDATE runs SET status = 'exploded' WHERE run_id = ?1", + (run.get(),) + ) + .await + .is_err(), "the schema refuses an unknown status" ); raw.execute("PRAGMA ignore_check_constraints = ON", ()) .await .unwrap(); - raw.execute(update, (run.get(),)).await.unwrap(); - drop(raw); - let refused = reread(&path, run).await; - assert!( - matches!(&refused, Err(LogError::Corrupt(message)) - if message.contains("status") && message.contains("exploded")), - "an unknown status is a read error naming the status: {refused:?}" - ); -} - -#[tokio::test] -async fn a_row_whose_columns_fit_no_result_reads_as_corrupt() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("runs.db"); - let run = ended(&path, Ok("done".to_owned())).await; - // Each row breaks one rule of the three shapes: a completed run has - // its final text alone, and a failed or canceled run has a code and a - // message, the code `canceled` exactly when the run is canceled. - let shapes = [ - ("completed", None, None, None), - ( - "completed", - Some("done"), - Some("tool_backend"), - Some("failed"), - ), - ("failed", None, Some("tool_backend"), None), - ("failed", Some("done"), Some("tool_backend"), Some("failed")), - ("failed", None, Some("canceled"), Some("canceled")), - ("canceled", None, Some("tool_backend"), Some("failed")), - ("canceled", None, None, Some("canceled")), - ]; - for (status, final_text, error_code, error_message) in shapes { - let raw = connect(&path).await; + for &(label, status, final_text, error_code, error_message) in CORRUPT_SHAPES { raw.execute( "UPDATE runs SET status = ?2, final_text = ?3, error_code = ?4, \ error_message = ?5 WHERE run_id = ?1", @@ -197,13 +161,25 @@ async fn a_row_whose_columns_fit_no_result_reads_as_corrupt() { ) .await .unwrap(); - drop(raw); - - let refused = reread(&path, run).await; + let refused = log.run(run).await; assert!( - matches!(refused, Err(LogError::Corrupt(_))), - "status {status} with final_text={final_text:?} error_code={error_code:?} \ - error_message={error_message:?} reads as corrupt: {refused:?}" + matches!(&refused, Err(LogError::Corrupt(msg)) if msg.contains(status)), + "{label}: expected Corrupt naming {status:?}, got {refused:?}" ); } + + for &(label, set_clause, tokens) in CORRUPT_COLUMNS { + let sql = format!("UPDATE runs SET {set_clause} WHERE run_id = ?1"); + raw.execute(&sql, (run.get(),)).await.unwrap(); + let refused = log.run(run).await; + let Err(LogError::Corrupt(message)) = refused else { + panic!("{label}: expected LogError::Corrupt, got {refused:?}"); + }; + for &token in tokens { + assert!( + message.contains(token), + "{label}: expected {token:?} in {message:?}" + ); + } + } } diff --git a/crates/workshop/run-log/tests/it/support.rs b/crates/workshop/run-log/tests/it/support.rs new file mode 100644 index 00000000..bed9aa72 --- /dev/null +++ b/crates/workshop/run-log/tests/it/support.rs @@ -0,0 +1,67 @@ +//! Shared fixtures for `workshop-run-log` integration tests. + +#![expect(clippy::unwrap_used, reason = "test helpers fail by panicking")] + +use std::path::Path; + +use runvil::{RunSeed, Timestamp}; +use serde_json::{Value, json}; +use workshop_run_log::{Record, RecordFilter, RecordKind, RunLog, RunMeta}; + +pub(crate) const ALL: RecordFilter = RecordFilter { + kind: None, + last: None, +}; +pub(crate) const AGENT: &str = "chat"; +pub(crate) const STARTED_AT: Timestamp = Timestamp::from_unix_millis(1_700_000_000_000); + +pub(crate) fn meta_at(started_at: Timestamp) -> RunMeta { + RunMeta { + seed: RunSeed::from_bytes([0xfe; 32]), + flags: 0, + started_at, + } +} + +pub(crate) fn meta() -> RunMeta { + meta_at(STARTED_AT) +} + +pub(crate) fn record_with( + task_id: &str, + task_seq: u32, + kind: RecordKind, + effect_id: Option, + payload: Value, +) -> Record { + Record { + task_id: task_id.to_owned(), + task_seq, + kind, + effect_id, + payload, + } +} + +pub(crate) fn record(kind: RecordKind, task_seq: u32, effect_id: Option) -> Record { + record_with( + "0", + task_seq, + kind, + effect_id, + json!({ "task_seq": task_seq }), + ) +} + +pub(crate) async fn connect(path: &Path) -> turso::Connection { + turso::Builder::new_local(path.to_str().unwrap()) + .build() + .await + .unwrap() + .connect() + .unwrap() +} + +pub(crate) async fn reopen(path: &Path) -> RunLog { + RunLog::open(path).await.unwrap() +} diff --git a/crates/workshop/server/build.rs b/crates/workshop/server/build.rs index a69db778..6d870344 100644 --- a/crates/workshop/server/build.rs +++ b/crates/workshop/server/build.rs @@ -6,19 +6,23 @@ //! the `crates/workshop/` npm workspace per checkout (`npm ci --prefix //! crates/workshop` from the repository root). -fn main() -> std::process::ExitCode { - match build_ui::build_sibling( +use std::process::ExitCode; + +use build_ui::{UiBuild, WORKSHOP_STATIC_FILES, build_sibling}; + +fn main() -> ExitCode { + match build_sibling( "../ui", - build_ui::UiBuild { - static_files: build_ui::WORKSHOP_STATIC_FILES, + UiBuild { + static_files: WORKSHOP_STATIC_FILES, define_app_version: true, splitting: true, }, ) { - Ok(()) => std::process::ExitCode::SUCCESS, + Ok(()) => ExitCode::SUCCESS, Err(error) => { eprintln!("{error}"); - std::process::ExitCode::FAILURE + ExitCode::FAILURE } } } diff --git a/crates/workshop/server/src/agents.rs b/crates/workshop/server/src/agents.rs index 215352ee..f3023c5a 100644 --- a/crates/workshop/server/src/agents.rs +++ b/crates/workshop/server/src/agents.rs @@ -1,9 +1,8 @@ //! The agent-sessions subsystem of the server: the `/agents/ws` //! agent-session socket ([`socket`]) and its frames ([`wire`]), the -//! `/v1/models` catalog relay ([`relay`]), their shared route state -//! ([`state`]), and [`AgentSessions`], the server's launcher of agent -//! conversations. The `/ws` workshop socket sits outside this subsystem; -//! the two share only [`crate::websocket`]. +//! `/v1/models` catalog relay ([`relay`]), and [`AgentSessions`], the +//! server's launcher of agent conversations. The `/ws` workshop socket +//! sits outside this subsystem; the two share only [`crate::websocket`]. //! //! The server builds one [`Host`] at startup, through its builder: a //! finder that reads each agent from the agents folder through @@ -13,35 +12,32 @@ //! std Plugin with the file-tool Pack, the bashkit Plugin with the shell //! Pack, and the web Plugin with the web Pack among them. Every Host has //! the built-ins subagents and user beside their Packs. Every tool call -//! of a -//! library Plugin is lent the server's [`resources`]: the Gateway the -//! registry holds as the call starts, which is where the web Pack sends a -//! search. Each launch opens a conversation in `workshop-agents` and builds -//! that conversation's one run its own [`RunSetup`]: the conversation's -//! recorder tee on a handle of the run log's [`TursoRecorder`] that names -//! the launched agent, the server's inference broker ([`broker`]), the -//! stock tokio timer of the Gateway client, a user, the conversation's -//! operator, so the run holds +//! of a library Plugin is lent the server's [`resources`]: the Gateway +//! the registry holds as the call starts, which is where the web Pack +//! sends a search. Each launch opens a conversation in `workshop-agents` +//! and builds that conversation's one run its own [`RunSetup`]: the +//! conversation's recorder tee on a handle of the run log's +//! [`TursoRecorder`] that names the launched agent, the server's +//! inference broker ([`broker`]), the stock tokio timer of the Gateway +//! client, a user, the conversation's operator, so the run holds //! `runvil/user`; the operator's messages reach the run's main chain //! through the conversation, and a streaming callback that publishes each //! live piece of a section's own round into the conversation under the -//! round's id. The run makes its own instance of each Pack -//! it holds and drops them when it ends. The run's model rounds reach the -//! gateway only through the server's inference broker, which follows the -//! live gateway binding and sends each round to the dropdown's current -//! pick. Each +//! round's id. The run makes its own instance of each Pack it holds and +//! drops them when it ends. The run's model rounds reach the gateway only +//! through the server's inference broker, which follows the live gateway +//! binding and sends each round to the dropdown's current pick. Each //! run's filesystem is an in-memory root, with a read-only mount beside it //! for each of two demos whose switch is on: the language guide, and the -//! machine's C drive (`language_guide`). Both switches are committed as +//! machine's C drive (see [`run_vfs`]). Both switches are committed as //! off. The filesystem has no policy of its own, so the default one, //! `AllowAll`, admits every operation: the file tools and the shell change //! the files of the in-memory root, which end with the run, and a //! read-only mount refuses each change. The run's setup takes the Host -//! state ([`bindings`]): the menu's pick, read once the menu's catalog -//! holds a chat-capable model. -//! Status-bar reporting stays in the server (`status`): a -//! per-conversation reporter derives it from the conversation's events, -//! deltas, and failure reports. +//! state ([`with_host_state`]): the menu's pick, read once the menu's +//! catalog holds a chat-capable model. Status-bar reporting stays in the +//! server ([`spawn_reporter`]): a per-conversation reporter derives it +//! from the conversation's events, deltas, and failure reports. //! //! **Registry carve-out.** Conversations survive socket disconnect and //! sockets attach and detach (`socket`), so the launcher keeps the @@ -49,49 +45,310 @@ //! governed per-request relay work, where every held resource belonged to //! one socket; a conversation is longer-lived than any socket on purpose. -mod bindings; mod broker; -mod gateway; -mod language_guide; mod relay; mod socket; -mod socket_frames; -mod state; -mod status; mod wire; use std::fmt; +use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; +use axum::Router; +use axum::routing::get; use harness_gateway_client::{ GatewayEndpoint, SecretString, TokioTimer, provide_gateway_resources, }; use runvil::effect::Round; -use runvil::harness::{HostResources, RunId, insert_plugin_dir}; +use runvil::event::Event; +use runvil::harness::{Delta as HarnessDelta, HostResources, RunId, insert_plugin_dir}; +use runvil::ids::{ChainId, TaskId}; +use runvil::model::ModelId; use runvil::plugin::PackRegistry; +use runvil::vfs::{RealBackend, VfsRef, Writability}; use runvil::{Error, ErrorCode, ErrorFact, Host, PromptFinder, RunSetup}; -use serde_json::Value; +use serde::Deserialize as _; +use serde_json::{Map, Value}; +use tokio::runtime::Handle; +use tokio::sync::broadcast; +use tokio::sync::broadcast::error::RecvError; use workshop_agents::{ - Conversation, ConversationId, Conversations, DeltaKind, LaunchError, discover_agents, - load_agent, + Conversation, ConversationId, Conversations, Delta, DeltaKind, FailureKind, LaunchError, + SessionEvent, SessionFailure, discover_agents, load_agent, }; use workshop_gateway::GatewayHandles; -use workshop_registry::Registry; +use workshop_menu::MenuHandles; +use workshop_protocol::Activity; +use workshop_registry::{Push, Registration, Registry, RouteRegistrarAdapter}; use workshop_run_log::TursoRecorder; -use workshop_support::{Config, ReconnectBackoff}; +use workshop_support::{Config, RELAY_DEADLINE, ReconnectBackoff, with_deadline}; -use bindings::with_host_state; -use broker::WorkshopBroker; -use gateway::{UsableGateway, usable_gateway}; -use socket::Receivers; -pub(crate) use state::{SessionsState, register}; +use self::broker::WorkshopBroker; +use self::socket::Receivers; +use crate::websocket::SocketState; /// The directory under the server's state directory the run log sits in: /// the `runs.db` every conversation's run is recorded in. const HARNESS_STATE_DIR: &str = "harness"; +/// The switch: `true` mounts the guide in every run. +const LANGUAGE_GUIDE_ENABLED: bool = false; + +/// The directory on this machine that holds the guide's pages. +const LANGUAGE_GUIDE_SOURCE: &str = r"C:\Users\Vinnie\cursor\runvil-docs\src\language"; + +/// The virtual path a run sees the guide at. +const LANGUAGE_GUIDE_MOUNT: &str = "/_runvil/language-guide"; + +/// The switch: `true` mounts the whole C drive, read-only, in every run. +/// +/// It is committed as `false`. While it is on, a model can read every +/// file the person who runs Workshop can, what it reads goes to the +/// model's provider, and a search that starts at `/` walks the drive. +const C_DRIVE: bool = false; + +/// The root of the drive [`C_DRIVE`] mounts. +const C_DRIVE_SOURCE: &str = r"C:\"; + +/// The virtual path a run sees the drive at, so `C:\Users` is `/c/Users`, +/// the path Git Bash gives it. +const C_DRIVE_MOUNT: &str = "/c"; + +/// The label for a run that ended in error or was cut short: the agent +/// itself is gone. +const RUN_FAILED_LABEL: &str = "Agent failed"; + +/// The sessions subsystem's routes: the `/v1/models` catalog relay on the +/// relay deadline, and the `/agents/ws` WebSocket upgrade, which answers +/// immediately and then outlives any deadline. +fn routes(state: SocketState) -> Router { + with_deadline( + Router::new().route("/v1/models", get(relay::models)), + RELAY_DEADLINE, + ) + .route("/agents/ws", get(socket::upgrade)) + .with_state(state) +} + +/// The sessions subsystem's registration guards: its routes and the +/// agent-session launcher. Dropping them deregisters the subsystem. +#[derive(Debug)] +#[must_use = "dropping the registrations deregisters the subsystem"] +pub(crate) struct SessionsRegistrations { + /// The `/v1/models` and `/agents/ws` route registrar. + pub(crate) routes: Registration, + /// The agent-session launcher as a state handle. + pub(crate) agents: Registration, +} + +/// Registers the sessions subsystem into the registry: its routes, merged +/// into the server's API router, and the agent-session launcher as a +/// state handle. The returned guards keep the registrations alive; the +/// composition root holds them for the process lifetime. +pub(crate) fn register( + registry: &Registry, + state: &SocketState, + agents: &AgentSessions, +) -> SessionsRegistrations { + let routes = registry.register_routes(Arc::new(RouteRegistrarAdapter::new({ + let state = state.clone(); + move || routes(state.clone()) + }))); + let agents = registry.register_state::(Arc::new(agents.clone())); + SessionsRegistrations { routes, agents } +} + +/// One gateway generation whose endpoint and key both build. +struct UsableGateway { + /// The generation the server assigned before publishing it. + generation: u64, + /// The gateway's OpenAI-compatible API root: its base URL with `/v1`. + endpoint: GatewayEndpoint, + /// The bearer paired with the base URL. + key: SecretString, +} + +impl UsableGateway { + /// The current generation of `handles`, or `None` when its URL or key + /// cannot build an endpoint and a bearer. + fn read(handles: &GatewayHandles) -> Option { + let snapshot = handles.binding().snapshot(); + let api_root = format!("{}/v1", snapshot.base_url().trim_end_matches('/')); + Some(Self { + generation: snapshot.generation(), + endpoint: GatewayEndpoint::new(&api_root).ok()?, + key: SecretString::new(snapshot.api_key()).ok()?, + }) + } +} + +/// The gateway `registry` holds, or `None` when no gateway handles are +/// registered or the current generation's URL or key cannot build. +fn usable_gateway(registry: &Registry) -> Option { + let handles = registry.state::()?; + UsableGateway::read(&handles) +} + +/// `setup` with its selected model read from `registry`: `selected_model` +/// from the menu's retained workbench state. An unregistered menu reads +/// as no selection. +fn with_host_state(registry: &Registry, setup: RunSetup) -> RunSetup { + let selected_model = registry + .state::() + .and_then(|handles| handles.menu().latest()) + .and_then(|snapshot| snapshot.selected_model) + .and_then(|name| ModelId::gateway(name).ok()); + RunSetup { + selected_model, + ..setup + } +} + +/// The filesystem for one run: the in-memory root, with the guide mounted +/// at [`LANGUAGE_GUIDE_MOUNT`] when [`LANGUAGE_GUIDE_ENABLED`], and the C +/// drive mounted at [`C_DRIVE_MOUNT`] when [`C_DRIVE`]. +fn run_vfs() -> VfsRef { + let mut vfs = VfsRef::default(); + if LANGUAGE_GUIDE_ENABLED { + vfs = mount_at(vfs, LANGUAGE_GUIDE_MOUNT, Path::new(LANGUAGE_GUIDE_SOURCE)); + } + if C_DRIVE { + vfs = mount_at(vfs, C_DRIVE_MOUNT, Path::new(C_DRIVE_SOURCE)); + } + vfs +} + +/// `base` with the directory `source` mounted read-only at `mount`, an +/// absolute virtual path. A `source` that cannot be mounted leaves `base` +/// as it is and logs a warning, because a run without the mount still +/// works. So a machine with no such directory, as one with no C drive, +/// runs with the switch on as it does with it off. +fn mount_at(base: VfsRef, mount: &str, source: &Path) -> VfsRef { + match RealBackend::rooted(source) { + Ok(backend) => base.overlay(mount, backend.with_writability(Writability::ReadOnly)), + Err(error) => { + tracing::warn!( + source = %source.display(), + mount, + %error, + "a directory is not mounted; runs start without it" + ); + base + } + } +} + +/// Spawns the status reporter for `conversation`, reporting through `push` +/// and resetting `backoff` on completed replies. +fn spawn_reporter(conversation: &Conversation, push: Push, backoff: ReconnectBackoff) { + let events = conversation.subscribe_events(); + let deltas = conversation.subscribe_deltas(); + let errors = conversation.subscribe_errors(); + tokio::spawn(report(events, deltas, errors, push, backoff)); +} + +/// Reports until all of the conversation's channels have closed. They +/// close together as the run ends, when its last reports, its success or +/// its failure, can still be queued, so each channel is drained to its +/// close. Deltas are drained ahead of events, so a round's activity +/// pulses precede the idle the main chain's next wait or its run's +/// success pushes when both sit queued. +async fn report( + mut events: broadcast::Receiver, + mut deltas: broadcast::Receiver, + mut errors: broadcast::Receiver, + push: Push, + backoff: ReconnectBackoff, +) { + let (mut deltas_open, mut events_open, mut errors_open) = (true, true, true); + loop { + tokio::select! { + biased; + received = deltas.recv(), if deltas_open => match received { + Ok(delta) => on_delta(&delta, &push), + // Pulses are ephemeral: a lost chunk's LED state is + // repaired by the next one or by the next wait's idle. + Err(RecvError::Lagged(_)) => {} + Err(RecvError::Closed) => deltas_open = false, + }, + received = events.recv(), if events_open => match received { + Ok(event) => on_event(&event, &push, &backoff), + // A lagged receiver missed at most a status transition the + // next event restates; the transcript still holds every event. + Err(RecvError::Lagged(_)) => {} + Err(RecvError::Closed) => events_open = false, + }, + received = errors.recv(), if errors_open => match received { + Ok(failure) => on_error(&failure, &push), + // Reports are ephemeral like the deltas; a lagged receiver + // missed a failure the error frame already reported. + Err(RecvError::Lagged(_)) => {} + Err(RecvError::Closed) => errors_open = false, + }, + else => return, + } + } +} + +/// The activity pulse that lights the status LED: Generating for answer +/// content, Thinking for the reasoning side channel. +fn on_delta(delta: &Delta, push: &Push) { + let activity = match delta.kind { + DeltaKind::Reasoning => Activity::Thinking, + // `Text`, or any other kind of the conversation's + // `#[non_exhaustive]` `DeltaKind`: the agent is producing output. + _ => Activity::Generating, + }; + push.push_activity("Streaming response...", "an agent response chunk", activity); +} + +/// The side effects the server wires to the conversation's events: the +/// backoff reset at a completed reply (an agent reply is useful gateway +/// work), and the idle status that releases the turn-dispatch Thinking +/// push once the main chain waits on its inbox or its run succeeds. A +/// reply alone leaves the status busy, since a message that lands as it +/// does makes the loop go on. A failed run's end pushes nothing, since +/// its failure report sets the status. +fn on_event(event: &SessionEvent, push: &Push, backoff: &ReconnectBackoff) { + let Ok(event) = Event::deserialize(&event.event) else { + // An event payload this build cannot read: the status bar has + // nothing to say about it. + return; + }; + match event { + Event::AssistantReply { .. } => backoff.record_useful_work(), + Event::InboxWaiting { provenance, .. } | Event::RunSucceeded { provenance, .. } + if provenance.task == TaskId::from(ChainId::root()) => + { + push.push_idle(); + } + _ => {} + } +} + +/// The operator-facing failure status for one of the conversation's +/// failure reports. The conversation reports the kind - a failed model +/// turn or tool call the program survived, a run that ended in error, or +/// a run a close cut short - and the server labels it; the report's +/// message passes through as the description, the same text the socket's +/// error frame reports. Each kind is terminal for its turn, so this status +/// releases the turn-dispatch Thinking push at once. A run that failed or +/// was cut short waits on its inbox no more, so for it this status is the +/// one frame that does; without it the status bar's sustained amber LED +/// never returns to idle. +fn on_error(failure: &SessionFailure, push: &Push) { + // The match is exhaustive on purpose: a new kind fails this build until + // it is labelled here. + let label = match failure.kind { + FailureKind::ModelTurnFailed => "Model turn failed", + FailureKind::ToolCallFailed => "Tool call failed", + FailureKind::RunFailed | FailureKind::Canceled => RUN_FAILED_LABEL, + }; + push.push_failure(label, &failure.message, Activity::General); +} + /// The server's Host, which finds its agents through `prompts`. /// `registry` holds the Gateway that each tool call of a library Plugin /// is lent ([`resources`]). `mcp` is the `[agents] mcp` setting: the mcp @@ -115,11 +372,11 @@ fn server_host( /// the mcp Pack refuses a malformed entry on its own, and the other /// servers still connect. fn read_mcp_servers(setting: Option<&Path>) -> Value { - let none = || Value::Object(serde_json::Map::new()); + let none = || Value::Object(Map::new()); let Some(path) = setting else { return none(); }; - let text = match std::fs::read_to_string(path) { + let text = match fs::read_to_string(path) { Ok(text) => text, Err(error) if error.kind() == io::ErrorKind::NotFound => return none(), Err(error) => { @@ -193,7 +450,7 @@ fn with_plugins( plugins: Option<&Path>, ) -> Arc { let mut builder = Host::builder(prompts).with_resources(resources); - if let Ok(runtime) = tokio::runtime::Handle::try_current() { + if let Ok(runtime) = Handle::try_current() { builder = builder.with_rust_plugin(move |packs| plugin_mcp::install(packs, servers, runtime)); } @@ -246,7 +503,7 @@ pub struct PluginListing { /// Returns the I/O error when `directory` cannot be read, as when it does /// not exist. pub fn list_plugin_dir(directory: &Path) -> io::Result { - let _ = std::fs::read_dir(directory)?; + let _ = fs::read_dir(directory)?; let mut packs = PackRegistry::new(); // A listing only loads and unloads the Plugins, so it offers them // empty resources. @@ -309,27 +566,24 @@ fn reachable_gateway(registry: &Registry) -> Option<(GatewayEndpoint, SecretStri } /// The Host finder over the agents folder at `agents_path`: the source -/// `load_agent` reads for each name, or its refusal as [`agent_error`]. -/// It comes inside an `Arc`, as a Host's builder takes its finder. +/// `load_agent` reads for each name, or its refusal mapped to +/// [`ErrorCode::NotFound`] for unknown agents and [`ErrorCode::Io`] for +/// unreadable sources. It comes inside an `Arc`, as a Host's builder +/// takes its finder. fn agent_finder(agents_path: PathBuf) -> Arc { Arc::new(move |name: &str| { load_agent(&agents_path, name) .map(|(_file, source)| source) - .map_err(|refusal| agent_error(&refusal)) + .map_err(|refusal| { + let code = match refusal { + LaunchError::UnknownAgent { .. } => ErrorCode::NotFound, + _ => ErrorCode::Io, + }; + Error::new(code, refusal.to_string(), code.prose()) + }) }) } -/// The Host finder's failure for an agent `load_agent` refused: the -/// refusal's display text, under `NotFound` for an agent discovery does -/// not list and `Io` for one whose source cannot be read. -fn agent_error(refusal: &LaunchError) -> Error { - let code = match refusal { - LaunchError::UnknownAgent { .. } => ErrorCode::NotFound, - _ => ErrorCode::Io, - }; - Error::new(code, refusal.to_string(), code.prose()) -} - /// The server's launcher of agent conversations: discovery, launch, /// lookup, and close, plus the server-side work a launch wires up - the /// run's setup and the status reporter. @@ -452,46 +706,36 @@ impl AgentSessions { })?; let conversation = self.inner.conversations.open(name); let receivers = Receivers::subscribe(&conversation); - status::spawn_reporter( + spawn_reporter( &conversation, self.inner.registry.push(), self.inner.backoff.clone(), ); - tokio::spawn(self.clone().drive(conversation.clone())); + let sessions = self.clone(); + let run_conversation = conversation.clone(); + tokio::spawn(async move { + tokio::select! { + () = run_conversation.closing() => {} + () = sessions.inner.broker.chat_model_ready() => {} + } + let recorder = run_conversation + .recorder(sessions.inner.recorder.for_agent(run_conversation.agent())); + let setup = RunSetup::new(recorder, sessions.inner.broker.clone(), TokioTimer) + .vfs(run_vfs()) + .has_user(true) + .streaming(live_pieces(run_conversation.clone())); + let setup = with_host_state(&sessions.inner.registry, setup); + run_conversation + .run( + Arc::clone(&sessions.inner.host), + run_conversation.agent(), + setup, + ) + .await; + }); Ok((conversation, receivers)) } - /// Runs `conversation`'s one run of its agent. The setup's selected - /// model is read once the menu's catalog holds a chat-capable model, - /// so a pick made while the catalog was empty is the one the run - /// binds; a close during that wait ends the run before it begins. - async fn drive(self, conversation: Conversation) { - tokio::select! { - () = conversation.closing() => {} - () = self.inner.broker.chat_model_ready() => {} - } - let setup = with_host_state(&self.inner.registry, self.setup_for(&conversation)); - conversation - .run(Arc::clone(&self.inner.host), conversation.agent(), setup) - .await; - } - - /// The setup of `conversation`'s run before the Host state is read: - /// its recorder tee over a run-log handle naming its agent, the - /// server's inference broker, the stock tokio timer, its filesystem, a - /// user, since every conversation has an operator, and the streaming - /// callback that publishes each live piece into the conversation. - fn setup_for(&self, conversation: &Conversation) -> RunSetup { - let recorder = conversation.recorder(self.inner.recorder.for_agent(conversation.agent())); - // The broker is a handle, and the setup owns one. The callback is - // `'static`, and the caller still needs the conversation to run - // the run, so the callback takes a handle to it. - RunSetup::new(recorder, self.inner.broker.clone(), TokioTimer) - .vfs(language_guide::run_vfs()) - .has_user(true) - .streaming(live_pieces(conversation.clone())) - } - /// The running conversation with this id, when one exists: how a /// socket reattaches after a disconnect. fn get(&self, id: &str) -> Option { @@ -519,13 +763,11 @@ impl AgentSessions { /// own round into `conversation`, under the round's id. It sends on the /// conversation's own broadcast and returns, and it calls nothing of the /// Harness. -fn live_pieces( - conversation: Conversation, -) -> impl Fn(Round, runvil::harness::Delta) + Send + Sync + 'static { +fn live_pieces(conversation: Conversation) -> impl Fn(Round, HarnessDelta) + Send + Sync + 'static { move |round, piece| { let (kind, content) = match piece { - runvil::harness::Delta::Text(text) => (DeltaKind::Text, text), - runvil::harness::Delta::Reasoning(text) => (DeltaKind::Reasoning, text), + HarnessDelta::Text(text) => (DeltaKind::Text, text), + HarnessDelta::Reasoning(text) => (DeltaKind::Reasoning, text), // The enum is non-exhaustive across the crate seam; any other // piece has no delta kind and stays unshown. _ => return, diff --git a/crates/workshop/server/src/agents/bindings-tests.rs b/crates/workshop/server/src/agents/bindings-tests.rs index 718f898d..6f67e733 100644 --- a/crates/workshop/server/src/agents/bindings-tests.rs +++ b/crates/workshop/server/src/agents/bindings-tests.rs @@ -1,10 +1,13 @@ //! Host binding tests: a run's setup takes the menu's selection. use harness_gateway_client::TokioTimer; +use runvil::RunSetup; use runvil::harness::{MemoryRecorder, OfflineBroker}; +use runvil::model::ModelId; use workshop_menu::{CatalogBus, MenuBus}; +use workshop_registry::Registry; -use super::*; +use crate::agents::with_host_state; /// A setup with nothing selected. fn empty_setup() -> RunSetup { diff --git a/crates/workshop/server/src/agents/bindings.rs b/crates/workshop/server/src/agents/bindings.rs deleted file mode 100644 index a8796d31..00000000 --- a/crates/workshop/server/src/agents/bindings.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! The Host state a conversation's run carries in its setup: the menu's -//! selected model, read through the registry as the run starts. The -//! Harness resolves the run's model from it. - -use runvil::RunSetup; -use runvil::model::ModelId; -use workshop_menu::MenuHandles; -use workshop_registry::Registry; - -/// `setup` with its selected model read from `registry`: `selected_model` -/// from the menu's retained workbench state. An unregistered menu reads -/// as no selection. -pub(super) fn with_host_state(registry: &Registry, setup: RunSetup) -> RunSetup { - let selected_model = registry - .state::() - .and_then(|handles| handles.menu().latest()) - .and_then(|snapshot| snapshot.selected_model) - .and_then(|name| ModelId::gateway(name).ok()); - RunSetup { - selected_model, - ..setup - } -} - -#[cfg(test)] -#[path = "bindings-tests.rs"] -mod tests; diff --git a/crates/workshop/server/src/agents/broker.rs b/crates/workshop/server/src/agents/broker.rs index 39cca429..dcc3aac9 100644 --- a/crates/workshop/server/src/agents/broker.rs +++ b/crates/workshop/server/src/agents/broker.rs @@ -27,10 +27,11 @@ use runvil::model::{ make_completion_error, phrase, }; use runvil::{BoxFuture, Error, ErrorCode}; -use workshop_menu::{CatalogBus, MenuHandles}; +use serde_json::Value; +use workshop_menu::MenuHandles; use workshop_registry::Registry; -use super::gateway::usable_gateway; +use super::usable_gateway; /// Serves rounds and model lists through the Gateway the server's registry /// currently holds. @@ -73,46 +74,19 @@ impl WorkshopBroker { } /// Resolves once the menu's catalog holds a chat-capable model, at - /// once when no menu is registered. + /// once when no menu is registered. The watch is taken before the first + /// read, so a generation published between the two still wakes the wait. pub(super) async fn chat_model_ready(&self) { - if let Some(menu) = self.registry.state::() { - chat_model_published(menu.catalog()).await; - } - } - - /// `options` sent to the dropdown's current pick: when the menu's - /// selected model differs from the model `options` names, it replaces - /// that model and every other field stays. With no menu or no pick, - /// `options` goes as it came. A pick whose context window, as the - /// menu's catalog lists it, is smaller than `binding`'s is logged and - /// still sent. - fn routed(&self, binding: &ModelBinding, options: CompletionOptions) -> CompletionOptions { let Some(menu) = self.registry.state::() else { - return options; - }; - let Some(pick) = menu - .menu() - .latest() - .and_then(|snapshot| snapshot.selected_model) - else { - return options; + return; }; - if pick == options.model() { - return options; - } - let models = menu - .catalog() - .latest() - .map_or_else(Vec::new, |push| push.models); - if let Some(pick_window) = narrower_pick_window(&models, &pick, binding.context()) { - tracing::warn!( - pick_window, - binding_window = binding.context().get(), - "the selected model's context window is smaller than the launch model's; \ - the round is sent to the selected model anyway" - ); + let catalog = menu.catalog(); + let mut generation = catalog.subscribe_chat_generation(); + while catalog.latest_chat().is_none() { + if generation.changed().await.is_err() { + return; + } } - options.with_model(pick) } } @@ -138,13 +112,35 @@ impl InferenceBroker for WorkshopBroker { binding: ModelBinding, messages: Vec, tools: Vec, - options: CompletionOptions, + mut options: CompletionOptions, round: Round, on_piece: Option, ) -> BoxFuture<'static, Result, Error>> { match self.current() { Ok(broker) => { - let options = self.routed(&binding, options); + if let Some(menu) = self.registry.state::() + && let Some(pick) = menu + .menu() + .latest() + .and_then(|snapshot| snapshot.selected_model) + && pick != options.model() + { + let models = menu + .catalog() + .latest() + .map_or_else(Vec::new, |push| push.models); + if let Some(pick_window) = + narrower_pick_window(&models, &pick, binding.context()) + { + tracing::warn!( + pick_window, + binding_window = binding.context().get(), + "the selected model's context window is smaller than the launch model's; \ + the round is sent to the selected model anyway" + ); + } + options = options.with_model(pick); + } broker.chat(binding, messages, tools, options, round, on_piece) } Err(error) => Box::pin(async move { Err(error) }), @@ -156,31 +152,15 @@ impl InferenceBroker for WorkshopBroker { /// when it is smaller than `bound`, the window the round's binding holds. /// A pick the catalog does not list, or lists without a window, has /// nothing to compare. -fn narrower_pick_window( - models: &[serde_json::Value], - pick: &str, - bound: NonZeroU32, -) -> Option { +fn narrower_pick_window(models: &[Value], pick: &str, bound: NonZeroU32) -> Option { models .iter() - .find(|model| model.get("id").and_then(serde_json::Value::as_str) == Some(pick)) + .find(|model| model.get("id").and_then(Value::as_str) == Some(pick)) .and_then(|model| model.get("context")) - .and_then(serde_json::Value::as_u64) + .and_then(Value::as_u64) .filter(|window| *window < u64::from(bound.get())) } -/// Waits until `catalog` holds a chat-capable model. The watch is taken -/// before the first read, so a generation published between the two still -/// wakes the wait. -async fn chat_model_published(catalog: &CatalogBus) { - let mut generation = catalog.subscribe_chat_generation(); - while catalog.latest_chat().is_none() { - if generation.changed().await.is_err() { - return; - } - } -} - #[cfg(test)] #[path = "broker-tests.rs"] mod tests; diff --git a/crates/workshop/server/src/agents/gateway.rs b/crates/workshop/server/src/agents/gateway.rs deleted file mode 100644 index 68b290c8..00000000 --- a/crates/workshop/server/src/agents/gateway.rs +++ /dev/null @@ -1,42 +0,0 @@ -//! The one read of a usable gateway that the agent sessions' broker, -//! launch refusal, and resources for the library Plugins share: the -//! generation, the API root, and the bearer of the gateway the registry -//! currently holds. -//! -//! It reads no heartbeat health; a caller that needs reachability checks -//! it itself. - -use harness_gateway_client::{GatewayEndpoint, SecretString}; -use workshop_gateway::GatewayHandles; -use workshop_registry::Registry; - -/// One gateway generation whose endpoint and key both build. -pub(super) struct UsableGateway { - /// The generation the server assigned before publishing it. - pub(super) generation: u64, - /// The gateway's OpenAI-compatible API root: its base URL with `/v1`. - pub(super) endpoint: GatewayEndpoint, - /// The bearer paired with the base URL. - pub(super) key: SecretString, -} - -impl UsableGateway { - /// The current generation of `handles`, or `None` when its URL or key - /// cannot build an endpoint and a bearer. - pub(super) fn read(handles: &GatewayHandles) -> Option { - let snapshot = handles.binding().snapshot(); - let api_root = format!("{}/v1", snapshot.base_url().trim_end_matches('/')); - Some(Self { - generation: snapshot.generation(), - endpoint: GatewayEndpoint::new(&api_root).ok()?, - key: SecretString::new(snapshot.api_key()).ok()?, - }) - } -} - -/// The gateway `registry` holds, or `None` when no gateway handles are -/// registered or the current generation's URL or key cannot build. -pub(super) fn usable_gateway(registry: &Registry) -> Option { - let handles = registry.state::()?; - UsableGateway::read(&handles) -} diff --git a/crates/workshop/server/src/agents/language_guide.rs b/crates/workshop/server/src/agents/language_guide.rs deleted file mode 100644 index c71ced58..00000000 --- a/crates/workshop/server/src/agents/language_guide.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! Two demos of the virtual filesystem, each a read-only mount in every -//! run behind a switch that is committed as off. -//! -//! [`ENABLED`] mounts the Runvil prompting language guide at [`MOUNT`], so -//! an agent can read the language's own documentation with the file -//! tools. The guide's pages are read from [`SOURCE`], a directory on one -//! machine. The chat agent's system prompt, which names the mount, is in -//! `chat.md` and is toggled there. -//! -//! [`C_DRIVE`] mounts this machine's whole C drive at [`C_DRIVE_MOUNT`], -//! so the shell and the file tools can be tried on real files. -//! -//! Both are hacks, and both are all here. With both switches off, a run -//! has its plain in-memory root. - -use std::path::Path; - -use runvil::vfs::{RealBackend, VfsRef, Writability}; - -/// The switch: `true` mounts the guide in every run. -const ENABLED: bool = false; - -/// The directory on this machine that holds the guide's pages. -const SOURCE: &str = r"C:\Users\Vinnie\cursor\runvil-docs\src\language"; - -/// The virtual path a run sees the guide at. -const MOUNT: &str = "/_runvil/language-guide"; - -/// The switch: `true` mounts the whole C drive, read-only, in every run. -/// -/// It is committed as `false`. While it is on, a model can read every -/// file the person who runs Workshop can, what it reads goes to the -/// model's provider, and a search that starts at `/` walks the drive. -const C_DRIVE: bool = false; - -/// The root of the drive [`C_DRIVE`] mounts. -const C_DRIVE_SOURCE: &str = r"C:\"; - -/// The virtual path a run sees the drive at, so `C:\Users` is `/c/Users`, -/// the path Git Bash gives it. -const C_DRIVE_MOUNT: &str = "/c"; - -/// The filesystem for one run: the in-memory root, with the guide mounted -/// at [`MOUNT`] when [`ENABLED`], and the C drive mounted at -/// [`C_DRIVE_MOUNT`] when [`C_DRIVE`]. -pub(super) fn run_vfs() -> VfsRef { - let mut vfs = VfsRef::default(); - if ENABLED { - vfs = mount_at(vfs, MOUNT, Path::new(SOURCE)); - } - if C_DRIVE { - vfs = mount_at(vfs, C_DRIVE_MOUNT, Path::new(C_DRIVE_SOURCE)); - } - vfs -} - -/// `base` with the directory `source` mounted read-only at `mount`, an -/// absolute virtual path. A `source` that cannot be mounted leaves `base` -/// as it is and logs a warning, because a run without the mount still -/// works. So a machine with no such directory, as one with no C drive, -/// runs with the switch on as it does with it off. -fn mount_at(base: VfsRef, mount: &str, source: &Path) -> VfsRef { - match RealBackend::rooted(source) { - Ok(backend) => base.overlay(mount, backend.with_writability(Writability::ReadOnly)), - Err(error) => { - tracing::warn!( - source = %source.display(), - mount, - %error, - "a directory is not mounted; runs start without it" - ); - base - } - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/workshop/server/src/agents/language_guide/tests.rs b/crates/workshop/server/src/agents/language_guide/tests.rs index d5c348ed..2c8a0d69 100644 --- a/crates/workshop/server/src/agents/language_guide/tests.rs +++ b/crates/workshop/server/src/agents/language_guide/tests.rs @@ -1,14 +1,5 @@ -//! Mapping a local directory into a run's filesystem: a directory mapped -//! under `/_runvil` reads through the mapping, is reached by listing down -//! from the root, refuses writes, leaves the in-memory root writable, and -//! is visible to a prompt that runs over the filesystem. The file tools -//! and the shell of such a prompt change nothing under the mapping, and -//! the shell still writes a file of the in-memory root beside it. Two -//! directories mapped one after the other are both visible, as the guide -//! and the C drive are with both switches on. Every test uses a local -//! directory it makes, so none depends on the language guide's files or -//! on a path on any one machine, but for the one that maps a drive's -//! root, which runs on Windows alone. +//! Mapping local directories read-only into a run's VFS while leaving +//! the in-memory root writable. use std::error::Error; use std::path::Path; @@ -16,104 +7,109 @@ use std::path::Path; use runvil::vfs::{Access, FileType, Origin, VfsError, VfsRef}; use workshop_registry::Registry; -use super::mount_at; +use crate::agents::tests::{BASHKIT_LIBRARY, STD_LIBRARY, plugin_dir_of, run_prompt_over, serving}; #[cfg(windows)] -use super::{C_DRIVE_MOUNT, C_DRIVE_SOURCE}; -use crate::agents::server_host; -use crate::agents::tests::{BASHKIT_LIBRARY, plugin_dir, plugin_dir_of, run_prompt_over, serving}; +use crate::agents::{C_DRIVE_MOUNT, C_DRIVE_SOURCE}; +use crate::agents::{mount_at, server_host}; -/// What a test returns: any error from setup or from the VFS fails it. type Outcome = Result<(), Box>; -/// Where the local directory is mapped. const MOUNT: &str = "/_runvil/test"; - -/// The one page the local directory holds. const PAGE: &str = "hello.md"; - -/// What that page says. const TEXT: &str = "# Hello from a local page\n"; -/// A directory holding the one page. -fn local_directory() -> Result> { +const OTHER_MOUNT: &str = "/c"; +const OTHER_PAGE: &str = "other.md"; +const OTHER_TEXT: &str = "# Hello from another page\n"; + +fn dir_with_file(name: &str, text: &str) -> Result> { let directory = tempfile::tempdir().map_err(|e| format!("create a temp dir: {e}"))?; - let page = directory.path().join(PAGE); - std::fs::write(&page, TEXT).map_err(|e| format!("write {}: {e}", page.display()))?; + let page = directory.path().join(name); + std::fs::write(&page, text).map_err(|e| format!("write {}: {e}", page.display()))?; Ok(directory) } -/// The filesystem with `source` mapped to [`MOUNT`]. -fn filesystem_with(source: &Path) -> VfsRef { +fn mounted(source: &Path) -> VfsRef { mount_at(VfsRef::default(), MOUNT, source) } -/// A run's access over the filesystem with `source` mapped to [`MOUNT`]. -fn access_with(source: &Path) -> Result { - filesystem_with(source).acquire(Origin::new("local mapping test")) +fn list_names(access: &Access, path: &str) -> Result, VfsError> { + Ok(access.list(path)?.into_iter().map(|e| e.name).collect()) +} + +#[track_caller] +fn assert_read_only(access: &Access, path: &str, bytes: &[u8]) { + let written = access.write(path, bytes); + assert!( + matches!(written, Err(VfsError::ReadOnly { .. })), + "{path}: {written:?}" + ); +} + +fn assert_dir_unchanged(dir: &Path) -> Outcome { + let page = dir.join(PAGE); + let text = + std::fs::read_to_string(&page).map_err(|e| format!("read {}: {e}", page.display()))?; + assert_eq!(text, TEXT, "the page is as it was"); + assert!(!dir.join("new.md").exists()); + Ok(()) +} + +async fn run_mapped_prompt( + test: &str, + library: &str, + prompt: &str, + vfs: VfsRef, +) -> Result> { + let (plugins, _library) = plugin_dir_of(test, library); + let host = server_host( + serving(prompt), + &Registry::new(), + None, + Some(plugins.path()), + ); + match run_prompt_over(host, vfs).await { + Ok(Ok(final_text)) => Ok(final_text), + result => Err(format!("the prompt did not complete: {result:?}").into()), + } } #[test] fn a_page_of_the_directory_reads_through_the_mapping() -> Outcome { - let directory = local_directory()?; - let access = access_with(directory.path())?; + let directory = dir_with_file(PAGE, TEXT)?; + let access = mounted(directory.path()).acquire(Origin::new("local mapping test"))?; assert_eq!(access.read_string(&format!("{MOUNT}/{PAGE}"))?, TEXT); - let names: Vec = access - .list(MOUNT)? - .into_iter() - .map(|entry| entry.name) - .collect(); - assert_eq!(names, [PAGE]); + assert_eq!(list_names(&access, MOUNT)?, [PAGE]); Ok(()) } #[test] fn listing_down_from_the_root_reaches_the_directory() -> Outcome { - let directory = local_directory()?; - let access = access_with(directory.path())?; - let names = |path: &str| -> Result, VfsError> { - Ok(access - .list(path)? - .into_iter() - .map(|entry| entry.name) - .collect()) - }; - - // The in-memory root holds nothing, so the mapping is the only way down. - assert_eq!(names("/")?, ["_runvil"]); - assert_eq!(names("/_runvil")?, ["test"]); - assert_eq!(names(MOUNT)?, [PAGE]); + let directory = dir_with_file(PAGE, TEXT)?; + let access = mounted(directory.path()).acquire(Origin::new("local mapping test"))?; + + assert_eq!(list_names(&access, "/")?, ["_runvil"]); + assert_eq!(list_names(&access, "/_runvil")?, ["test"]); + assert_eq!(list_names(&access, MOUNT)?, [PAGE]); assert_eq!(access.stat("/_runvil")?.file_type, FileType::Directory); Ok(()) } #[test] fn the_mapping_refuses_a_write_and_leaves_the_page_alone() -> Outcome { - let directory = local_directory()?; - let access = access_with(directory.path())?; + let directory = dir_with_file(PAGE, TEXT)?; + let access = mounted(directory.path()).acquire(Origin::new("local mapping test"))?; - let created = access.write(&format!("{MOUNT}/new.md"), b"new"); - assert!( - matches!(created, Err(VfsError::ReadOnly { .. })), - "{created:?}" - ); - let replaced = access.write(&format!("{MOUNT}/{PAGE}"), b"changed"); - assert!( - matches!(replaced, Err(VfsError::ReadOnly { .. })), - "{replaced:?}" - ); - let page = directory.path().join(PAGE); - let text = - std::fs::read_to_string(&page).map_err(|e| format!("read {}: {e}", page.display()))?; - assert_eq!(text, TEXT); - assert!(!directory.path().join("new.md").exists()); - Ok(()) + assert_read_only(&access, &format!("{MOUNT}/new.md"), b"new"); + assert_read_only(&access, &format!("{MOUNT}/{PAGE}"), b"changed"); + assert_dir_unchanged(directory.path()) } #[test] fn the_in_memory_root_stays_writable_beside_the_mapping() -> Outcome { - let directory = local_directory()?; - let access = access_with(directory.path())?; + let directory = dir_with_file(PAGE, TEXT)?; + let access = mounted(directory.path()).acquire(Origin::new("local mapping test"))?; access.write("/scratch.txt", b"kept")?; assert_eq!(access.read_string("/scratch.txt")?, "kept"); @@ -122,9 +118,9 @@ fn the_in_memory_root_stays_writable_beside_the_mapping() -> Outcome { #[test] fn a_directory_that_cannot_be_mapped_leaves_the_run_its_root() -> Outcome { - let directory = local_directory()?; + let directory = dir_with_file(PAGE, TEXT)?; let missing = directory.path().join("no-such-directory"); - let access = access_with(&missing)?; + let access = mounted(&missing).acquire(Origin::new("local mapping test"))?; assert!(!access.exists(MOUNT)?, "nothing is mapped"); access.write("/scratch.txt", b"kept")?; @@ -132,28 +128,11 @@ fn a_directory_that_cannot_be_mapped_leaves_the_run_its_root() -> Outcome { Ok(()) } -/// Where a second local directory is mapped. -const OTHER_MOUNT: &str = "/c"; - -/// The one page the second local directory holds. -const OTHER_PAGE: &str = "other.md"; - -/// What that page says. -const OTHER_TEXT: &str = "# Hello from another page\n"; - -/// A second directory, holding its own page. -fn other_directory() -> Result> { - let directory = tempfile::tempdir().map_err(|e| format!("create a temp dir: {e}"))?; - let page = directory.path().join(OTHER_PAGE); - std::fs::write(&page, OTHER_TEXT).map_err(|e| format!("write {}: {e}", page.display()))?; - Ok(directory) -} - #[test] fn two_directories_mapped_one_after_the_other_are_both_visible() -> Outcome { - let first = local_directory()?; - let second = other_directory()?; - let access = mount_at(filesystem_with(first.path()), OTHER_MOUNT, second.path()) + let first = dir_with_file(PAGE, TEXT)?; + let second = dir_with_file(OTHER_PAGE, OTHER_TEXT)?; + let access = mount_at(mounted(first.path()), OTHER_MOUNT, second.path()) .acquire(Origin::new("two mappings test"))?; assert_eq!(access.read_string(&format!("{MOUNT}/{PAGE}"))?, TEXT); @@ -161,25 +140,13 @@ fn two_directories_mapped_one_after_the_other_are_both_visible() -> Outcome { access.read_string(&format!("{OTHER_MOUNT}/{OTHER_PAGE}"))?, OTHER_TEXT ); - let names: Vec = access - .list("/")? - .into_iter() - .map(|entry| entry.name) - .collect(); - assert_eq!(names, ["_runvil", "c"], "the root lists both ways down"); - - let written = access.write(&format!("{OTHER_MOUNT}/new.md"), b"new"); - assert!( - matches!(written, Err(VfsError::ReadOnly { .. })), - "{written:?}" - ); + assert_eq!(list_names(&access, "/")?, ["_runvil", "c"]); + assert_read_only(&access, &format!("{OTHER_MOUNT}/new.md"), b"new"); access.write("/scratch.txt", b"kept")?; assert_eq!(access.read_string("/scratch.txt")?, "kept"); Ok(()) } -/// The root of a drive maps as any directory does, which is what the C -/// drive switch relies on. A machine with no C drive has nothing to map. #[cfg(windows)] #[test] fn a_drives_root_maps_read_only_like_any_directory() -> Outcome { @@ -189,28 +156,17 @@ fn a_drives_root_maps_read_only_like_any_directory() -> Outcome { } let access = mount_at(VfsRef::default(), C_DRIVE_MOUNT, root).acquire(Origin::new("drive root test"))?; - assert_eq!(access.stat(C_DRIVE_MOUNT)?.file_type, FileType::Directory); - assert!( - !access.list(C_DRIVE_MOUNT)?.is_empty(), - "the drive's root lists its entries" - ); - let written = access.write(&format!("{C_DRIVE_MOUNT}/runvil-test.tmp"), b"x"); - assert!( - matches!(written, Err(VfsError::ReadOnly { .. })), - "{written:?}" - ); + assert!(!access.list(C_DRIVE_MOUNT)?.is_empty()); + assert_read_only(&access, &format!("{C_DRIVE_MOUNT}/runvil-test.tmp"), b"x"); Ok(()) } -/// A prompt that lists `/_runvil` and reads the mapped page with the `std` -/// file tools, and returns both answers. const PROMPT: &str = r"--- name: sees-the-mapping description: lists and reads a mapped directory runvil: 0 -uses: - - std +uses: [std] --- ## Only @@ -224,40 +180,27 @@ return listing .. '\n' .. page #[tokio::test] async fn a_prompt_sees_the_directory_mapped_under_the_runvil_mount() -> Outcome { - let directory = local_directory()?; - // The std Plugin is a library, which the Host loads from a directory. - let (plugins, _library) = plugin_dir("sees-the-mapping"); - let host = server_host( - serving(PROMPT), - &Registry::new(), - None, - Some(plugins.path()), - ); - - let result = run_prompt_over(host, filesystem_with(directory.path())).await; - - let Ok(Ok(final_text)) = result else { - return Err(format!("the prompt did not complete: {result:?}").into()); - }; - assert!( - final_text.contains(" - test/"), - "the prompt lists the mapping under /_runvil: {final_text}" - ); + let directory = dir_with_file(PAGE, TEXT)?; + let final_text = run_mapped_prompt( + "sees-the-mapping", + STD_LIBRARY, + PROMPT, + mounted(directory.path()), + ) + .await?; + assert!(final_text.contains(" - test/"), "{final_text}"); assert!( final_text.contains(" 1|# Hello from a local page"), - "the prompt reads the mapped page: {final_text}" + "{final_text}" ); Ok(()) } -/// A prompt that asks the three `std` tools that change files to change -/// the mapped directory, and returns each refusal on a line of its own. const CHANGING_PROMPT: &str = r"--- name: changes-the-mapping description: tries to change a mapped directory runvil: 0 -uses: - - std +uses: [std] --- ## Only @@ -269,9 +212,7 @@ local function refused(tool, arguments) end return table.concat({ refused('std/write', { path = '/_runvil/test/new.md', contents = 'new' }), - refused('std/replace', { - path = '/_runvil/test/hello.md', old_string = 'Hello', new_string = 'Goodbye', - }), + refused('std/replace', { path = '/_runvil/test/hello.md', old_string = 'Hello', new_string = 'Goodbye' }), refused('std/rm', { path = '/_runvil/test/hello.md' }), }, '\n') ``` @@ -279,20 +220,15 @@ return table.concat({ #[tokio::test] async fn the_file_tools_change_nothing_under_the_mapping() -> Outcome { - let directory = local_directory()?; - let (plugins, _library) = plugin_dir("changes-the-mapping"); - let host = server_host( - serving(CHANGING_PROMPT), - &Registry::new(), - None, - Some(plugins.path()), - ); + let directory = dir_with_file(PAGE, TEXT)?; + let final_text = run_mapped_prompt( + "changes-the-mapping", + STD_LIBRARY, + CHANGING_PROMPT, + mounted(directory.path()), + ) + .await?; - let result = run_prompt_over(host, filesystem_with(directory.path())).await; - - let Ok(Ok(final_text)) = result else { - return Err(format!("the prompt did not complete: {result:?}").into()); - }; let refusals: Vec<&str> = final_text.lines().collect(); assert_eq!(refusals.len(), 3, "one line for each tool: {final_text}"); for (refusal, path) in refusals.iter().zip([ @@ -302,20 +238,12 @@ async fn the_file_tools_change_nothing_under_the_mapping() -> Outcome { ]) { assert!( refusal.ends_with(&format!("{path} is served read-only and cannot change")), - "the tool answers with the mapping's refusal: {refusal}" + "{refusal}" ); } - let page = directory.path().join(PAGE); - let text = - std::fs::read_to_string(&page).map_err(|e| format!("read {}: {e}", page.display()))?; - assert_eq!(text, TEXT, "the page is as it was"); - assert!(!directory.path().join("new.md").exists()); - Ok(()) + assert_dir_unchanged(directory.path()) } -/// A prompt that asks the shell to make a file in the mapped directory, -/// to remove its page, and to make a file in the in-memory root, and -/// returns what the shell answers. const CHANGING_SHELL_PROMPT: &str = r#"--- name: shells-into-the-mapping description: tries to change a mapped directory with the shell @@ -336,44 +264,35 @@ return tools.call('bash/shell', { #[tokio::test] async fn the_shell_changes_nothing_under_the_mapping_and_writes_beside_it() -> Outcome { - let directory = local_directory()?; - let vfs = filesystem_with(directory.path()); - let (plugins, _library) = plugin_dir_of("shells-into-the-mapping", BASHKIT_LIBRARY); - let host = server_host( - serving(CHANGING_SHELL_PROMPT), - &Registry::new(), - None, - Some(plugins.path()), - ); - - let result = run_prompt_over(host, vfs.clone()).await; + let directory = dir_with_file(PAGE, TEXT)?; + let vfs = mounted(directory.path()); + let final_text = run_mapped_prompt( + "shells-into-the-mapping", + BASHKIT_LIBRARY, + CHANGING_SHELL_PROMPT, + vfs.clone(), + ) + .await?; - let Ok(Ok(final_text)) = result else { - return Err(format!("the prompt did not complete: {result:?}").into()); - }; assert!( final_text.contains("```\nwrite 1\nremove 1\nkept\n"), - "the write and the removal under the mapping both fail, and the shell writes and \ - reads a file of the in-memory root: {final_text}" + "{final_text}" ); for path in ["/_runvil/test/new.md", "/_runvil/test/hello.md"] { assert!( final_text.contains(&format!("{path} is served read-only and cannot change\n")), - "the shell prints the mapping's refusal of {path}: {final_text}" + "{final_text}" ); } - let page = directory.path().join(PAGE); - let text = - std::fs::read_to_string(&page).map_err(|e| format!("read {}: {e}", page.display()))?; - assert_eq!(text, TEXT, "the page is as it was"); - assert!(!directory.path().join("new.md").exists()); - let access = vfs.acquire(Origin::new("check"))?; - assert_eq!(access.read_string("/scratch.txt")?, "kept\n"); + assert_dir_unchanged(directory.path())?; + assert_eq!( + vfs.acquire(Origin::new("check"))? + .read_string("/scratch.txt")?, + "kept\n" + ); Ok(()) } -/// A prompt that lists the root and reads a page of each mapped -/// directory with the shell, and returns what the shell answers. const SHELL_PROMPT: &str = r"--- name: shells-over-the-mappings description: reads two mapped directories with the shell @@ -392,28 +311,23 @@ return tools.call('bash/shell', { #[tokio::test] async fn the_shell_reads_two_directories_mapped_into_its_run() -> Outcome { - let first = local_directory()?; - let second = other_directory()?; - let vfs = mount_at(filesystem_with(first.path()), OTHER_MOUNT, second.path()); - let (plugins, _library) = plugin_dir_of("shells-over-the-mappings", BASHKIT_LIBRARY); - let host = server_host( - serving(SHELL_PROMPT), - &Registry::new(), - None, - Some(plugins.path()), - ); - - let result = run_prompt_over(host, vfs).await; + let first = dir_with_file(PAGE, TEXT)?; + let second = dir_with_file(OTHER_PAGE, OTHER_TEXT)?; + let vfs = mount_at(mounted(first.path()), OTHER_MOUNT, second.path()); + let final_text = run_mapped_prompt( + "shells-over-the-mappings", + BASHKIT_LIBRARY, + SHELL_PROMPT, + vfs, + ) + .await?; - let Ok(Ok(final_text)) = result else { - return Err(format!("the prompt did not complete: {result:?}").into()); - }; assert!( final_text.contains( "Exit code: 0\n\nCommand output:\n\n```\n_runvil\nc\n# Hello from another page\n\ # Hello from a local page\n```" ), - "the shell lists both mappings at the root and reads a page of each: {final_text}" + "{final_text}" ); Ok(()) } diff --git a/crates/workshop/server/src/agents/relay-tests.rs b/crates/workshop/server/src/agents/relay-tests.rs index 2c9f7573..a39b36a1 100644 --- a/crates/workshop/server/src/agents/relay-tests.rs +++ b/crates/workshop/server/src/agents/relay-tests.rs @@ -10,7 +10,7 @@ use tower::ServiceExt as _; use workshop_gateway::{GatewayBinding, GatewayHandles, GatewayHealth}; use workshop_registry::{Registration, Registry}; -use crate::agents::state::routes; +use crate::agents::routes; const CATALOG: &str = r#"{"object":"list","data":[{"id":"test-model","object":"model","created":1,"owned_by":"runvil"}]}"#; const UPSTREAM_ERROR: &str = @@ -35,7 +35,7 @@ async fn spawn_gateway(app: Router) -> String { /// through, the push sinks unregistered (pushes are graceful no-ops), /// the state directory a fresh tempdir returned alongside so it outlives /// the test. -fn state_for(base_url: &str) -> (SessionsState, tempfile::TempDir, Registration) { +fn state_for(base_url: &str) -> (SocketState, tempfile::TempDir, Registration) { let dir = tempfile::TempDir::new().expect("tempdir"); let registry = Registry::new(); let gateway = GatewayBinding::new(base_url, "test-key").expect("the binding builds"); @@ -43,7 +43,7 @@ fn state_for(base_url: &str) -> (SessionsState, tempfile::TempDir, Registration) ®istry, GatewayHandles::new(gateway, GatewayHealth::new()), ); - let state = SessionsState::new(registry, |_| true); + let state = SocketState::new(registry, |_| true); (state, dir, guard) } diff --git a/crates/workshop/server/src/agents/relay.rs b/crates/workshop/server/src/agents/relay.rs index 77a24450..62dc3086 100644 --- a/crates/workshop/server/src/agents/relay.rs +++ b/crates/workshop/server/src/agents/relay.rs @@ -1,26 +1,24 @@ //! The buffered gateway relay: the `/v1/models` catalog passthrough and -//! the helpers that shape gateway responses for the wire. +//! the helper that shapes gateway error envelopes for the wire. use axum::extract::State; use axum::http::{StatusCode, header}; use axum::response::{IntoResponse, Response}; - -use workshop_gateway::{GatewayError, GatewayResponse}; use workshop_protocol::{Activity, ErrorEnvelope}; -use workshop_registry::Push; +use workshop_support::{LEAK_DETAIL, envelope_response, render_message}; -use super::state::SessionsState; +use crate::websocket::SocketState; /// Relays the gateway's model catalog to the caller verbatim. /// /// While the heartbeat reports the gateway down, the route /// short-circuits: it answers 502 with a user-visible message instead of /// fetching the catalog. -pub(super) async fn models(State(state): State) -> Response { +pub(super) async fn models(State(state): State) -> Response { // An unregistered gateway subsystem reads as the health flag's // optimistic default; a registered one short-circuits while down. if state.health().is_some_and(|health| !health.is_reachable()) { - return envelope(StatusCode::BAD_GATEWAY, "Gateway unreachable".to_string()); + return envelope(StatusCode::BAD_GATEWAY, "Gateway unreachable"); } let push = state.push(); push.push_status_update( @@ -29,68 +27,37 @@ pub(super) async fn models(State(state): State) -> Response { Activity::General, ); let Some(gateway) = state.gateway_snapshot() else { - return envelope(StatusCode::BAD_GATEWAY, "Gateway unreachable".to_string()); + return envelope(StatusCode::BAD_GATEWAY, "Gateway unreachable"); }; - let result = gateway.client().list_models().await; - report_gateway_outcome(&push, &result, "GET /v1/models"); - relay(result) -} - -/// Reports a gateway call's outcome on the status bus: back to idle on -/// success, otherwise the error label matching the failure shape. -fn report_gateway_outcome( - push: &Push, - result: &Result, - route: &str, -) { - match result { - Ok(upstream) if upstream.status.is_success() => push.push_idle(), - Ok(upstream) => push.push_failure( - format!("Gateway error: {}", upstream.status), - format!("{route} answered a non-success status"), - Activity::General, - ), - Err(error) => push.push_failure("Connection lost", error.to_string(), Activity::General), - } -} - -/// Turns a gateway call outcome into the workshop's HTTP response. -/// -/// Success (any status) is relayed byte-for-byte; a transport failure -/// becomes `502 Bad Gateway` in the `gateway_unreachable` wire envelope. -fn relay(result: Result) -> Response { - match result { - Ok(upstream) => ( - upstream.status, - [(header::CONTENT_TYPE, "application/json")], - upstream.body, - ) - .into_response(), - Err(error) => envelope(StatusCode::BAD_GATEWAY, gateway_message(&error)), - } -} - -/// The wire message of a gateway transport failure: the error's own -/// summary line, with the source chain appended in debug builds only. -fn gateway_message(error: &GatewayError) -> String { - use std::fmt::Write as _; - let mut message = error.to_string(); - if workshop_support::LEAK_DETAIL { - let mut source = std::error::Error::source(error); - while let Some(cause) = source { - // fmt::Write to a String cannot fail; the Result is a trait - // artifact. - let _ = write!(message, ": {cause}"); - source = cause.source(); + match gateway.client().list_models().await { + Ok(upstream) => { + if upstream.status.is_success() { + push.push_idle(); + } else { + push.push_failure( + format!("Gateway error: {}", upstream.status), + "GET /v1/models answered a non-success status", + Activity::General, + ); + } + ( + upstream.status, + [(header::CONTENT_TYPE, "application/json")], + upstream.body, + ) + .into_response() + } + Err(error) => { + push.push_failure("Connection lost", error.to_string(), Activity::General); + envelope(StatusCode::BAD_GATEWAY, render_message(&error, LEAK_DETAIL)) } } - message } /// Renders one `gateway_unreachable` envelope at `status`. -fn envelope(status: StatusCode, message: String) -> Response { - let envelope = ErrorEnvelope::new(message, "gateway_unreachable"); - workshop_support::envelope_response(status, &envelope) +fn envelope(status: StatusCode, message: impl Into) -> Response { + let envelope = ErrorEnvelope::new(message.into(), "gateway_unreachable"); + envelope_response(status, &envelope) } #[cfg(test)] diff --git a/crates/workshop/server/src/agents/socket-tests.rs b/crates/workshop/server/src/agents/socket-tests.rs index 22b9fdc7..33d3c5e9 100644 --- a/crates/workshop/server/src/agents/socket-tests.rs +++ b/crates/workshop/server/src/agents/socket-tests.rs @@ -14,9 +14,13 @@ use workshop_gateway::ResolvedGateway; use workshop_support::{AgentsConfig, Config}; use super::*; +use crate::agents::LaunchRefusal; use crate::app::state_with_gateway; use crate::app::test_helpers::config_for; +#[path = "socket_frames-tests.rs"] +mod frames; + #[test] fn a_refused_launch_frame_includes_the_cause_text() { let cause = "agents directory is locked by another process"; @@ -24,7 +28,7 @@ fn a_refused_launch_frame_includes_the_cause_text() { source: io::Error::new(io::ErrorKind::PermissionDenied, cause), }); - let rendered = refusal_text(&refusal); + let rendered = render_message(&refusal, true); assert!( rendered.contains("agent session state unavailable"), @@ -39,7 +43,7 @@ fn a_refused_launch_frame_includes_the_cause_text() { #[test] fn an_unusable_gateway_renders_its_own_message_alone() { assert_eq!( - refusal_text(&LaunchRefusal::GatewayUnusable), + render_message(&LaunchRefusal::GatewayUnusable, true), "agent sessions need a usable gateway binding; check the gateway base URL and key" ); } diff --git a/crates/workshop/server/src/agents/socket.rs b/crates/workshop/server/src/agents/socket.rs index 49ca3c2a..c0c0a31c 100644 --- a/crates/workshop/server/src/agents/socket.rs +++ b/crates/workshop/server/src/agents/socket.rs @@ -29,50 +29,75 @@ use axum::extract::State; use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; use axum::http::HeaderMap; -use axum::response::Response; +use axum::response::{IntoResponse, Response}; +use runvil::event::Event; +use serde::Deserialize as _; +use serde_json::Value; use tokio::sync::broadcast; use tokio::sync::broadcast::error::RecvError; - -use workshop_agents::{Conversation, Delta, SessionEvent, SessionFailure, SessionState}; +use workshop_agents::{Conversation, Delta, DeltaKind, SessionEvent, SessionFailure, SessionState}; use workshop_protocol::{Activity, ErrorFrame, InputResponse}; -use workshop_support::recv_or_pending; +use workshop_support::{recv_or_pending, render_message}; -use super::LaunchRefusal; -use super::socket_frames::{delta_frame, drain_events, frame_entry}; -use super::state::SessionsState; -use crate::agents::wire::{AgentSessionFrame, AgentsFrame, RequestRefusal, SessionRequest}; -use crate::websocket::{cross_site_refusal, send_error, send_frame}; +use super::wire::{ + AgentDeltaFrame, AgentDeltaKind, AgentEventFrame, AgentSessionFrame, AgentsFrame, + RequestRefusal, SessionRequest, +}; +use crate::error::AppError; +use crate::websocket::{SocketState, encode_frame, forward_broadcast, send_error, send_frame}; /// Upgrades a `GET /agents/ws` request to an agent-session socket. A /// foreign `Origin` is refused with 403, as the workshop socket's /// upgrade is. pub(super) async fn upgrade( - State(state): State, + State(state): State, headers: HeaderMap, ws: WebSocketUpgrade, ) -> Response { if !state.origin_allowed(&headers) { - return cross_site_refusal(); + return AppError::CrossSite.into_response(); } ws.on_upgrade(move |socket| run_socket(socket, state)) } /// The attachment state of one socket: the conversation it serves and the /// per-client cursors deriving durable-frame indices. -pub(super) struct Attached { +struct Attached { /// The conversation this socket serves. - pub(super) conversation: Conversation, + conversation: Conversation, /// The next transcript index to consider; everything below it has /// been read (framed or skipped) for this client already. - pub(super) cursor: u64, + cursor: u64, /// The wire index the next framed entry takes: the count of /// transcript entries with a wire shape sent so far, so the durable /// frames number the transcript the client renders, gap-free. - pub(super) framed: u64, + framed: u64, +} + +/// A conversation's three live channels, subscribed together, so the +/// socket that attaches with them misses nothing sent from that point +/// on. A receiver still yields what was queued after its channel +/// closes, so a run that fails and ends before the socket attaches +/// still reaches it. +pub(super) struct Receivers { + events: broadcast::Receiver, + deltas: broadcast::Receiver, + errors: broadcast::Receiver, +} + +impl Receivers { + /// Subscribes to every live channel of `conversation`. + pub(super) fn subscribe(conversation: &Conversation) -> Receivers { + Receivers { + events: conversation.subscribe_events(), + deltas: conversation.subscribe_deltas(), + errors: conversation.subscribe_errors(), + } + } } /// Runs one agent-session socket until it closes or fails. -async fn run_socket(mut socket: WebSocket, state: SessionsState) { +async fn run_socket(mut socket: WebSocket, state: SocketState) { // The list is discovered per connect: the frame is a complete // snapshot, so a directory edited between connects is picked up by // the next window with no push machinery. An unregistered sessions @@ -86,7 +111,7 @@ async fn run_socket(mut socket: WebSocket, state: SessionsState) { let mut attached: Option = None; // The subscriptions are stored beside the attachment (not inside it) // so the select! arms below can borrow them while the inbound arm - // borrows `attached`; attach() and the arms keep them all in step. + // borrows `attached`; the arms keep them all in step. let mut events_rx: Option> = None; let mut deltas_rx: Option> = None; let mut errors_rx: Option> = None; @@ -104,18 +129,179 @@ async fn run_socket(mut socket: WebSocket, state: SessionsState) { // delivers everything past it whenever it runs. biased; received = recv_or_pending(&mut errors_rx) => { - forward_error(received, &mut errors_rx, &mut socket).await - } - inbound = socket.recv() => { - let subscriptions = (&mut events_rx, &mut deltas_rx, &mut errors_rx); - on_inbound(&state, inbound, &mut attached, subscriptions, &mut socket).await + forward_broadcast(received, &mut errors_rx, &mut socket, "agent error", |failure| { + encode_frame(&ErrorFrame::new(failure.message, None)) + }) + .await } + inbound = socket.recv() => match inbound { + Some(Ok(Message::Text(text))) => 'frame: { + let frame: Value = match serde_json::from_str(&text) { + Ok(frame) => frame, + Err(error) => { + send_error(&mut socket, None, format!("invalid JSON frame: {error}")) + .await; + break 'frame true; + } + }; + if frame.get("type").and_then(Value::as_str) == Some("input_response") { + let Some(current) = attached.as_ref() else { + send_error( + &mut socket, + None, + "input_response before a session is attached", + ) + .await; + break 'frame true; + }; + let response: InputResponse = match serde_json::from_value(frame) { + Ok(response) => response, + Err(error) => { + send_error( + &mut socket, + None, + format!("invalid input_response: {error}"), + ) + .await; + break 'frame true; + } + }; + let conversation = ¤t.conversation; + if conversation.send_input(response.text) { + // The run took the message: the turn is dispatched. + state.push().push_status_update( + "Running agent turn", + format!("agent `{}` is thinking", conversation.agent()), + Activity::Thinking, + ); + } else { + let message = if conversation.state() == SessionState::Closed + || conversation.run_id().is_some() + { + "The agent's run has ended, so your message was not sent." + } else { + "The agent is not taking messages yet, so your message was not sent." + }; + send_error(&mut socket, None, message).await; + } + break 'frame true; + } + + let request = SessionRequest::parse(&frame); + match &request { + Ok(SessionRequest::Cancel) => { + if let Some(current) = attached.as_ref() { + // A stop is a stop reason: no reply frame of any kind. The + // round in flight is dropped, and a message already sent + // stays queued for the agent. + current.conversation.stop_round(); + } else { + send_error(&mut socket, None, "cancel before a session is attached") + .await; + } + break 'frame true; + } + Err(refusal @ RequestRefusal::UnknownType) => { + send_error(&mut socket, None, refusal.to_string()).await; + break 'frame true; + } + Ok(SessionRequest::Launch { .. } | SessionRequest::Attach { .. }) + | Err( + RequestRefusal::LaunchWithoutAgent + | RequestRefusal::AttachWithoutSession, + ) => {} + } + + // One socket serves one conversation - agent windows are modal - so + // a second open on an attached socket is refused, before the frame's + // own shape is. + if attached.is_some() { + send_error( + &mut socket, + None, + "this socket already serves a session; agent windows are modal", + ) + .await; + break 'frame true; + } + let Some(agents) = state.agents() else { + send_error(&mut socket, None, "agent sessions are unavailable").await; + break 'frame true; + }; + let (conversation, receivers) = match request { + Ok(SessionRequest::Launch { agent }) => match agents.launch(&agent).await { + Ok(launched) => launched, + Err(refusal) => { + send_error(&mut socket, None, render_message(&refusal, true)).await; + break 'frame true; + } + }, + Ok(SessionRequest::Attach { session: id }) => { + let Some(conversation) = agents.get(&id) else { + send_error(&mut socket, None, "unknown agent session").await; + break 'frame true; + }; + let receivers = Receivers::subscribe(&conversation); + (conversation, receivers) + } + Err(refusal) => { + send_error(&mut socket, None, refusal.to_string()).await; + break 'frame true; + } + Ok(SessionRequest::Cancel) => break 'frame true, + }; + + // Take the subscriptions before the replay so nothing lands + // between them unseen, acknowledge with the session frame, + // and replay the transcript from index zero. + let Receivers { + events, + deltas, + errors, + } = receivers; + events_rx = Some(events); + deltas_rx = Some(deltas); + errors_rx = Some(errors); + let acknowledgment = + AgentSessionFrame::new(conversation.id().as_str(), conversation.agent()); + if !send_frame(&mut socket, &acknowledgment).await { + break 'frame false; + } + let mut next = Attached { + conversation, + cursor: 0, + framed: 0, + }; + if !drain_events(&mut next, &mut socket).await { + break 'frame false; + } + attached = Some(next); + true + } + Some(Ok(Message::Ping(_) | Message::Pong(_) | Message::Binary(_))) => true, + Some(Ok(Message::Close(_))) | None => false, + Some(Err(error)) => { + tracing::warn!(%error, "agent session socket failed"); + false + } + }, received = recv_or_pending(&mut deltas_rx) => { - forward_delta(received, &mut deltas_rx, &mut socket).await - } - received = recv_or_pending(&mut events_rx) => { - forward_event(received, &mut events_rx, attached.as_mut(), &mut socket).await + forward_broadcast(received, &mut deltas_rx, &mut socket, "agent delta", |delta| { + delta_frame(delta).and_then(|frame| encode_frame(&frame)) + }) + .await } + received = recv_or_pending(&mut events_rx) => match (received, attached.as_mut()) { + (Err(RecvError::Closed), _) => { + events_rx = None; + true + } + (Ok(entry), Some(current)) if entry.index <= current.cursor => { + frame_entry(current, &entry, &mut socket).await + } + (_, Some(current)) => drain_events(current, &mut socket).await, + (_, None) => true, + }, }; if !open { break; @@ -125,342 +311,65 @@ async fn run_socket(mut socket: WebSocket, state: SessionsState) { // replays the transcript. } -/// Forwards one session error report. Errors are ephemeral: a lagged -/// receiver misses only what the durable transcript shows as a turn with -/// no reply. A `false` return means the client is gone. -async fn forward_error( - received: Result, - errors_rx: &mut Option>, - socket: &mut WebSocket, -) -> bool { - match received { - Ok(failure) => send_frame(socket, &ErrorFrame::new(failure.message, None)).await, - Err(RecvError::Lagged(skipped)) => { - tracing::debug!(skipped, "agent error receiver lagged; reports dropped"); - true - } - Err(RecvError::Closed) => { - *errors_rx = None; - true - } - } -} - -/// Handles one inbound socket read. A `false` return means the socket -/// closed or failed, or the client is gone. -async fn on_inbound( - state: &SessionsState, - inbound: Option>, - attached: &mut Option, - subscriptions: Subscriptions<'_>, - socket: &mut WebSocket, -) -> bool { - match inbound { - Some(Ok(Message::Text(text))) => { - handle_frame(state, &text, attached, subscriptions, socket).await - } - Some(Ok(Message::Ping(_) | Message::Pong(_) | Message::Binary(_))) => true, - Some(Ok(Message::Close(_))) | None => false, - Some(Err(error)) => { - tracing::warn!(%error, "agent session socket failed"); - false - } - } -} - -/// Forwards one delta. Deltas are ephemeral: a lagged client skips chunks -/// and the superseding durable event repairs the transcript. A `false` -/// return means the client is gone. -async fn forward_delta( - received: Result, - deltas_rx: &mut Option>, - socket: &mut WebSocket, -) -> bool { - match received { - Ok(delta) => match delta_frame(delta) { - Some(frame) => send_frame(socket, &frame).await, - None => true, - }, - Err(RecvError::Lagged(skipped)) => { - tracing::debug!(skipped, "agent delta receiver lagged; chunks dropped"); - true - } - Err(RecvError::Closed) => { - *deltas_rx = None; - true - } - } -} - -/// Handles one event wakeup. The broadcast is only the wakeup: a live -/// entry at the cursor frames directly, and anything else (a gap, a lag, -/// even a closed receiver) drains the transcript from the cursor, so no -/// entry is ever lost. A `false` return means the client is gone. -async fn forward_event( - received: Result, - events_rx: &mut Option>, - attached: Option<&mut Attached>, - socket: &mut WebSocket, -) -> bool { - match (received, attached) { - (Err(RecvError::Closed), _) => { - *events_rx = None; - true - } - (received, Some(attached)) => on_event_wake(attached, received.ok(), socket).await, - (_, None) => true, - } -} - -/// A conversation's three live channels, subscribed together, so the -/// socket that attaches with them misses nothing sent from that point -/// on. A receiver still yields what was queued after its channel -/// closes, so a run that fails and ends before the socket attaches -/// still reaches it. -pub(super) struct Receivers { - events: broadcast::Receiver, - deltas: broadcast::Receiver, - errors: broadcast::Receiver, -} - -impl Receivers { - /// Subscribes to every live channel of `conversation`. - pub(super) fn subscribe(conversation: &Conversation) -> Receivers { - Receivers { - events: conversation.subscribe_events(), - deltas: conversation.subscribe_deltas(), - errors: conversation.subscribe_errors(), - } - } -} - -/// The three channel subscriptions an attachment holds, passed as one -/// bundle so [`handle_frame`] can replace them atomically on attach. -type Subscriptions<'a> = ( - &'a mut Option>, - &'a mut Option>, - &'a mut Option>, -); - -/// Handles one inbound text frame. A `false` return means the client is -/// gone and the socket loop should end. -async fn handle_frame( - state: &SessionsState, - text: &str, - attached: &mut Option, - subscriptions: Subscriptions<'_>, - socket: &mut WebSocket, -) -> bool { - let frame: serde_json::Value = match serde_json::from_str(text) { - Ok(frame) => frame, - Err(error) => { - send_error(socket, None, format!("invalid JSON frame: {error}")).await; - return true; - } - }; - let request = match frame.get("type").and_then(serde_json::Value::as_str) { - Some("input_response") => { - answer_input(state, frame, attached.as_ref(), socket).await; - return true; - } - _ => SessionRequest::parse(&frame), - }; - let open = match request { - Ok(SessionRequest::Cancel) => { - if let Some(attached) = attached.as_ref() { - // A stop is a stop reason: no reply frame of any kind. The - // round in flight is dropped, and a message already sent - // stays queued for the agent. - attached.conversation.stop_round(); - } else { - send_error(socket, None, "cancel before a session is attached").await; - } - return true; - } - Ok(SessionRequest::Launch { agent }) => Ok(OpenRequest::Launch { agent }), - Ok(SessionRequest::Attach { session }) => Ok(OpenRequest::Attach { session }), - Err(refusal @ RequestRefusal::UnknownType) => { - send_error(socket, None, refusal.to_string()).await; - return true; - } - Err( - refusal @ (RequestRefusal::LaunchWithoutAgent | RequestRefusal::AttachWithoutSession), - ) => Err(refusal), - }; - handle_open(state, open, attached, subscriptions, socket).await -} - -/// A [`SessionRequest`] that opens a conversation. -enum OpenRequest { - /// Start a conversation running `agent`. - Launch { agent: String }, - /// Reattach to the running conversation `session`. - Attach { session: String }, -} - -/// Handles an `input_response` frame: sends the operator's message to the -/// attached conversation's run and, when the run accepts it, reports the -/// dispatched turn; a message the run refuses is answered with an error -/// frame. -async fn answer_input( - state: &SessionsState, - frame: serde_json::Value, - attached: Option<&Attached>, - socket: &mut WebSocket, -) { - let Some(attached) = attached else { - send_error(socket, None, "input_response before a session is attached").await; - return; - }; - let response: InputResponse = match serde_json::from_value(frame) { - Ok(response) => response, - Err(error) => { - send_error(socket, None, format!("invalid input_response: {error}")).await; - return; - } +/// Renders a conversation's delta as the protocol's delta frame, the reply stamp +/// passed through; `None` for a side channel the wire has no label for, +/// dropped like a lagged delta because the completed-reply event repairs +/// the transcript. +fn delta_frame(delta: Delta) -> Option { + let channel = match delta.kind { + DeltaKind::Text => AgentDeltaKind::Text, + DeltaKind::Reasoning => AgentDeltaKind::Reasoning, + // The conversation's `DeltaKind` is `#[non_exhaustive]`. + _ => return None, }; - let conversation = &attached.conversation; - if conversation.send_input(response.text) { - // The run took the message: the turn is dispatched. - state.push().push_status_update( - "Running agent turn", - format!("agent `{}` is thinking", conversation.agent()), - Activity::Thinking, - ); - } else { - send_error(socket, None, refused_input_text(conversation)).await; - } + Some(AgentDeltaFrame::new(channel, delta.content, delta.reply)) } -/// The text of the error frame answering a message the run refused: the -/// run either has no Harness yet or has ended. A run that has started -/// takes every message until it ends, so a refusal after its start means -/// it ended, even before the conversation is `Closed`. -fn refused_input_text(conversation: &Conversation) -> &'static str { - if conversation.state() == SessionState::Closed || conversation.run_id().is_some() { - "The agent's run has ended, so your message was not sent." - } else { - "The agent is not taking messages yet, so your message was not sent." - } -} - -/// Handles a `launch` or `attach` request, or the refusal of a malformed -/// one: resolves the conversation it names and attaches the socket to -/// it. One socket serves one conversation - agent windows are modal - so -/// a second open on an attached socket is refused, before the frame's -/// own shape is. A `false` return means the client is gone. -async fn handle_open( - state: &SessionsState, - open: Result, - attached: &mut Option, - subscriptions: Subscriptions<'_>, - socket: &mut WebSocket, -) -> bool { - if attached.is_some() { - send_error( - socket, - None, - "this socket already serves a session; agent windows are modal", - ) - .await; - return true; - } - let Some(agents) = state.agents() else { - send_error(socket, None, "agent sessions are unavailable").await; - return true; - }; - let (conversation, receivers) = match open { - Ok(OpenRequest::Launch { agent }) => match agents.launch(&agent).await { - Ok(launched) => launched, - Err(refusal) => { - send_error(socket, None, refusal_text(&refusal)).await; - return true; - } - }, - Ok(OpenRequest::Attach { session: id }) => { - let Some(conversation) = agents.get(&id) else { - send_error(socket, None, "unknown agent session").await; - return true; - }; - let receivers = Receivers::subscribe(&conversation); - (conversation, receivers) - } - Err(refusal) => { - send_error(socket, None, refusal.to_string()).await; - return true; +/// Sends every transcript entry past the client's cursor as a durable +/// `agent_event` frame stamped with its wire index and, on the +/// model-round content kinds, the reply stamp its deltas had. A `false` +/// return means the client is gone. +async fn drain_events(attached: &mut Attached, socket: &mut WebSocket) -> bool { + let transcript = attached.conversation.transcript(attached.cursor); + for entry in &transcript { + if !frame_entry(attached, entry, socket).await { + return false; } - }; - attach(conversation, receivers, attached, subscriptions, socket).await -} - -/// The text of the error frame reporting a refused launch: the refusal -/// and its cause chain. A refusal's `Display` is only its own -/// message, so an unreadable agent source would otherwise reach the -/// client as the bare "agent session state unavailable" with the -/// filesystem's diagnosis gone. -fn refusal_text(refusal: &LaunchRefusal) -> String { - let mut text = refusal.to_string(); - let mut next = std::error::Error::source(refusal); - while let Some(cause) = next { - let _ = std::fmt::Write::write_fmt(&mut text, format_args!(": {cause}")); - next = cause.source(); } - text + true } -/// Attaches the socket to `conversation`: takes `receivers` as the -/// socket's three subscriptions (subscribed before the replay, so nothing -/// lands between them unseen), acknowledges with the session frame, and -/// replays the conversation's transcript from index zero, so a client -/// that attaches while the agent waits on its inbox ends on that wait's -/// `awaiting_input`. A `false` return means the client is gone. -async fn attach( - conversation: Conversation, - receivers: Receivers, - attached: &mut Option, - (events_rx, deltas_rx, errors_rx): Subscriptions<'_>, +/// Frames one transcript entry at or past the cursor and advances the +/// cursor over it. An entry with no wire shape (every lifecycle event but +/// the run's end, task and debug events, and a task's inbox events) +/// advances the cursor without a frame or a wire index. A `false` return +/// means the client is gone. +async fn frame_entry( + attached: &mut Attached, + entry: &SessionEvent, socket: &mut WebSocket, ) -> bool { - let Receivers { - events, - deltas, - errors, - } = receivers; - *events_rx = Some(events); - *deltas_rx = Some(deltas); - *errors_rx = Some(errors); - let acknowledgment = AgentSessionFrame::new( - conversation.id().to_string(), - conversation.agent().to_owned(), - ); - let mut state = Attached { - conversation, - cursor: 0, - framed: 0, - }; - if !send_frame(socket, &acknowledgment).await || !drain_events(&mut state, socket).await { - return false; + match advance(&mut attached.cursor, &mut attached.framed, entry) { + Some(text) => socket.send(Message::Text(text.into())).await.is_ok(), + None => true, } - *attached = Some(state); - true } -/// Frames what an event wakeup delivered: the live entry itself when it -/// is the entry at the cursor (or one the replay already covered, which -/// frames nothing), else - a gap past the cursor, or a lag that delivered -/// no entry - the transcript from the cursor on. A `false` return means -/// the client is gone. -async fn on_event_wake( - attached: &mut Attached, - entry: Option, - socket: &mut WebSocket, -) -> bool { - match entry { - Some(entry) if entry.index <= attached.cursor => { - frame_entry(attached, &entry, socket).await - } - _ => drain_events(attached, socket).await, +/// Moves the transcript `cursor` past `entry` and returns the entry's +/// serialized JSON frame, stamped with the wire index `framed` and +/// advancing it. An entry below the cursor was already read and moves +/// neither; an entry with no wire shape moves only the cursor. +fn advance(cursor: &mut u64, framed: &mut u64, entry: &SessionEvent) -> Option { + if entry.index < *cursor { + return None; } + *cursor = entry.index + 1; + // A stored payload this build cannot read has no wire shape either; + // the transcript's index sequence stays whole. + let event = Event::deserialize(&entry.event).ok()?; + let frame = AgentEventFrame::new(*framed, entry.reply, &event)?; + *framed += 1; + serde_json::to_string(&frame).ok() } #[cfg(test)] diff --git a/crates/workshop/server/src/agents/socket_frames-tests.rs b/crates/workshop/server/src/agents/socket_frames-tests.rs index 28961ab5..ecb11164 100644 --- a/crates/workshop/server/src/agents/socket_frames-tests.rs +++ b/crates/workshop/server/src/agents/socket_frames-tests.rs @@ -7,7 +7,7 @@ use runvil::event::Event; use runvil::ids::{ChainId, Provenance, TaskId}; use workshop_agents::{Delta, SessionEvent}; -use super::{advance, delta_frame}; +use super::super::{advance, delta_frame}; use crate::agents::wire::{AgentDeltaFrame, AgentDeltaKind, AgentEventFrame}; #[test] @@ -63,9 +63,10 @@ fn entry(index: u64, reply: Option, event: &Event) -> SessionEvent { } } -/// The frame `event` renders at wire index `index`. -fn frame(index: u64, reply: Option, event: &Event) -> AgentEventFrame { - AgentEventFrame::new(index, reply, event).expect("an operator message frames") +/// The serialized frame `event` renders at wire index `index`. +fn frame(index: u64, reply: Option, event: &Event) -> String { + let rendered = AgentEventFrame::new(index, reply, event).expect("an operator message frames"); + serde_json::to_string(&rendered).expect("an agent event frame serializes") } #[test] diff --git a/crates/workshop/server/src/agents/socket_frames.rs b/crates/workshop/server/src/agents/socket_frames.rs deleted file mode 100644 index 4abd0e7f..00000000 --- a/crates/workshop/server/src/agents/socket_frames.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! The agent socket's framing helpers: the pure render function that -//! maps the conversation's delta vocabulary onto Workshop's wire shape, -//! and the durable-event framing that drains a conversation's transcript -//! past the per-client cursor. - -use axum::extract::ws::WebSocket; -use runvil::event::Event; -use workshop_agents::{Delta, DeltaKind, SessionEvent}; - -use super::socket::Attached; -use crate::agents::wire::{AgentDeltaFrame, AgentDeltaKind, AgentEventFrame}; -use crate::websocket::send_frame; - -/// Renders a conversation's delta as the protocol's delta frame, the reply stamp -/// passed through; `None` for a side channel the wire has no label for, -/// dropped like a lagged delta because the completed-reply event repairs -/// the transcript. -pub(super) fn delta_frame(delta: Delta) -> Option { - let channel = match delta.kind { - DeltaKind::Text => AgentDeltaKind::Text, - DeltaKind::Reasoning => AgentDeltaKind::Reasoning, - // The conversation's `DeltaKind` is `#[non_exhaustive]`. - _ => return None, - }; - Some(AgentDeltaFrame::new(channel, delta.content, delta.reply)) -} - -/// Sends every transcript entry past the client's cursor as a durable -/// `agent_event` frame stamped with its wire index and, on the -/// model-round content kinds, the reply stamp its deltas had. A `false` -/// return means the client is gone. -pub(super) async fn drain_events(attached: &mut Attached, socket: &mut WebSocket) -> bool { - let transcript = attached.conversation.transcript(attached.cursor); - for entry in &transcript { - if !frame_entry(attached, entry, socket).await { - return false; - } - } - true -} - -/// Frames one transcript entry at or past the cursor and advances the -/// cursor over it. An entry with no wire shape (every lifecycle event but -/// the run's end, task and debug events, and a task's inbox events) -/// advances the cursor without a frame or a wire index. A `false` return -/// means the client is gone. -pub(super) async fn frame_entry( - attached: &mut Attached, - entry: &SessionEvent, - socket: &mut WebSocket, -) -> bool { - match advance(&mut attached.cursor, &mut attached.framed, entry) { - Some(frame) => send_frame(socket, &frame).await, - None => true, - } -} - -/// Moves the transcript `cursor` past `entry` and returns the entry's -/// frame, stamped with the wire index `framed` and advancing it. An entry -/// below the cursor was already read and moves neither; an entry with no -/// wire shape moves only the cursor. -fn advance(cursor: &mut u64, framed: &mut u64, entry: &SessionEvent) -> Option { - if entry.index < *cursor { - return None; - } - *cursor = entry.index + 1; - // A stored payload this build cannot read has no wire shape either; - // the transcript's index sequence stays whole. - let event = serde_json::from_value::(entry.event.clone()).ok()?; - let frame = AgentEventFrame::new(*framed, entry.reply, &event)?; - *framed += 1; - Some(frame) -} - -#[cfg(test)] -#[path = "socket_frames-tests.rs"] -mod tests; diff --git a/crates/workshop/server/src/agents/state.rs b/crates/workshop/server/src/agents/state.rs deleted file mode 100644 index d5574e7e..00000000 --- a/crates/workshop/server/src/agents/state.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! The sessions subsystem's shared route state and its registry -//! registration: the state every sessions route handler draws its -//! handles from, the router constructor, and the `register` entry point -//! the composition root calls. - -use std::ops::Deref; -use std::sync::Arc; - -use axum::Router; -use axum::http::HeaderMap; -use axum::routing::get; - -use workshop_registry::{Registration, Registry, RouteRegistrarAdapter}; -use workshop_support::{RELAY_DEADLINE, with_deadline}; - -use super::{AgentSessions, relay, socket}; -use crate::websocket::SocketState; - -/// The shared state of the sessions subsystem's routes: the socket state -/// every socket route shares (registry, origin policy, and the gateway -/// and push accessors, reached through `Deref`), plus the agent-session -/// opener, read through the registry's type-keyed state collection at -/// the point of use as an `Option` whose `None` degrades the feature. -#[derive(Debug, Clone)] -pub(crate) struct SessionsState { - socket: SocketState, -} - -impl SessionsState { - /// Builds the route state over the subsystem registry and the - /// server's origin policy. - #[must_use] - pub(crate) fn new(registry: Registry, origin_allowed: fn(&HeaderMap) -> bool) -> Self { - Self { - socket: SocketState::new(registry, origin_allowed), - } - } - - /// The agent-session opener behind `/agents/ws`, or `None` while - /// the sessions subsystem has not registered. - pub(super) fn agents(&self) -> Option { - self.registry() - .state::() - .map(|agents| (*agents).clone()) - } -} - -impl Deref for SessionsState { - type Target = SocketState; - - fn deref(&self) -> &SocketState { - &self.socket - } -} - -/// The sessions subsystem's routes: the `/v1/models` catalog relay on the -/// relay deadline, and the `/agents/ws` WebSocket upgrade, which answers -/// immediately and then outlives any deadline. -pub(super) fn routes(state: SessionsState) -> Router { - with_deadline( - Router::new().route("/v1/models", get(relay::models)), - RELAY_DEADLINE, - ) - .route("/agents/ws", get(socket::upgrade)) - .with_state(state) -} - -/// The sessions subsystem's registration guards: its routes and the -/// agent-session launcher. Dropping them deregisters the subsystem. -#[derive(Debug)] -#[must_use = "dropping the registrations deregisters the subsystem"] -pub(crate) struct SessionsRegistrations { - /// The `/v1/models` and `/agents/ws` route registrar. - pub(crate) routes: Registration, - /// The agent-session launcher as a state handle. - pub(crate) agents: Registration, -} - -/// Registers the sessions subsystem into the registry: its routes, merged -/// into the server's API router, and the agent-session launcher as a -/// state handle. The returned guards keep the registrations alive; the -/// composition root holds them for the process lifetime. -pub(crate) fn register( - registry: &Registry, - state: &SessionsState, - agents: &AgentSessions, -) -> SessionsRegistrations { - let routes = registry.register_routes(Arc::new(RouteRegistrarAdapter::new({ - let state = state.clone(); - move || routes(state.clone()) - }))); - let agents = registry.register_state::(Arc::new(agents.clone())); - SessionsRegistrations { routes, agents } -} diff --git a/crates/workshop/server/src/agents/status-tests.rs b/crates/workshop/server/src/agents/status-tests.rs index f4e4feae..b1055d44 100644 --- a/crates/workshop/server/src/agents/status-tests.rs +++ b/crates/workshop/server/src/agents/status-tests.rs @@ -3,12 +3,16 @@ use std::fmt; use std::time::Duration; +use runvil::event::Event; use runvil::ids::{ChainId, Provenance, RoundId, TaskId}; -use workshop_protocol::Severity; -use workshop_registry::Registry; +use tokio::sync::broadcast; +use workshop_agents::{Delta, FailureKind, SessionEvent, SessionFailure}; +use workshop_protocol::{Activity, Severity}; +use workshop_registry::{Push, Registry}; use workshop_status::StatusBus; +use workshop_support::ReconnectBackoff; -use super::*; +use crate::agents::{on_delta, on_error, on_event, report}; /// A push facade wired to a real status bus through the registry, with /// the bus's receiver and the registration guards a test reads through. diff --git a/crates/workshop/server/src/agents/status.rs b/crates/workshop/server/src/agents/status.rs deleted file mode 100644 index 115de31e..00000000 --- a/crates/workshop/server/src/agents/status.rs +++ /dev/null @@ -1,142 +0,0 @@ -//! The server's status reporter for one agent conversation: the -//! status-bar frames and the backoff reset, derived in the server from -//! the conversation's live events, deltas, and failure reports. -//! -//! One reporter task per conversation, spawned at launch. It holds only -//! the conversation's broadcast receivers, never the conversation, and -//! the conversation's channels close when its run ends, so the loop -//! returns with it. - -use runvil::event::Event; -use runvil::ids::{ChainId, TaskId}; -use tokio::sync::broadcast; -use workshop_agents::{Conversation, Delta, DeltaKind, FailureKind, SessionEvent, SessionFailure}; -use workshop_protocol::Activity; -use workshop_registry::Push; -use workshop_support::ReconnectBackoff; - -/// Spawns the reporter for `conversation`, reporting through `push` and -/// resetting `backoff` on completed replies. -pub(super) fn spawn_reporter(conversation: &Conversation, push: Push, backoff: ReconnectBackoff) { - let events = conversation.subscribe_events(); - let deltas = conversation.subscribe_deltas(); - let errors = conversation.subscribe_errors(); - tokio::spawn(report(events, deltas, errors, push, backoff)); -} - -/// Reports until all of the conversation's channels have closed. They -/// close together as the run ends, when its last reports, its success or -/// its failure, can still be queued, so each channel is drained to its -/// close. Deltas are drained ahead of events, so a round's activity -/// pulses precede the idle the main chain's next wait or its run's -/// success pushes when both sit queued. -async fn report( - mut events: broadcast::Receiver, - mut deltas: broadcast::Receiver, - mut errors: broadcast::Receiver, - push: Push, - backoff: ReconnectBackoff, -) { - let (mut deltas_open, mut events_open, mut errors_open) = (true, true, true); - loop { - tokio::select! { - biased; - received = deltas.recv(), if deltas_open => match received { - Ok(delta) => on_delta(&delta, &push), - // Pulses are ephemeral: a lost chunk's LED state is - // repaired by the next one or by the next wait's idle. - Err(broadcast::error::RecvError::Lagged(_)) => {} - Err(broadcast::error::RecvError::Closed) => deltas_open = false, - }, - received = events.recv(), if events_open => match received { - Ok(event) => on_event(&event, &push, &backoff), - // A lagged receiver missed at most a status transition the - // next event restates; the transcript still holds every event. - Err(broadcast::error::RecvError::Lagged(_)) => {} - Err(broadcast::error::RecvError::Closed) => events_open = false, - }, - received = errors.recv(), if errors_open => match received { - Ok(failure) => on_error(&failure, &push), - // Reports are ephemeral like the deltas; a lagged receiver - // missed a failure the error frame already reported. - Err(broadcast::error::RecvError::Lagged(_)) => {} - Err(broadcast::error::RecvError::Closed) => errors_open = false, - }, - else => return, - } - } -} - -/// The activity pulse that lights the status LED: Generating for answer -/// content, Thinking for the reasoning side channel. -fn on_delta(delta: &Delta, push: &Push) { - let activity = match delta.kind { - DeltaKind::Reasoning => Activity::Thinking, - // `Text`, or any other kind of the conversation's - // `#[non_exhaustive]` `DeltaKind`: the agent is producing output. - _ => Activity::Generating, - }; - push.push_activity("Streaming response...", "an agent response chunk", activity); -} - -/// The side effects the server wires to the conversation's events: the -/// backoff reset at a completed reply (an agent reply is useful gateway -/// work), and the idle status that releases the turn-dispatch Thinking -/// push once the main chain waits on its inbox or its run succeeds. A -/// reply alone leaves the status busy, since a message that lands as it -/// does makes the loop go on. A failed run's end pushes nothing, since -/// its failure report sets the status. -fn on_event(event: &SessionEvent, push: &Push, backoff: &ReconnectBackoff) { - let Ok(event) = serde_json::from_value::(event.event.clone()) else { - // An event payload this build cannot read: the status bar has - // nothing to say about it. - return; - }; - match event { - Event::AssistantReply { .. } => backoff.record_useful_work(), - Event::InboxWaiting { provenance, .. } | Event::RunSucceeded { provenance, .. } - if provenance.task == TaskId::from(ChainId::root()) => - { - push.push_idle(); - } - _ => {} - } -} - -/// The label for a run that ended in error or was cut short: the agent -/// itself is gone. -const RUN_FAILED_LABEL: &str = "Agent failed"; - -/// The operator-facing failure status for one of the conversation's -/// failure reports. The conversation reports the kind - a failed model -/// turn or tool call the program survived, a run that ended in error, or -/// a run a close cut short - and the server labels it; the report's -/// message passes through as the description, the same text the socket's -/// error frame reports. Each kind is terminal for its turn, so this status -/// releases the turn-dispatch Thinking push at once. A run that failed or -/// was cut short waits on its inbox no more, so for it this status is the -/// one frame that does; without it the status bar's sustained amber LED -/// never returns to idle. -fn on_error(failure: &SessionFailure, push: &Push) { - push.push_failure( - failure_label(failure.kind), - &failure.message, - Activity::General, - ); -} - -/// The status label for one failure kind: a survived turn is labelled by -/// its boundary, so the status bar tells a still-running agent from one -/// whose run ended. The match is exhaustive on purpose: a new kind fails -/// this build until it is labelled here. -fn failure_label(kind: FailureKind) -> &'static str { - match kind { - FailureKind::ModelTurnFailed => "Model turn failed", - FailureKind::ToolCallFailed => "Tool call failed", - FailureKind::RunFailed | FailureKind::Canceled => RUN_FAILED_LABEL, - } -} - -#[cfg(test)] -#[path = "status-tests.rs"] -mod tests; diff --git a/crates/workshop/server/src/agents/tests.rs b/crates/workshop/server/src/agents/tests.rs index bc33c1ad..9055143f 100644 --- a/crates/workshop/server/src/agents/tests.rs +++ b/crates/workshop/server/src/agents/tests.rs @@ -1,32 +1,5 @@ -//! The agent conversations' Harness setup: after the server installs the -//! linked mcp Plugin, loads the std and web Plugins' libraries from its -//! Plugin directory, and builds its Host, every run of a conversation, -//! which has a user, holds the `web`, `subagents`, `mcp`, `std`, and -//! `user` Packs. A prompt declaring `web` prepares over a Plugin -//! directory that holds the web library, and one declaring the built-in -//! `subagents` prepares over the server's installed Packs. The `mcp.json` -//! reader returns the `mcpServers` object as it stands, or an empty one. -//! A prompt declaring `mcp` prepares on a Host built on a runtime, whose -//! handle the mcp Pack is installed with, and a Host built outside a -//! runtime installs no mcp Pack and refuses that prompt. The servers -//! value is the mcp Pack's server list, so one it refuses refuses a -//! prompt requiring `mcp` as it parses. The Host's finder refuses an -//! unknown agent as `NotFound` and an unreadable one as `Io`, each with -//! the launch refusal's own text, and it reads an agent that another -//! names under `prompts:`, which that agent then runs with `execute`. A -//! configured Plugin directory loads each library Plugin in it and -//! reports each file that is none, a directory that does not exist -//! loads nothing, and one that cannot be read is a failure of the Host's -//! report while the Host is built. A prompt reads and changes the files -//! of its run through -//! the std library's `Read`, `Write`, `StrReplace`, and `Delete` tools -//! and through the bashkit library's `Shell` tool, and the Host reads -//! each change back after the run. A Host with no Plugin directory -//! refuses a prompt that requires `std`, `bash`, or `web`. A run's -//! streaming callback publishes each piece it is handed into its -//! conversation, under the id of the round the piece belongs to. The -//! Gateway that a tool call of a library Plugin is lent has its tests in -//! `gateway`. +//! Harness setup tests for agent conversations: Packs, Plugin directories, +//! `mcp.json` reading, prompt finder, VFS tools, and delta streaming. use std::env::consts::{DLL_EXTENSION, DLL_PREFIX, DLL_SUFFIX}; use std::path::PathBuf; @@ -50,10 +23,20 @@ use super::{ read_mcp_servers, resources, server_host, with_plugins, }; +#[path = "bindings-tests.rs"] +mod bindings; #[path = "tests-gateway.rs"] mod gateway; +#[path = "language_guide/tests.rs"] +mod language_guide; +#[path = "status-tests.rs"] +mod status; + +static PLUGIN_DIRS: AtomicUsize = AtomicUsize::new(0); +pub(super) const STD_LIBRARY: &str = "plugin_std"; +pub(super) const BASHKIT_LIBRARY: &str = "plugin_bashkit"; +const WEB_LIBRARY: &str = "plugin_web"; -/// A prompt that requires the Pack `pack` and returns a fixed text. fn requiring(pack: &str) -> String { format!( "---\nname: browses\ndescription: needs {pack}\nrunvil: 0\n\ @@ -62,21 +45,17 @@ fn requiring(pack: &str) -> String { ) } -/// A finder that gives `source` under every name. pub(super) fn serving(source: impl Into) -> Arc { let source = source.into(); Arc::new(move |_: &str| -> Result { Ok(source.clone()) }) } -/// The report of the Plugin directory of `host`, which is the last step -/// its builder names. fn directory_report(host: &Host) -> &PluginReport { host.plugin_reports() .last() .expect("the Host names a Plugin directory") } -/// The name of each Plugin that the Plugin directory of `host` loaded. fn loaded(host: &Host) -> Vec<&str> { directory_report(host) .plugins() @@ -85,22 +64,16 @@ fn loaded(host: &Host) -> Vec<&str> { .collect() } -/// Asserts that the Plugin directory of `host` reported no failure. #[track_caller] fn assert_no_failures(host: &Host) { let failures = directory_report(host).failures(); assert!(failures.is_empty(), "{failures:?}"); } -/// Runs the prompt that `host` finds under every name as one -/// conversation over the default in-memory filesystem; see -/// [`run_agent_on`]. async fn run_prompt(host: Arc) -> Result, String> { run_prompt_over(host, VfsRef::default()).await } -/// Runs the prompt that `host` finds under every name as one -/// conversation over the filesystem `vfs`; see [`run_agent_on`]. pub(super) async fn run_prompt_over( host: Arc, vfs: VfsRef, @@ -108,11 +81,6 @@ pub(super) async fn run_prompt_over( run_agent_on(host, "browses", vfs).await } -/// Runs the agent `name` of `host` as one conversation, which has a user, -/// over the filesystem `vfs`, then reads the conversation's state and how -/// it ended: the result of its one run, or the message of the run-failed -/// report when the Host refused the prompt as it parsed it and no run -/// began. async fn run_agent_on( host: Arc, name: &str, @@ -131,11 +99,7 @@ async fn run_agent_on( tokio::time::timeout(Duration::from_secs(10), conversation.run(host, name, setup)) .await .expect("the run ends in time"); - assert_eq!( - conversation.state(), - SessionState::Closed, - "the conversation ends with its run" - ); + assert_eq!(conversation.state(), SessionState::Closed); match conversation.run_id() { Some(run) => Ok(recorder.result(run).expect("the recorder ended the run")), None => Err(errors @@ -145,14 +109,47 @@ async fn run_agent_on( } } -/// An `mcp.json` file in a new directory holding `text`. -fn mcp_file(text: &str) -> (tempfile::TempDir, std::path::PathBuf) { +fn mcp_file(text: &str) -> (tempfile::TempDir, PathBuf) { let dir = tempfile::TempDir::new().expect("tempdir"); let path = dir.path().join("mcp.json"); std::fs::write(&path, text).expect("write fixture"); (dir, path) } +fn library_file(library: &str) -> String { + format!("{DLL_PREFIX}{library}{DLL_SUFFIX}") +} + +fn plugin_dir_with(test: &str, libraries: &[&str]) -> tempfile::TempDir { + let prefix = format!( + "{test}-{}-{}-", + std::process::id(), + PLUGIN_DIRS.fetch_add(1, Ordering::Relaxed) + ); + let dir = tempfile::Builder::new() + .prefix(&prefix) + .tempdir() + .expect("a temporary directory is made"); + let exe = std::env::current_exe().expect("the test executable has a path"); + let built = exe.parent().expect("the test executable has a directory"); + for library in libraries { + let file = library_file(library); + std::fs::copy(built.join(&file), dir.path().join(&file)) + .expect("the Plugin's library is copied"); + } + dir +} + +pub(super) fn plugin_dir_of(test: &str, library: &str) -> (tempfile::TempDir, PathBuf) { + let dir = plugin_dir_with(test, &[library]); + let copy = dir.path().join(library_file(library)); + (dir, copy) +} + +pub(super) fn plugin_dir(test: &str) -> (tempfile::TempDir, PathBuf) { + plugin_dir_of(test, STD_LIBRARY) +} + #[tokio::test] async fn every_run_holds_the_packs_the_three_plugins_add_and_the_builtins() { let lists = "---\nname: lists\ndescription: reads its Packs\nrunvil: 0\n---\n\n\ @@ -166,50 +163,49 @@ async fn every_run_holds_the_packs_the_three_plugins_add_and_the_builtins() { let host = server_host(serving(lists), &Registry::new(), None, Some(dir.path())); assert_eq!( run_prompt(host).await, - Ok(Ok("web,subagents,mcp,std,user|nil".to_owned())), - "a run that declares nothing holds every runvil Pack the server installed, the \ - built-ins, and the user Pack its user brings, and no user-input Pack" - ); -} - -#[tokio::test] -async fn a_prompt_declaring_web_prepares_on_the_servers_built_packs() { - let (dir, _library) = plugin_dir_of("declares-web", WEB_LIBRARY); - let host = server_host( - serving(requiring("web")), - &Registry::new(), - None, - Some(dir.path()), - ); - assert_no_failures(&host); - assert_eq!(loaded(&host), ["web"]); - assert_eq!( - run_prompt(host).await, - Ok(Ok("browsed".to_owned())), - "the web library's Pack is installed, so a prompt that requires web runs" + Ok(Ok("web,subagents,mcp,std,user|nil".to_owned())) ); } #[tokio::test] -async fn a_prompt_declaring_subagents_prepares_on_the_servers_built_packs() { - let host = server_host( - serving(requiring("subagents")), - &Registry::new(), - None, - None, - ); - assert_eq!( - run_prompt(host).await, - Ok(Ok("browsed".to_owned())), - "the server's Host installs the built-in subagents" - ); +async fn prompts_declaring_available_packs_prepare_and_run() { + const CASES: &[(&str, &str, Option<&str>, Option<&str>)] = &[ + ("library-web", "web", Some(WEB_LIBRARY), Some("web")), + ("library-std", "std", Some(STD_LIBRARY), Some("std")), + ( + "library-bash", + "bash", + Some(BASHKIT_LIBRARY), + Some("bashkit"), + ), + ("builtin-subagents", "subagents", None, None), + ("runtime-mcp", "mcp", None, None), + ]; + + for &(label, pack, library, expected_plugin) in CASES { + let dir = library.map(|lib| plugin_dir_of(label, lib)); + let plugin_path = dir.as_ref().map(|(d, _)| d.path()); + let host = server_host( + serving(requiring(pack)), + &Registry::new(), + None, + plugin_path, + ); + if let Some(plugin) = expected_plugin { + assert_no_failures(&host); + assert_eq!(loaded(&host), [plugin], "{label}"); + } + assert_eq!( + run_prompt(host).await, + Ok(Ok("browsed".to_owned())), + "{label}: prompt declaring {pack} prepares and runs" + ); + } } #[test] fn the_finder_refuses_an_unknown_agent_as_not_found_and_an_unreadable_one_as_io() { let dir = tempfile::TempDir::new().expect("tempdir"); - // Discovery lists `broken`, but its bytes are not UTF-8, so its read - // fails. std::fs::write(dir.path().join("broken.md"), [0xff, 0xfe]).expect("write fixture"); let finder = agent_finder(dir.path().to_path_buf()); @@ -225,8 +221,6 @@ fn the_finder_refuses_an_unknown_agent_as_not_found_and_an_unreadable_one_as_io( #[tokio::test] async fn an_agent_executes_an_agent_of_the_folder_that_its_prompts_list_names() { let dir = tempfile::TempDir::new().expect("tempdir"); - // A `prompts:` entry is the name the finder knows the agent under, - // which is the name discovery lists: the file's stem. let outer = "---\nname: outer\ndescription: runs inner\nrunvil: 0\n\ prompts:\n - inner\n---\n\n## Only\n\n```lua\n\ return 'outer got ' .. execute('inner', {})\n```\n"; @@ -243,16 +237,12 @@ async fn an_agent_executes_an_agent_of_the_folder_that_its_prompts_list_names() assert_eq!( run_agent_on(host, "outer", VfsRef::default()).await, - Ok(Ok("outer got inner ran".to_owned())), - "the Host's finder reads the listed agent, and `execute` runs it in the same run" + Ok(Ok("outer got inner ran".to_owned())) ); } #[tokio::test] async fn the_servers_of_the_configured_mcp_file_reach_the_mcp_pack() { - // Nothing listens on port 1, so neither server ever becomes ready. - // The Pack's listing still names each server it was handed, and the - // names are all this test reads. let (_dir, path) = mcp_file( r#"{ "mcpServers": { "docs": { "url": "http://127.0.0.1:1/mcp" }, @@ -269,123 +259,52 @@ async fn the_servers_of_the_configured_mcp_file_reach_the_mcp_pack() { end\n\ return table.concat(names, ',')\n```\n"; let host = server_host(serving(lists), &Registry::new(), Some(&path), None); - assert_eq!( - run_prompt(host).await, - Ok(Ok("docs,search".to_owned())), - "the mcp Pack lists the two servers the file names, in name order" - ); -} - -#[tokio::test] -async fn a_prompt_declaring_mcp_prepares_on_a_host_built_on_a_runtime() { - // The Host is built on this test's runtime, as the server builds its - // own, so the mcp Pack is installed with that runtime's handle, here - // over no servers. - let host = server_host(serving(requiring("mcp")), &Registry::new(), None, None); - assert_eq!( - run_prompt(host).await, - Ok(Ok("browsed".to_owned())), - "a Host built on a runtime installs the mcp Pack once" - ); + assert_eq!(run_prompt(host).await, Ok(Ok("docs,search".to_owned()))); } #[test] fn a_host_built_outside_a_runtime_installs_no_mcp_pack() { - // A synchronous test builds the Host outside a runtime, so the Host - // is built without the mcp Pack. The run itself needs a runtime, - // which starts only after the Host is built. let host = server_host(serving(requiring("mcp")), &Registry::new(), None, None); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .expect("a runtime for the run is built"); - let result = runtime.block_on(run_prompt(host)); - let Err(message) = result else { - panic!("the Host refuses the prompt as it parses: {result:?}"); + let Err(message) = runtime.block_on(run_prompt(host)) else { + panic!("the Host refuses the prompt as it parses"); }; assert!( message.contains("- mcp is unavailable: runvil/mcp is not installed"), - "the refusal names the Pack no Plugin inserted: {message}" + "{message}" ); } #[tokio::test] async fn the_servers_value_is_the_mcp_packs_server_list() { - // A value that is neither null nor an object is the one server list - // the install refuses, so only that value reaching it fails the run. - let host = with_plugins( - serving(requiring("mcp")), - resources(&Registry::new()), - json!([]), - None, - ); - - let result = run_prompt(host).await; - let Err(message) = result else { - panic!("the Host refuses the prompt as it parses: {result:?}"); - }; - assert!( - message.contains("- mcp is unavailable: the MCP configuration must be a JSON object"), - "the refusal names the mcp Pack and its server list rule: {message}" - ); -} - -/// Counts the Plugin directories this process has made, so two tests -/// never share one. -static PLUGIN_DIRS: AtomicUsize = AtomicUsize::new(0); - -/// The std Plugin's library, as Cargo names it. -const STD_LIBRARY: &str = "plugin_std"; - -/// The bashkit Plugin's library, as Cargo names it. -pub(super) const BASHKIT_LIBRARY: &str = "plugin_bashkit"; - -/// The web Plugin's library, as Cargo names it. -const WEB_LIBRARY: &str = "plugin_web"; - -/// The file name of the dynamic library `library`. -fn library_file(library: &str) -> String { - format!("{DLL_PREFIX}{library}{DLL_SUFFIX}") -} - -/// A Plugin directory for the test named `test`, holding a copy of each -/// dynamic library of `libraries`. Cargo builds each library beside this -/// test executable, because the crate depends on the `workshop-plugin-*` -/// crate that exports it. The directory's name comes from the test, the -/// process id, and a counter. -fn plugin_dir_with(test: &str, libraries: &[&str]) -> tempfile::TempDir { - let prefix = format!( - "{test}-{}-{}-", - std::process::id(), - PLUGIN_DIRS.fetch_add(1, Ordering::Relaxed) - ); - let dir = tempfile::Builder::new() - .prefix(&prefix) - .tempdir() - .expect("a temporary directory is made"); - let exe = std::env::current_exe().expect("the test executable has a path"); - let built = exe.parent().expect("the test executable has a directory"); - for library in libraries { - let file = library_file(library); - std::fs::copy(built.join(&file), dir.path().join(&file)) - .expect("the Plugin's library is copied"); + const INVALID_SERVERS: &[(&str, &str)] = &[ + ("array", "[]"), + ("string", r#""not-an-object""#), + ("number", "42"), + ("bool-true", "true"), + ("bool-false", "false"), + ]; + for &(label, raw) in INVALID_SERVERS { + let servers: serde_json::Value = + serde_json::from_str(raw).unwrap_or_else(|e| panic!("{label}: valid JSON: {e}")); + let host = with_plugins( + serving(requiring("mcp")), + resources(&Registry::new()), + servers, + None, + ); + let Err(message) = run_prompt(host).await else { + panic!("{label}: the Host refuses the prompt as it parses"); + }; + assert!( + message.contains("- mcp is unavailable: the MCP configuration must be a JSON object"), + "{label}: {message}" + ); } - dir -} - -/// A Plugin directory for the test named `test`, holding a copy of the -/// dynamic library `library`, and that copy's path. -pub(super) fn plugin_dir_of(test: &str, library: &str) -> (tempfile::TempDir, PathBuf) { - let dir = plugin_dir_with(test, &[library]); - let copy = dir.path().join(library_file(library)); - (dir, copy) -} - -/// A Plugin directory for the test named `test`, holding a copy of the -/// std Plugin's library, and that copy's path. -pub(super) fn plugin_dir(test: &str) -> (tempfile::TempDir, PathBuf) { - plugin_dir_of(test, STD_LIBRARY) } #[test] @@ -393,7 +312,6 @@ fn a_plugin_directory_loads_the_std_plugin_from_its_library() { let (dir, library) = plugin_dir("loads-std"); let host = server_host(serving(""), &Registry::new(), None, Some(dir.path())); let report = directory_report(&host); - assert!(report.failures().is_empty(), "{:?}", report.failures()); let [plugin] = report.plugins() else { panic!("one library loads one Plugin: {:?}", report.plugins()); @@ -402,7 +320,7 @@ fn a_plugin_directory_loads_the_std_plugin_from_its_library() { assert_eq!(plugin.version(), "0.1.0"); assert_eq!( plugin.source(), - &PluginSource::Library(std::path::absolute(&library).expect("the path is made absolute")) + &PluginSource::Library(std::path::absolute(&library).expect("absolute path")) ); } @@ -420,7 +338,7 @@ fn a_file_that_is_no_library_is_reported_and_the_std_plugin_still_loads() { }; assert_eq!(failure.code, ErrorCode::PluginLoadFailed); assert_eq!(failure.facts.get(&ErrorFact::Reason), Some(&json!("open"))); - let expected = std::path::absolute(&bad).expect("the path is made absolute"); + let expected = std::path::absolute(&bad).expect("absolute path"); assert_eq!( failure.facts.get(&ErrorFact::Path), Some(&json!(expected.display().to_string())) @@ -431,24 +349,24 @@ fn a_file_that_is_no_library_is_reported_and_the_std_plugin_still_loads() { fn a_listing_names_each_plugin_that_loads_and_each_library_that_does_not() { let (dir, _library) = plugin_dir("lists-std"); assert_eq!( - list_plugin_dir(dir.path()).expect("the directory is read"), + list_plugin_dir(dir.path()).expect("directory is read"), PluginListing { loaded: vec!["std 0.1.0".to_owned()], - failed: Vec::new(), + failed: Vec::new() } ); let bad = dir.path().join(format!("a-text-file.{DLL_EXTENSION}")); std::fs::write(&bad, "not a library").expect("write fixture"); - let listing = list_plugin_dir(dir.path()).expect("the directory is read"); + let listing = list_plugin_dir(dir.path()).expect("directory is read"); assert_eq!(listing.loaded, ["std 0.1.0"]); let [failed] = listing.failed.as_slice() else { panic!("the text file is the one failure: {:?}", listing.failed); }; - let path = std::path::absolute(&bad).expect("the path is made absolute"); + let path = std::path::absolute(&bad).expect("absolute path"); assert!( failed.starts_with(&format!("{}: ", path.display())), - "the line opens with the library's path: {failed}" + "{failed}" ); let missing = list_plugin_dir(&dir.path().join("absent")).expect_err("no such directory"); @@ -458,8 +376,6 @@ fn a_listing_names_each_plugin_that_loads_and_each_library_that_does_not() { #[test] fn a_plugin_directory_that_does_not_exist_loads_nothing() { let (dir, _library) = plugin_dir("missing-directory"); - // A synchronous test builds the Host outside a runtime, so the Plugin - // directory would be its one step. let host = server_host( serving(""), &Registry::new(), @@ -468,21 +384,16 @@ fn a_plugin_directory_that_does_not_exist_loads_nothing() { ); assert!( host.plugin_reports().is_empty(), - "a missing directory is a state, not a failure: {:?}", + "{:?}", host.plugin_reports() ); } #[test] fn a_plugin_directory_that_cannot_be_read_is_a_failure_and_the_host_is_built() { - // A regular file in the directory's place exists, so the Host names - // it, and it cannot be read as a directory. The directory around it - // is named for this test, as each Plugin directory here is. let dir = plugin_dir_with("cannot-be-read", &[]); let file = dir.path().join("plugins"); std::fs::write(&file, "not a directory").expect("write fixture"); - // A synchronous test builds the Host outside a runtime, so the Plugin - // directory is its one step. let host = server_host(serving(""), &Registry::new(), None, Some(&file)); let [report] = host.plugin_reports() else { @@ -499,31 +410,9 @@ fn a_plugin_directory_that_cannot_be_read_is_a_failure_and_the_host_is_built() { ); assert_eq!( failure.facts.get(&ErrorFact::Path), - Some(&json!(file.display().to_string())), - "the failure names the configured path" - ); - assert!( - holds(&host, "runvil/user") && !holds(&host, "runvil/std"), - "the Host is built, with its built-ins and no library Plugin's Pack" - ); -} - -#[tokio::test] -async fn the_servers_host_loads_its_plugin_directory_beside_the_linked_plugin() { - let (dir, _library) = plugin_dir("server-host"); - let host = server_host( - serving(requiring("std")), - &Registry::new(), - None, - Some(dir.path()), - ); - - assert_eq!(loaded(&host), ["std"]); - assert_eq!( - run_prompt(host).await, - Ok(Ok("browsed".to_owned())), - "the library's Pack is installed, so a prompt that requires std runs" + Some(&json!(file.display().to_string())) ); + assert!(holds(&host, "runvil/user") && !holds(&host, "runvil/std")); } #[test] @@ -542,10 +431,6 @@ fn only_a_plugin_directory_with_a_shipped_library_gives_the_host_its_pack() { } } -/// A prompt that declares `std` and returns what four of its tools -/// answer, in this order: `std/read` for `/notes.md`, `std/write` for a -/// file under a directory that is absent, `std/replace` for a text of -/// `/notes.md`, and `std/rm` for `/old.md`. const READS_AND_CHANGES: &str = "---\nname: changes\ndescription: reads and changes files\n\ runvil: 0\nuses:\n - std\n---\n\n## Only\n\n```lua\n\ local read = tools.call('std/read', { path = '/notes.md' })\n\ @@ -568,53 +453,30 @@ async fn a_prompt_reads_and_changes_files_of_its_run_through_the_std_library_plu assert_no_failures(&host); let vfs = VfsRef::default(); - let seed = vfs - .acquire(Origin::new("seed")) - .expect("a fresh memory filesystem acquires"); - seed.write("/notes.md", b"hello\nworld\n") - .expect("the file is seeded"); - seed.write("/old.md", b"old\n").expect("the file is seeded"); - - let result = run_prompt_over(host, vfs.clone()).await; - let Ok(Ok(text)) = result else { - panic!("the run ends with its text: {result:?}"); + let seed = vfs.acquire(Origin::new("seed")).expect("acquire"); + seed.write("/notes.md", b"hello\nworld\n").expect("seed"); + seed.write("/old.md", b"old\n").expect("seed"); + + let Ok(Ok(text)) = run_prompt_over(host, vfs.clone()).await else { + panic!("the run ends with its text"); }; - // Each numbered line holds a `|`, and the three trusted texts hold - // none, so the answers split from the right. let mut answers = text.rsplitn(4, '|'); - let mut next = || answers.next().expect("the prompt joins four answers"); + let mut next = || answers.next().expect("four answers"); let (delete, replace, write, read) = (next(), next(), next(), next()); - assert!( - read.contains(" 1|hello\n 2|world\n"), - "Read answers the file's numbered lines: {read}" - ); - assert!( - read.contains(" serde_json::Value { +fn agent_fixture() -> Value { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/agent-frames.json"); let text = std::fs::read_to_string(&path) .unwrap_or_else(|error| panic!("the fixture {} is readable: {error}", path.display())); serde_json::from_str(&text).unwrap_or_else(|error| panic!("the fixture is valid JSON: {error}")) } -/// The root task's zeroth sequence: the provenance every test event -/// holds, since the wire does not expose it. fn provenance() -> Provenance { Provenance::new(TaskId::from(ChainId::root()), 0) } -/// The provenance of the first task the main chain spawned. fn task_provenance() -> Provenance { Provenance::new(TaskId::from(ChainId::root().child(0)), 0) } -/// The operator's message in the `chat` section, as it entered the main -/// chain's inbox: the fixture's `agent_event_minimal` entry as the Engine -/// event it projects from. fn operator_message(text: &str) -> Event { Event::InboxMessage { section: "chat".to_owned(), @@ -47,9 +34,6 @@ fn operator_message(text: &str) -> Event { } } -/// The main chain parked on its empty inbox in the `chat` section: the -/// fixture's `agent_event_awaiting` entry as the Engine event it projects -/// from. fn awaiting() -> Event { Event::InboxWaiting { section: "chat".to_owned(), @@ -57,9 +41,6 @@ fn awaiting() -> Event { } } -/// The run's end in the `chat` section, reported under the main chain: -/// the fixture's `agent_event_run_ended` entry as the Engine event it -/// projects from. fn run_succeeded() -> Event { Event::RunSucceeded { section: "chat".to_owned(), @@ -67,19 +48,25 @@ fn run_succeeded() -> Event { } } -/// The fixture's `agent_event_stamped` entry as the Engine event it -/// projects from, every metrics section populated. -fn stamped_fixture_event() -> Event { +fn assistant_reply(text: &str, finish_reason: Option<&str>, metrics: Option) -> Event { Event::AssistantReply { section: "chat".to_owned(), provenance: provenance(), turn: 2, round: RoundId::new(1), - text: "hello".to_owned(), - finish_reason: Some("stop".to_owned()), + text: text.to_owned(), + finish_reason: finish_reason.map(str::to_owned), model: "llama-3".to_owned(), origin: ReplyOrigin::Chat, - metrics: Some( + metrics, + } +} + +fn stamped_fixture_event() -> Event { + assistant_reply( + "hello", + Some("stop"), + Some( CallMetrics::new() .with_usage(Some( Usage::new(7, 3, 10) @@ -105,210 +92,9 @@ fn stamped_fixture_event() -> Event { .with_mean_itl_ms(Some(8.25)), )), ), - } -} - -/// Serializes one frame to its JSON value. -fn wire(frame: &impl Serialize) -> serde_json::Value { - serde_json::to_value(frame).expect("the frame serializes") -} - -#[test] -fn an_agents_frame_serializes_the_discovered_names() { - assert_eq!( - wire(&AgentsFrame::new(vec![ - "chat".to_owned(), - "research".to_owned() - ])), - serde_json::json!({"type": "agents", "agents": ["chat", "research"]}), - "the wire shape matches the workshop protocol's frame taxonomy" - ); + ) } -#[test] -fn an_agent_session_frame_serializes_its_id_and_agent() { - assert_eq!( - wire(&AgentSessionFrame::new( - "a1b2".to_owned(), - "chat".to_owned() - )), - serde_json::json!({"type": "agent_session", "session": "a1b2", "agent": "chat"}), - ); -} - -#[test] -fn an_agent_event_frame_has_its_log_index_and_optional_reply_id() { - let event = operator_message("hi"); - let plain = wire(&AgentEventFrame::new(3, None, &event).expect("an operator message frames")); - assert_eq!(plain["type"], "agent_event"); - assert_eq!(plain["index"], 3, "the frame reports the entry's log index"); - assert!( - plain.get("reply").is_none(), - "an absent reply id is omitted from the wire, not serialized as null" - ); - assert_eq!( - plain["event"], - serde_json::json!({ - "kind": "user_message", "section": "chat", "turn": 0, "content": "hi", - }), - "the entry serializes in its ACP-labelled wire shape" - ); - let stamped = - wire(&AgentEventFrame::new(4, Some(1), &event).expect("an operator message frames")); - assert_eq!( - stamped["reply"], 1, - "a superseding event is stamped with the same reply id as its deltas" - ); -} - -#[test] -fn the_main_chains_inbox_events_frame_as_the_operators_message_and_the_wait_for_it() { - let message = wire( - &AgentEventFrame::new(1, None, &operator_message("two words")) - .expect("the main chain's message frames"), - ); - assert_eq!( - message["event"], - serde_json::json!({ - "kind": "user_message", "section": "chat", "turn": 0, "content": "two words", - }), - "a message in the main chain's inbox is the operator's, framed on turn 0" - ); - let waiting = - wire(&AgentEventFrame::new(0, None, &awaiting()).expect("the main chain's wait frames")); - assert_eq!( - waiting["event"], - serde_json::json!({ - "kind": "awaiting_input", "section": "chat", "turn": 0, "content": "", - }), - "the main chain parking on its empty inbox is the wait for the operator" - ); -} - -#[test] -fn the_main_chains_run_end_frames_as_run_ended_with_empty_content() { - let failed = Event::RunFailed { - section: "chat".to_owned(), - provenance: provenance(), - }; - for event in [run_succeeded(), failed] { - let frame = wire(&AgentEventFrame::new(5, None, &event).expect("the run's end frames")); - assert_eq!( - frame["event"], - serde_json::json!({ - "kind": "run_ended", "section": "chat", "turn": 0, "content": "", - }), - "a run that returned or failed takes no more messages: {event:?}" - ); - } - let foreign = Event::RunSucceeded { - section: "Worker".to_owned(), - provenance: task_provenance(), - }; - assert!( - AgentEventFrame::new(0, None, &foreign).is_none(), - "only the main chain reports the run's end, as only its inbox frames" - ); -} - -#[test] -fn a_tasks_inbox_events_have_no_wire_shape() { - let message = Event::InboxMessage { - section: "Worker".to_owned(), - provenance: task_provenance(), - text: "also cover the tests".to_owned(), - }; - let waiting = Event::InboxWaiting { - section: "Worker".to_owned(), - provenance: task_provenance(), - }; - for event in [message, waiting] { - assert!( - AgentEventFrame::new(0, None, &event).is_none(), - "a task's inbox is its owner's business, never the operator's: {event:?}" - ); - } -} - -#[test] -fn an_agent_event_frame_renders_tool_call_batches_and_skips_lifecycle_events() { - let batch = Event::AssistantToolCalls { - section: "chat".to_owned(), - provenance: provenance(), - turn: 1, - round: RoundId::new(0), - model: "llama-3".to_owned(), - calls: vec![ToolCallEvent::new( - "call_1", - "read_file", - serde_json::json!({ "path": "notes.txt" }), - )], - }; - let frame = wire(&AgentEventFrame::new(0, Some(0), &batch).expect("a tool-call batch frames")); - assert_eq!(frame["event"]["kind"], "tool_call"); - assert_eq!( - frame["event"]["content"], - r#"[{"id":"call_1","name":"read_file","arguments":{"path":"notes.txt"}}]"#, - "a batch renders as the JSON array of its calls in one string field" - ); - assert_eq!(frame["event"]["model"], "llama-3"); - - let lifecycle = Event::SectionStarted { - section: "chat".to_owned(), - provenance: provenance(), - }; - assert!( - AgentEventFrame::new(1, None, &lifecycle).is_none(), - "a lifecycle event has no wire label and never frames" - ); -} - -#[test] -fn an_agent_event_frame_keeps_the_model_on_thinking_and_the_call_id_on_tool_results() { - let thinking = Event::Thinking { - section: "chat".to_owned(), - provenance: provenance(), - turn: 2, - round: RoundId::new(1), - model: "llama-3".to_owned(), - text: "weighing the options".to_owned(), - }; - let thought = - wire(&AgentEventFrame::new(5, Some(2), &thinking).expect("a thinking event frames")); - assert_eq!( - thought["event"], - serde_json::json!({ - "kind": "agent_thought", "section": "chat", "turn": 2, - "content": "weighing the options", "model": "llama-3", - }), - "a thinking block keeps its model and omits the tool-call id" - ); - - let result = tool_result("call_7", "read_file", "files/read", None, "the file's text"); - let update = wire(&AgentEventFrame::new(6, None, &result).expect("a tool-result event frames")); - assert_eq!( - update["event"], - serde_json::json!({ - "kind": "tool_call_update", "section": "chat", "turn": 2, - "content": "the file's text", "tool_call_id": "call_7", - }), - "a tool result keeps the id it answers and its content, and omits the model" - ); -} - -#[test] -fn a_scripts_tool_result_stays_a_tool_call_update() { - let result = tool_result("", "fetch", "web/fetch", Some("runvil"), "the page"); - let frame = wire(&AgentEventFrame::new(7, None, &result).expect("a tool-result event frames")); - assert_eq!( - frame["event"]["kind"], "tool_call_update", - "only a message in the main chain's inbox is the operator's message" - ); -} - -/// An untrusted tool result in the `chat` section on turn 2, answering -/// `tool_call_id` (empty for a script's call) under `alias`, bound to the -/// tool `tool` of a Pack from `vendor`. fn tool_result( tool_call_id: &str, alias: &str, @@ -329,87 +115,251 @@ fn tool_result( } } +fn wire(frame: &impl Serialize) -> Value { + serde_json::to_value(frame).expect("the frame serializes") +} + #[test] -fn an_agent_delta_frame_is_stamped_with_its_superseding_reply_id() { - assert_eq!( - wire(&AgentDeltaFrame::new( - AgentDeltaKind::Text, - "po".to_owned(), - 2 - )), - serde_json::json!({"type": "agent_delta", "kind": "text", "content": "po", "reply": 2}), - ); - assert_eq!( - wire(&AgentDeltaFrame::new( - AgentDeltaKind::Reasoning, - "hmm".to_owned(), - 2 - )), - serde_json::json!({ - "type": "agent_delta", "kind": "reasoning", "content": "hmm", "reply": 2, - }), - ); +fn agent_event_projections_match_wire_contract() { + let cases: [(&str, u64, Option, Event, Value); 11] = [ + ( + "user_message_plain", + 3, + None, + operator_message("two words"), + json!({"kind": "user_message", "section": "chat", "turn": 0, "content": "two words"}), + ), + ( + "user_message_stamped", + 4, + Some(1), + operator_message("hi"), + json!({"kind": "user_message", "section": "chat", "turn": 0, "content": "hi"}), + ), + ( + "awaiting_input", + 0, + None, + awaiting(), + json!({"kind": "awaiting_input", "section": "chat", "turn": 0, "content": ""}), + ), + ( + "run_succeeded", + 5, + None, + run_succeeded(), + json!({"kind": "run_ended", "section": "chat", "turn": 0, "content": ""}), + ), + ( + "run_failed", + 5, + None, + Event::RunFailed { + section: "chat".to_owned(), + provenance: provenance(), + }, + json!({"kind": "run_ended", "section": "chat", "turn": 0, "content": ""}), + ), + ( + "assistant_reply_minimal_omits_optional_fields", + 8, + None, + assistant_reply("bare", None, None), + json!({"kind": "agent_message", "section": "chat", "turn": 2, "content": "bare", "model": "llama-3"}), + ), + ( + "assistant_reply_finish_reason_without_metrics", + 9, + Some(4), + assistant_reply("cut", Some("length"), None), + json!({"kind": "agent_message", "section": "chat", "turn": 2, "content": "cut", "model": "llama-3", "finish_reason": "length"}), + ), + ( + "tool_call_batch", + 0, + Some(0), + Event::AssistantToolCalls { + section: "chat".to_owned(), + provenance: provenance(), + turn: 1, + round: RoundId::new(0), + model: "llama-3".to_owned(), + calls: vec![ToolCallEvent::new( + "call_1", + "read_file", + json!({ "path": "notes.txt" }), + )], + }, + json!({ + "kind": "tool_call", "section": "chat", "turn": 1, "model": "llama-3", + "content": r#"[{"id":"call_1","name":"read_file","arguments":{"path":"notes.txt"}}]"#, + }), + ), + ( + "thinking_keeps_model_and_omits_tool_call_id", + 5, + Some(2), + Event::Thinking { + section: "chat".to_owned(), + provenance: provenance(), + turn: 2, + round: RoundId::new(1), + model: "llama-3".to_owned(), + text: "weighing the options".to_owned(), + }, + json!({"kind": "agent_thought", "section": "chat", "turn": 2, "content": "weighing the options", "model": "llama-3"}), + ), + ( + "tool_result_keeps_call_id_and_omits_model", + 6, + None, + tool_result("call_7", "read_file", "files/read", None, "the file's text"), + json!({"kind": "tool_call_update", "section": "chat", "turn": 2, "content": "the file's text", "tool_call_id": "call_7"}), + ), + ( + "script_tool_result_stays_tool_call_update", + 7, + None, + tool_result("", "fetch", "web/fetch", Some("runvil"), "the page"), + json!({"kind": "tool_call_update", "section": "chat", "turn": 2, "content": "the page", "tool_call_id": ""}), + ), + ]; + + for (label, index, reply, event, expected_event) in cases { + let frame = AgentEventFrame::new(index, reply, &event) + .unwrap_or_else(|| panic!("{label}: event must project onto a wire frame")); + let mut expected = json!({"type": "agent_event", "index": index, "event": expected_event}); + if let Some(reply_id) = reply { + expected["reply"] = json!(reply_id); + } + assert_eq!(wire(&frame), expected, "{label}"); + } +} + +#[test] +fn non_wire_events_do_not_frame() { + let cases: [(&str, Event); 5] = [ + ( + "task_inbox_message", + Event::InboxMessage { + section: "Worker".to_owned(), + provenance: task_provenance(), + text: "also cover the tests".to_owned(), + }, + ), + ( + "task_inbox_waiting", + Event::InboxWaiting { + section: "Worker".to_owned(), + provenance: task_provenance(), + }, + ), + ( + "task_run_succeeded", + Event::RunSucceeded { + section: "Worker".to_owned(), + provenance: task_provenance(), + }, + ), + ( + "task_run_failed", + Event::RunFailed { + section: "Worker".to_owned(), + provenance: task_provenance(), + }, + ), + ( + "lifecycle_section_started", + Event::SectionStarted { + section: "chat".to_owned(), + provenance: provenance(), + }, + ), + ]; + + for (label, event) in cases { + assert!( + AgentEventFrame::new(0, None, &event).is_none(), + "{label}: non-wire event must not frame" + ); + } } #[test] fn each_request_frame_parses_into_its_variant() { let cases = [ ( - serde_json::json!({"type": "launch", "agent": "chat"}), + "launch", + json!({"type": "launch", "agent": "chat"}), SessionRequest::Launch { agent: "chat".to_owned(), }, ), ( - serde_json::json!({"type": "attach", "session": "a1b2"}), + "attach", + json!({"type": "attach", "session": "a1b2"}), SessionRequest::Attach { session: "a1b2".to_owned(), }, ), ( - serde_json::json!({"type": "cancel"}), + "cancel_bare", + json!({"type": "cancel"}), SessionRequest::Cancel, ), ( - serde_json::json!({"type": "cancel", "id": 4}), + "cancel_with_id", + json!({"type": "cancel", "id": 4}), SessionRequest::Cancel, ), ]; - for (frame, expected) in cases { - assert_eq!(SessionRequest::parse(&frame), Ok(expected), "{frame}"); + for (label, frame, expected) in cases { + assert_eq!( + SessionRequest::parse(&frame), + Ok(expected), + "{label}: {frame}" + ); } } #[test] fn malformed_request_frames_are_refused_with_the_socket_messages() { - let unknown = "unknown frame type; expected \"launch\", \"attach\", \"input_response\", \ - or \"cancel\""; - let cases = [ + const UNKNOWN: &str = "unknown frame type; expected \"launch\", \"attach\", \ + \"input_response\", or \"cancel\""; + const CASES: &[(&str, &str, &str)] = &[ ( - serde_json::json!({"type": "launch"}), + "launch-missing-agent", + r#"{"type":"launch"}"#, "launch frame without an agent name", ), ( - serde_json::json!({"type": "launch", "agent": 7}), + "launch-numeric-agent", + r#"{"type":"launch","agent":7}"#, "launch frame without an agent name", ), ( - serde_json::json!({"type": "attach"}), + "attach-missing-session", + r#"{"type":"attach"}"#, "attach frame without a session id", ), ( - serde_json::json!({"type": "attach", "session": null}), + "attach-null-session", + r#"{"type":"attach","session":null}"#, "attach frame without a session id", ), - (serde_json::json!({"type": "mystery"}), unknown), - (serde_json::json!({"agent": "chat"}), unknown), - (serde_json::json!({"type": 7}), unknown), - (serde_json::json!(["cancel"]), unknown), - (serde_json::json!("cancel"), unknown), + ("unknown-type", r#"{"type":"mystery"}"#, UNKNOWN), + ("missing-type", r#"{"agent":"chat"}"#, UNKNOWN), + ("numeric-type", r#"{"type":7}"#, UNKNOWN), + ("array-frame", r#"["cancel"]"#, UNKNOWN), + ("string-frame", r#""cancel""#, UNKNOWN), ]; - for (frame, message) in cases { - let refusal = SessionRequest::parse(&frame).expect_err("the frame is refused"); - assert_eq!(refusal.to_string(), message, "{frame}"); + for &(label, raw, expected) in CASES { + let frame: Value = + serde_json::from_str(raw).unwrap_or_else(|e| panic!("{label}: valid JSON: {e}")); + let Err(refusal) = SessionRequest::parse(&frame) else { + panic!("{label}: {frame} must be refused"); + }; + assert_eq!(refusal.to_string(), expected, "{label}: {frame}"); } } @@ -439,20 +389,24 @@ fn the_shared_fixture_pins_exactly_the_agreed_case_list() { "input_response", "launch", ], - "both suites pin exactly the same case list, so a case added on \ - one side fails the other" + "both suites pin exactly the same case list, so a case added on one side fails the other" ); } #[test] fn server_to_client_agent_frames_match_the_shared_fixture() { - // Each typed frame serializes to its fixture entry, compared as - // values so key order in the file is free. let fixture = agent_fixture(); - let agents = AgentsFrame::new(vec!["chat".to_owned(), "research".to_owned()]); - assert_eq!(wire(&agents), fixture["agents"]); - let session = AgentSessionFrame::new("a1b2".to_owned(), "chat".to_owned()); - assert_eq!(wire(&session), fixture["agent_session"]); + assert_eq!( + wire(&AgentsFrame::new(vec![ + "chat".to_owned(), + "research".to_owned() + ])), + fixture["agents"] + ); + assert_eq!( + wire(&AgentSessionFrame::new("a1b2", "chat")), + fixture["agent_session"] + ); assert_eq!( wire(&AgentEventFrame::new(3, None, &operator_message("hi"))), fixture["agent_event_minimal"] @@ -470,10 +424,22 @@ fn server_to_client_agent_frames_match_the_shared_fixture() { fixture["agent_event_stamped"], "the event serializes in its wire shape, metrics and all" ); - let text = AgentDeltaFrame::new(AgentDeltaKind::Text, "po".to_owned(), 2); - assert_eq!(wire(&text), fixture["agent_delta_text"]); - let reasoning = AgentDeltaFrame::new(AgentDeltaKind::Reasoning, "hmm".to_owned(), 2); - assert_eq!(wire(&reasoning), fixture["agent_delta_reasoning"]); + assert_eq!( + wire(&AgentDeltaFrame::new( + AgentDeltaKind::Text, + "po".to_owned(), + 2 + )), + fixture["agent_delta_text"] + ); + assert_eq!( + wire(&AgentDeltaFrame::new( + AgentDeltaKind::Reasoning, + "hmm".to_owned(), + 2 + )), + fixture["agent_delta_reasoning"] + ); } #[test] diff --git a/crates/workshop/server/src/agents/wire.rs b/crates/workshop/server/src/agents/wire.rs index eac7765a..929e9886 100644 --- a/crates/workshop/server/src/agents/wire.rs +++ b/crates/workshop/server/src/agents/wire.rs @@ -9,20 +9,18 @@ //! frame holding its log index, replayed from the top on attach - and //! [`AgentDeltaFrame`]s, the ephemeral live chunks, each stamped with the //! `reply` id of its round. The event log says when the agent waits on -//! its empty inbox for the operator -//! (`awaiting_input`), holds each message the operator sent -//! (`user_message`), and closes with `run_ended` once the run ends, after -//! which the run takes no more messages. `{"type":"cancel"}` fires the -//! session's turn-cancel: cancellation is a stop reason, never an error - -//! no error frame follows, and the agent's chat loop returns to its -//! inbox, where it goes on with a message already queued and otherwise -//! waits. -//! Frames already in flight from the canceled round may still arrive -//! after the cancel: a defined grace window, never a protocol violation. -//! The canceled round never settles, so the SPA drops its pending chunks -//! once a later round settles. The three client requests parse as -//! [`SessionRequest`]; the operator's message, `input_response`, stays in -//! `workshop-protocol`. +//! its empty inbox for the operator (`awaiting_input`), holds each +//! message the operator sent (`user_message`), and closes with +//! `run_ended` once the run ends, after which the run takes no more +//! messages. `{"type":"cancel"}` fires the session's turn-cancel: +//! cancellation is a stop reason, never an error - no error frame +//! follows, and the agent's chat loop returns to its inbox, where it goes +//! on with a message already queued and otherwise waits. Frames already +//! in flight from the canceled round may still arrive after the cancel: a +//! defined grace window, never a protocol violation. The canceled round +//! never settles, so the SPA drops its pending chunks once a later round +//! settles. The three client requests parse as [`SessionRequest`]; the +//! operator's message, `input_response`, stays in `workshop-protocol`. //! //! A session-level failure is pushed as an id-less //! [`ErrorFrame`](workshop_protocol::ErrorFrame): a model round that @@ -41,10 +39,13 @@ //! SPA suite's `crates/workshop/ui/test/agent-wire-fixtures.mjs`, so drift //! on either side fails that side's tests. +use std::borrow::Cow; + use runvil::event::Event; use runvil::ids::{ChainId, TaskId}; use runvil::metrics::{CallMetrics, ToolCallEvent}; use serde::{Deserialize, Serialize}; +use serde_json::Value; /// A session request the client sends: `launch`, `attach`, or `cancel`. /// Fields beyond the ones a variant names are ignored. @@ -92,8 +93,8 @@ impl SessionRequest { /// /// # Errors /// Returns the [`RequestRefusal`] naming what the frame lacks. - pub(super) fn parse(frame: &serde_json::Value) -> Result { - let refusal = match frame.get("type").and_then(serde_json::Value::as_str) { + pub(super) fn parse(frame: &Value) -> Result { + let refusal = match frame.get("type").and_then(Value::as_str) { Some("launch") => RequestRefusal::LaunchWithoutAgent, Some("attach") => RequestRefusal::AttachWithoutSession, Some("cancel") => RequestRefusal::UnknownType, @@ -135,19 +136,19 @@ impl AgentsFrame { /// Delivery: durable - a direct per-request reply sent by the loop that /// owns the socket, the contract's no-cursor case. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] -pub(super) struct AgentSessionFrame { +pub(super) struct AgentSessionFrame<'a> { #[serde(rename = "type")] kind: &'static str, /// The session's unguessable id. - session: String, + session: &'a str, /// The launched agent's name. - agent: String, + agent: &'a str, } -impl AgentSessionFrame { +impl<'a> AgentSessionFrame<'a> { /// Builds the acknowledgment for `session` running `agent`. #[must_use] - pub(super) fn new(session: String, agent: String) -> Self { + pub(super) fn new(session: &'a str, agent: &'a str) -> Self { Self { kind: "agent_session", session, @@ -209,28 +210,28 @@ enum AgentEventKind { /// free-text field is untrusted model-, tool-, or user-authored data. #[derive(Debug, Clone, PartialEq, Serialize)] #[non_exhaustive] -struct AgentEvent { +struct AgentEvent<'a> { /// What kind of thing happened. kind: AgentEventKind, /// The reporting scope: the agent's name. - section: String, + section: &'a str, /// The model-turn counter the event was reported under. turn: u32, /// The kind-specific untrusted payload. - content: String, + content: Cow<'a, str>, /// The model that produced the event, for model-attributed kinds. #[serde(skip_serializing_if = "Option::is_none")] - model: Option, + model: Option<&'a str>, /// The provider-issued tool-call id the event answers to, for tool /// results. #[serde(skip_serializing_if = "Option::is_none")] - tool_call_id: Option, + tool_call_id: Option<&'a str>, /// The provider's finish reason, when it sent one. #[serde(skip_serializing_if = "Option::is_none")] - finish_reason: Option, + finish_reason: Option<&'a str>, /// Everything measured about the model call that produced the event. #[serde(skip_serializing_if = "Option::is_none")] - metrics: Option, + metrics: Option<&'a CallMetrics>, } /// Whether `event` was reported under the main chain, task `0`, whose @@ -239,7 +240,7 @@ fn on_main_chain(event: &Event) -> bool { event.provenance().task == TaskId::from(ChainId::root()) } -impl AgentEvent { +impl<'a> AgentEvent<'a> { /// Projects one Engine event onto the wire shape, or `None` for a /// variant the transcript does not render (every lifecycle event but /// the run's end, task and debug events, and a task's inbox events). A @@ -249,10 +250,10 @@ impl AgentEvent { /// `awaiting_input`, and the run's end under the main chain frames as /// `run_ended` with empty content. #[must_use] - fn from_event(event: &Event) -> Option { - let base = |kind: AgentEventKind, turn: u32, content: String| AgentEvent { + fn from_event(event: &'a Event) -> Option { + let base = |kind: AgentEventKind, turn: u32, content: Cow<'a, str>| AgentEvent { kind, - section: event.section().to_owned(), + section: event.section(), turn, content, model: None, @@ -264,8 +265,12 @@ impl AgentEvent { Event::Thinking { turn, model, text, .. } => AgentEvent { - model: Some(model.clone()), - ..base(AgentEventKind::Thinking, *turn, text.clone()) + model: Some(model.as_str()), + ..base( + AgentEventKind::Thinking, + *turn, + Cow::Borrowed(text.as_str()), + ) }, Event::AssistantReply { turn, @@ -275,29 +280,33 @@ impl AgentEvent { metrics, .. } => AgentEvent { - model: Some(model.clone()), - finish_reason: finish_reason.clone(), - metrics: metrics.clone(), - ..base(AgentEventKind::AssistantReply, *turn, text.clone()) + model: Some(model.as_str()), + finish_reason: finish_reason.as_deref(), + metrics: metrics.as_ref(), + ..base( + AgentEventKind::AssistantReply, + *turn, + Cow::Borrowed(text.as_str()), + ) }, Event::AssistantToolCalls { turn, model, calls, .. } => AgentEvent { - model: Some(model.clone()), + model: Some(model.as_str()), ..base( AgentEventKind::AssistantToolCalls, *turn, - render_tool_calls(calls), + Cow::Owned(render_tool_calls(calls)), ) }, Event::InboxMessage { text, .. } if on_main_chain(event) => { - base(AgentEventKind::UserInput, 0, text.clone()) + base(AgentEventKind::UserInput, 0, Cow::Borrowed(text.as_str())) } Event::InboxWaiting { .. } if on_main_chain(event) => { - base(AgentEventKind::AwaitingInput, 0, String::new()) + base(AgentEventKind::AwaitingInput, 0, Cow::Borrowed("")) } Event::RunSucceeded { .. } | Event::RunFailed { .. } if on_main_chain(event) => { - base(AgentEventKind::RunEnded, 0, String::new()) + base(AgentEventKind::RunEnded, 0, Cow::Borrowed("")) } Event::ToolResult { turn, @@ -305,8 +314,12 @@ impl AgentEvent { content, .. } => AgentEvent { - tool_call_id: Some(tool_call_id.clone()), - ..base(AgentEventKind::ToolResult, *turn, content.clone()) + tool_call_id: Some(tool_call_id.as_str()), + ..base( + AgentEventKind::ToolResult, + *turn, + Cow::Borrowed(content.as_str()), + ) }, _ => return None, }) @@ -331,7 +344,7 @@ fn render_tool_calls(calls: &[ToolCallEvent]) -> String { /// event log, and the per-client cursor recovers everything past it on /// reconnect. #[derive(Debug, Clone, PartialEq, Serialize)] -pub(super) struct AgentEventFrame { +pub(super) struct AgentEventFrame<'a> { #[serde(rename = "type")] kind: &'static str, /// The entry's log index. @@ -341,14 +354,14 @@ pub(super) struct AgentEventFrame { #[serde(skip_serializing_if = "Option::is_none")] reply: Option, /// The logged entry, in its wire shape. - event: AgentEvent, + event: AgentEvent<'a>, } -impl AgentEventFrame { +impl<'a> AgentEventFrame<'a> { /// Builds the frame for the entry at `index`, or `None` when `event` /// is a variant the transcript does not render. #[must_use] - pub(super) fn new(index: u64, reply: Option, event: &Event) -> Option { + pub(super) fn new(index: u64, reply: Option, event: &'a Event) -> Option { Some(Self { kind: "agent_event", index, diff --git a/crates/workshop/server/src/app.rs b/crates/workshop/server/src/app.rs index 69bd6656..64c8776b 100644 --- a/crates/workshop/server/src/app.rs +++ b/crates/workshop/server/src/app.rs @@ -9,7 +9,6 @@ //! runtime infrastructure - the shared reconnect backoff - plus the //! registration guards keeping every self-registration alive. -mod compose; #[cfg(any(test, feature = "test-fixtures"))] pub(crate) mod test_helpers; #[cfg(test)] @@ -17,25 +16,30 @@ mod tests; use std::fmt; use std::sync::Arc; +use std::time::Duration; use axum::Router; - -#[cfg(test)] -use workshop_gateway::GatewayBinding; +use axum::http::header; +use axum::middleware; +use axum::response::IntoResponse; +use axum::routing::get; use workshop_gateway::{ - GatewayClient, GatewayError, GatewayHandles, GatewayHealth, GatewaySnapshot, GatewayUpdater, - ResolvedGateway, + GatewayBinding, GatewayClient, GatewayError, GatewayHandles, GatewayHealth, GatewaySnapshot, + GatewayUpdater, ResolveError, ResolvedGateway, }; use workshop_menu::MenuHandles; use workshop_menu::catalog::CatalogBus; use workshop_menu::menu::MenuBus; -use workshop_registry::{Push, Registration, Registry}; +use workshop_registry::{MissingContribution, Push, Registration, Registry}; use workshop_status::StatusBus; use workshop_support::{Config, DEFAULT_DEADLINE, ReconnectBackoff, with_deadline}; +use workshop_user_state::UserStateStore; use workshop_workspace::Workspace; -use crate::agents::AgentSessions; -use crate::routes; +use crate::agents::{self, AgentSessions}; +use crate::websocket::SocketState; +use crate::workshop_socket::{self, WorkshopSocketState}; +use crate::{assets, cross_site, routes}; /// Shared handler state: the subsystem registry, the server's runtime /// infrastructure, and the registration guards. Subsystem handles - the @@ -48,15 +52,14 @@ pub struct AppState { registry: Registry, // Keeps the subsystems' self-registrations alive; dropping the last // state clone deregisters them. - _registrations: Registrations, + _registrations: Arc, } /// The registration guards keeping every subsystem's self-registrations /// alive: the push channels, the producer sinks, the state handles, the /// route registrars, and the background tasks. -#[derive(Clone)] struct Registrations { - guards: Vec>, + guards: Vec, } impl Registrations { @@ -66,7 +69,7 @@ impl Registrations { /// Holds one registration guard for the state's lifetime. fn hold(&mut self, guard: Registration) { - self.guards.push(Arc::new(guard)); + self.guards.push(guard); } } @@ -145,12 +148,6 @@ impl AppState { self.gateway_snapshot().client().clone() } - /// The replaceable Gateway binding shared with long-lived tasks. - #[cfg(test)] - pub(crate) fn gateway_binding(&self) -> GatewayBinding { - self.gateway_handles().binding().clone() - } - /// Restricted local-Gateway authority for the embedding binary. pub(crate) fn gateway_updater(&self) -> GatewayUpdater { self.gateway_handles().binding().updater() @@ -283,7 +280,7 @@ pub fn state_with_gateway( config: &Config, gateway: &ResolvedGateway, ) -> Result { - compose::compose(config, gateway, None, None) + compose(config, gateway, None, None) } /// [`state_with_gateway`] with the profile switch's sidecar restart bound @@ -298,9 +295,9 @@ pub fn state_with_gateway( pub fn state_with_gateway_and_restart_bound( config: &Config, gateway: &ResolvedGateway, - restart_bound: std::time::Duration, + restart_bound: Duration, ) -> Result { - compose::compose(config, gateway, None, Some(restart_bound)) + compose(config, gateway, None, Some(restart_bound)) } /// [`state_with_gateway`] with one subsystem's `register` call removed: @@ -317,7 +314,134 @@ pub fn state_with_gateway_omitting( gateway: &ResolvedGateway, omit: Omit, ) -> Result { - compose::compose(config, gateway, Some(omit), None) + compose(config, gateway, Some(omit), None) +} + +/// The composition root behind [`state_with_gateway`]; `omit` removes one +/// subsystem's `register` call for the boot-failure test, and +/// `restart_bound` replaces the `/ws` socket's sidecar restart bound when +/// given. +fn compose( + config: &Config, + gateway: &ResolvedGateway, + omit: Option, + restart_bound: Option, +) -> Result { + let status = StatusBus::new(); + let catalog = CatalogBus::new(); + // The per-profile model memory lives in the state directory; a bad + // or missing memory file costs the memory, never startup. + let state_dir = &config.server.state_dir; + // A crash between an atomic write's temp file and its rename + // orphans the temp; boot is the one moment the directory is + // known and quiet, so it is swept here. + workshop_support::sweep_orphaned_temps(state_dir); + let menu = MenuBus::new(catalog.clone(), Some(state_dir)); + // The subsystems self-register: consumers reach their channels, + // sinks, state handles, routes, and tasks through the registry's + // collections instead of by name. + let registry = Registry::new(); + let mut registrations = Registrations::new(); + + if omit != Some(Omit::Status) { + let regs = workshop_status::register(®istry, &status); + registrations.hold(regs.channel); + registrations.hold(regs.sink); + registrations.hold(regs.state); + } + + if omit != Some(Omit::Menu) { + let regs = workshop_menu::register(®istry, &catalog, &menu); + registrations.hold(regs.catalog_sink); + registrations.hold(regs.menu_sink); + registrations.hold(regs.state); + } + + let push = registry.push(); + // Startup phases are reported as they run; with no client connected + // yet these land on an empty bus, ready for the first session. + workshop_gateway::report(gateway, &push); + // The Gateway ships as a separate release, so the running one may be + // older than this Workshop needs. Its version arrives in the discovery + // file; an explicit config has no discovery file, so there is nothing + // to compare and the pin's minimum is simply not checked. + if let Some(identity) = gateway.identity() { + workshop_gateway::report_version(identity.version(), &push); + } + let gateway_binding = GatewayBinding::new_with_identity( + gateway.base_url(), + gateway.api_key(), + gateway.identity().cloned(), + ) + .map_err(StateError::Gateway)?; + let backoff = ReconnectBackoff::new(); + let health = GatewayHealth::new(); + let gateway_handles = GatewayHandles::new(gateway_binding, health); + if omit != Some(Omit::Gateway) { + registrations.hold(workshop_gateway::register( + ®istry, + gateway_handles.clone(), + )); + } + // The background tasks register beside the state handles; the server + // spawns them from the registry's task vector when it starts serving. + let tasks = workshop_gateway::register_tasks(®istry, &gateway_handles, backoff.clone()); + registrations.hold(tasks.heartbeat); + registrations.hold(tasks.subscriber); + + // The workspace remembers its last-used file in the state directory; + // boot follows that memory through `reopen_last_workspace` once the + // runtime is up, since the reopen is async and composition is not. + let workspace = Workspace::with_state_dir(state_dir); + if omit != Some(Omit::Workspace) { + let regs = workshop_workspace::register(®istry, &workspace); + registrations.hold(regs.routes); + registrations.hold(regs.state); + // The shutdown lever that closes the workspace file inside the + // graceful stop, so a quit leaves one complete file and no + // sidecar. + registrations.hold(workshop_workspace::register_tasks(®istry, &workspace)); + } + + if omit != Some(Omit::UserState) { + // The account-scoped UI state lives beside the menu memory in the + // state directory; a bad or missing file costs the state, never + // startup. + let user_state = Arc::new(UserStateStore::new(state_dir)); + let regs = workshop_user_state::register(®istry, user_state); + registrations.hold(regs.routes); + registrations.hold(regs.state); + } + + let agent_sessions = AgentSessions::new(config, registry.clone(), backoff.clone()); + let socket_state = SocketState::new(registry.clone(), cross_site::origin_allowed); + if omit != Some(Omit::AgentSessions) { + let regs = agents::register(®istry, &socket_state, &agent_sessions); + registrations.hold(regs.routes); + registrations.hold(regs.agents); + } + + let mut ws_state = WorkshopSocketState::new(registry.clone(), cross_site::origin_allowed); + if let Some(bound) = restart_bound { + ws_state = ws_state.with_restart_bound(bound); + } + registrations.hold(workshop_socket::register(®istry, &ws_state)); + + // The boot contract: every subsystem's handle set is present before + // state is shared, so a missing contribution fails here, naming the + // type, instead of panicking later at first use. + registry.require::()?; + registry.require::()?; + registry.require::()?; + registry.require::()?; + registry.require::()?; + registry.require::()?; + push.push_idle(); + Ok(AppState { + backoff, + registry, + _registrations: Arc::new(registrations), + }) } /// A shared-state construction failure: rich, init-only, and never sent @@ -334,14 +458,23 @@ pub enum StateError { /// no explicit `[gateway]` config. #[non_exhaustive] #[error("resolve the gateway endpoint")] - Resolution(#[source] workshop_gateway::ResolveError), + Resolution(#[source] ResolveError), /// A required subsystem contribution was never registered: the /// composition root itself is broken, so boot fails naming the /// absent type instead of panicking later at first use. #[non_exhaustive] #[error("compose the subsystem registry")] - Composition(#[from] workshop_registry::MissingContribution), + Composition(#[from] MissingContribution), +} + +/// Answers the stateless liveness probe with a static JSON body so it +/// responds even while every backing service is degraded. +async fn health() -> impl IntoResponse { + ( + [(header::CONTENT_TYPE, "application/json")], + r#"{"status":"serving"}"#, + ) } /// Returns the workshop server router with every route mounted: the @@ -351,30 +484,33 @@ pub enum StateError { /// routes sit behind the /// `crate::cross_site` guard; `/health` and the UI assets stay outside it /// so the desktop app probe, heartbeat, and initial navigation keep working. -/// Every response includes the `crate::csp` policy: the desktop app's webview -/// loads the UI as an External origin, so the server sets the page's -/// Content-Security-Policy. Each subsystem applies its own deadline tier: -/// the default on the workspace routes, the relay tier on `/v1/models`, -/// none on the WebSocket upgrades. +/// Every response includes the `crate::cross_site::csp_header` policy: the +/// desktop app's webview loads the UI as an External origin, so the server +/// sets the page's Content-Security-Policy. Each subsystem applies its own +/// deadline tier: the default on the workspace routes, the relay tier on +/// `/v1/models`, none on the WebSocket upgrades. pub fn router(state: AppState) -> Router { - let registry = state.registry().clone(); + let registrars = state.registry().routes(); let mut api = Router::new() .merge(routes::realtime::routes(state.clone())) .merge(routes::gateway_config::routes(state)) .merge(with_deadline(routes::prompts::routes(), DEFAULT_DEADLINE)); // The subsystems' routes merge in registration order; an empty // vector is a graceful no-op. - for registrar in registry.routes() { + for registrar in registrars { api = api.merge(registrar.routes()); } - let api = api.layer(axum::middleware::from_fn(crate::cross_site::guard)); + let api = api.layer(middleware::from_fn(cross_site::guard)); Router::new() - .merge(with_deadline(routes::assets::routes(), DEFAULT_DEADLINE)) - .merge(with_deadline(routes::health::routes(), DEFAULT_DEADLINE)) + .merge(with_deadline(assets::routes(), DEFAULT_DEADLINE)) + .merge(with_deadline( + Router::new().route("/health", get(health)), + DEFAULT_DEADLINE, + )) .merge(api) // The outermost layer on the server's own routes: every response // is stamped with the CSP, error envelopes included, so the desktop app's // External-origin webview runs under the policy no matter which // route answered. - .layer(axum::middleware::from_fn(crate::csp::header)) + .layer(middleware::from_fn(cross_site::csp_header)) } diff --git a/crates/workshop/server/src/app/compose.rs b/crates/workshop/server/src/app/compose.rs deleted file mode 100644 index 73f2d26f..00000000 --- a/crates/workshop/server/src/app/compose.rs +++ /dev/null @@ -1,223 +0,0 @@ -//! The composition root: constructs every subsystem, registers it into -//! the shared [`Registry`], and assembles the shared [`AppState`]. Each -//! subsystem owns a `register` helper here so the composition reads as a -//! single list of subsystem registrations in registration order. - -use std::sync::Arc; - -use workshop_gateway::{GatewayBinding, GatewayHandles, GatewayHealth, ResolvedGateway}; -use workshop_menu::MenuHandles; -use workshop_menu::catalog::CatalogBus; -use workshop_menu::menu::MenuBus; -use workshop_registry::{Push, Registry}; -use workshop_status::StatusBus; -use workshop_support::{Config, ReconnectBackoff}; -use workshop_user_state::UserStateStore; -use workshop_workspace::Workspace; - -use super::{AppState, Omit, Registrations, StateError}; -use crate::agents::{self, AgentSessions, SessionsState}; -use crate::workshop_socket::{self, WorkshopSocketState}; - -/// The composition root behind [`super::state_with_gateway`]; `omit` -/// removes one subsystem's `register` call for the boot-failure test, and -/// `restart_bound` replaces the `/ws` socket's sidecar restart bound when -/// given. -pub(super) fn compose( - config: &Config, - gateway: &ResolvedGateway, - omit: Option, - restart_bound: Option, -) -> Result { - let status = StatusBus::new(); - let catalog = CatalogBus::new(); - // The per-profile model memory lives in the state directory; a bad - // or missing memory file costs the memory, never startup. - let state_dir = &config.server.state_dir; - // A crash between an atomic write's temp file and its rename - // orphans the temp; boot is the one moment the directory is - // known and quiet, so it is swept here. - workshop_support::sweep_orphaned_temps(state_dir); - let menu = MenuBus::new(catalog.clone(), Some(state_dir)); - // The subsystems self-register: consumers reach their channels, - // sinks, state handles, routes, and tasks through the registry's - // collections instead of by name. - let registry = Registry::new(); - let mut registrations = Registrations::new(); - register_status(®istry, &mut registrations, &status, omit); - register_menu(®istry, &mut registrations, &catalog, &menu, omit); - let push = registry.push(); - let backoff = register_gateway(®istry, &mut registrations, gateway, &push, omit)?; - register_workspace(®istry, &mut registrations, state_dir, omit); - register_user_state(®istry, &mut registrations, state_dir, omit); - register_sessions(®istry, &mut registrations, config, &backoff, omit); - register_workshop_socket(®istry, &mut registrations, restart_bound); - // The boot contract: every subsystem's handle set is present before - // state is shared, so a missing contribution fails here, naming the - // type, instead of panicking later at first use. - registry.require::()?; - registry.require::()?; - registry.require::()?; - registry.require::()?; - registry.require::()?; - registry.require::()?; - push.push_idle(); - Ok(AppState { - backoff, - registry, - _registrations: registrations, - }) -} - -/// The status subsystem: its bus plus the push channel, sink, and state -/// handle it self-registers. -fn register_status( - registry: &Registry, - registrations: &mut Registrations, - status: &StatusBus, - omit: Option, -) { - if omit != Some(Omit::Status) { - let regs = workshop_status::register(registry, status); - registrations.hold(regs.channel); - registrations.hold(regs.sink); - registrations.hold(regs.state); - } -} - -/// The menu subsystem: its catalog and menu buses plus the sinks and -/// state handle it self-registers. -fn register_menu( - registry: &Registry, - registrations: &mut Registrations, - catalog: &CatalogBus, - menu: &MenuBus, - omit: Option, -) { - if omit != Some(Omit::Menu) { - let regs = workshop_menu::register(registry, catalog, menu); - registrations.hold(regs.catalog_sink); - registrations.hold(regs.menu_sink); - registrations.hold(regs.state); - } -} - -/// The gateway subsystem: reports the resolved gateway, builds the -/// replaceable binding, and self-registers its handles and background -/// tasks. Returns the shared reconnect backoff the sessions subsystem -/// later draws from. -fn register_gateway( - registry: &Registry, - registrations: &mut Registrations, - gateway: &ResolvedGateway, - push: &Push, - omit: Option, -) -> Result { - // Startup phases are reported as they run; with no client connected - // yet these land on an empty bus, ready for the first session. - workshop_gateway::report(gateway, push); - // The Gateway ships as a separate release, so the running one may be - // older than this Workshop needs. Its version arrives in the discovery - // file; an explicit config has no discovery file, so there is nothing - // to compare and the pin's minimum is simply not checked. - if let Some(identity) = gateway.identity() { - workshop_gateway::report_version(identity.version(), push); - } - let gateway_binding = GatewayBinding::new_with_identity( - gateway.base_url(), - gateway.api_key(), - gateway.identity().cloned(), - ) - .map_err(StateError::Gateway)?; - let backoff = ReconnectBackoff::new(); - let health = GatewayHealth::new(); - let gateway_handles = GatewayHandles::new(gateway_binding, health.clone()); - if omit != Some(Omit::Gateway) { - registrations.hold(workshop_gateway::register( - registry, - gateway_handles.clone(), - )); - } - // The background tasks register beside the state handles; the server - // spawns them from the registry's task vector when it starts - // serving. - let tasks = workshop_gateway::register_tasks(registry, &gateway_handles, backoff.clone()); - registrations.hold(tasks.heartbeat); - registrations.hold(tasks.subscriber); - Ok(backoff) -} - -/// The workspace subsystem: its file handle plus the routes, state, and -/// shutdown task it self-registers. -fn register_workspace( - registry: &Registry, - registrations: &mut Registrations, - state_dir: &std::path::Path, - omit: Option, -) { - // The workspace remembers its last-used file in the state directory; - // boot follows that memory through `reopen_last_workspace` once the - // runtime is up, since the reopen is async and composition is not. - let workspace = Workspace::with_state_dir(state_dir); - if omit != Some(Omit::Workspace) { - let regs = workshop_workspace::register(registry, &workspace); - registrations.hold(regs.routes); - registrations.hold(regs.state); - // The shutdown lever that closes the workspace file inside the - // graceful stop, so a quit leaves one complete file and no - // sidecar. - registrations.hold(workshop_workspace::register_tasks(registry, &workspace)); - } -} - -/// The user-state subsystem: the account-scoped UI state store plus the -/// routes and state handle it self-registers. -fn register_user_state( - registry: &Registry, - registrations: &mut Registrations, - state_dir: &std::path::Path, - omit: Option, -) { - if omit != Some(Omit::UserState) { - // The account-scoped UI state lives beside the menu memory in the - // state directory; a bad or missing file costs the state, never - // startup. - let user_state = Arc::new(UserStateStore::new(state_dir)); - let regs = workshop_user_state::register(registry, user_state); - registrations.hold(regs.routes); - registrations.hold(regs.state); - } -} - -/// The agent-sessions subsystem: the agent-session launcher, which builds -/// each conversation's per-run Harness, and its route state, plus the -/// routes it self-registers. -fn register_sessions( - registry: &Registry, - registrations: &mut Registrations, - config: &Config, - backoff: &ReconnectBackoff, - omit: Option, -) { - let agents = AgentSessions::new(config, registry.clone(), backoff.clone()); - let sessions = SessionsState::new(registry.clone(), crate::cross_site::origin_allowed); - if omit != Some(Omit::AgentSessions) { - let regs = agents::register(registry, &sessions, &agents); - registrations.hold(regs.routes); - registrations.hold(regs.agents); - } -} - -/// The `/ws` workshop socket: its route state, with the sidecar restart -/// bound replaced when given, and the route it self-registers. -fn register_workshop_socket( - registry: &Registry, - registrations: &mut Registrations, - restart_bound: Option, -) { - let mut state = WorkshopSocketState::new(registry.clone(), crate::cross_site::origin_allowed); - if let Some(bound) = restart_bound { - state = state.with_restart_bound(bound); - } - registrations.hold(workshop_socket::register(registry, &state)); -} diff --git a/crates/workshop/server/src/app/test_helpers.rs b/crates/workshop/server/src/app/test_helpers.rs index db9f8ce1..8379a79d 100644 --- a/crates/workshop/server/src/app/test_helpers.rs +++ b/crates/workshop/server/src/app/test_helpers.rs @@ -10,14 +10,26 @@ use std::path::Path; use axum::Router; #[cfg(test)] -use axum::body::to_bytes; +use axum::body::{Bytes, to_bytes}; #[cfg(test)] use axum::response::Response; +#[cfg(test)] +use tempfile::TempDir; +#[cfg(test)] +use workshop_gateway::{GatewayBinding, ResolvedGateway}; +#[cfg(test)] +use workshop_support::{AgentsConfig, Config, GatewayConfig, ServerConfig}; #[cfg(test)] use crate::app::{AppState, state_with_gateway}; + #[cfg(test)] -use workshop_support::{AgentsConfig, Config, GatewayConfig, ServerConfig}; +impl AppState { + /// The replaceable Gateway binding shared with long-lived tasks. + pub(crate) fn gateway_binding(&self) -> GatewayBinding { + self.gateway_handles().binding().clone() + } +} /// Builds a configuration pointing at `base_url`, anchoring the state /// directory at `state_dir`. @@ -40,17 +52,17 @@ pub(crate) fn config_for(base_url: &str, state_dir: &Path) -> Config { /// alongside so the directory outlives the test. Discovery is /// bypassed: a test never consults the real run directory. #[cfg(test)] -pub(crate) fn state_for(base_url: &str) -> (AppState, tempfile::TempDir) { - let state_dir = tempfile::TempDir::new().expect("tempdir"); +pub(crate) fn state_for(base_url: &str) -> (AppState, TempDir) { + let state_dir = TempDir::new().expect("tempdir"); let config = config_for(base_url, state_dir.path()); - let gateway = workshop_gateway::ResolvedGateway::from_config(&config.gateway); + let gateway = ResolvedGateway::from_config(&config.gateway); let state = state_with_gateway(&config, &gateway).expect("state builds in tests"); (state, state_dir) } /// Collects a response body already buffered in memory. #[cfg(test)] -pub(crate) async fn body_bytes(response: Response) -> axum::body::Bytes { +pub(crate) async fn body_bytes(response: Response) -> Bytes { to_bytes(response.into_body(), usize::MAX) .await .expect("the body is in memory already") diff --git a/crates/workshop/server/src/app/tests.rs b/crates/workshop/server/src/app/tests.rs index 050d7ca7..7384ae80 100644 --- a/crates/workshop/server/src/app/tests.rs +++ b/crates/workshop/server/src/app/tests.rs @@ -233,3 +233,25 @@ async fn post_chat_is_absent_and_answers_not_found() { .expect("the router is infallible"); assert_eq!(response.status(), axum::http::StatusCode::NOT_FOUND); } + +#[tokio::test] +async fn health_returns_serving() { + use tower::ServiceExt as _; + + let (state, _state_dir) = state_for("http://127.0.0.1:1"); + let request = axum::http::Request::builder() + .uri("/health") + .body(axum::body::Body::empty()) + .expect("static request parts are valid"); + let response = router(state) + .oneshot(request) + .await + .expect("the router is infallible"); + assert_eq!(response.status(), axum::http::StatusCode::OK); + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .expect("the health handler sets content-type"); + assert_eq!(content_type, "application/json"); + assert_eq!(&body_bytes(response).await[..], br#"{"status":"serving"}"#); +} diff --git a/crates/workshop/server/src/routes/assets-tests.rs b/crates/workshop/server/src/assets-tests.rs similarity index 83% rename from crates/workshop/server/src/routes/assets-tests.rs rename to crates/workshop/server/src/assets-tests.rs index 65d87e2b..940dcc56 100644 --- a/crates/workshop/server/src/routes/assets-tests.rs +++ b/crates/workshop/server/src/assets-tests.rs @@ -1,12 +1,58 @@ -//! Asset route tests: content types, cache headers, hashed bundles, and chunk-path confinement. +//! Asset and asset-route tests: content types, cache headers, hashed bundles, +//! and traversal confinement. use axum::body::Body; use axum::http::{Request, Response, StatusCode, header}; use tower::ServiceExt; +use super::{CachePolicy, UiAssets, ui_asset}; use crate::app::router; use crate::app::test_helpers::{body_bytes, state_for}; +/// Asserts an asset name answers 404 rather than file contents. +fn assert_asset_misses(path: &str) { + let response = ui_asset(path, "text/plain; charset=utf-8", CachePolicy::Revalidate); + assert_eq!( + response.status(), + StatusCode::NOT_FOUND, + "{path:?} must not escape the asset root" + ); +} + +// These pin traversal parity between the two build profiles: release +// misses the embed map by construction, while a debug build reads +// `$OUT_DIR/ui-dist/` from disk at request time and must refuse names +// resolving outside it. That guarantee covers request-supplied names +// only: rust-embed 8.12.0 deliberately still serves an out-of-root +// symlink planted inside the asset root, a bypass outside the parity +// pinned here. The absolute target names this crate's own manifest - a +// file that exists on disk - so it can only fail on containment; the +// relative targets may also fail on absence. + +#[test] +fn relative_traversal_answers_not_found() { + assert_asset_misses("../../Cargo.toml"); +} + +#[test] +fn backslash_traversal_answers_not_found() { + assert_asset_misses(r"..\..\Cargo.toml"); +} + +#[test] +fn absolute_path_answers_not_found() { + assert_asset_misses(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml")); +} + +#[test] +fn the_cache_policies_render_their_header_values() { + assert_eq!(CachePolicy::Revalidate.header_value(), "no-cache"); + assert_eq!( + CachePolicy::Immutable.header_value(), + "public, max-age=31536000, immutable" + ); +} + /// Performs one GET against the router and returns the response. async fn get(uri: &str) -> Response { let (state, _state_dir) = state_for("http://127.0.0.1:1"); @@ -31,7 +77,7 @@ fn cache_control(response: &Response) -> &header::HeaderValue { /// The build's asset manifest: the logical-to-hashed name map the UI /// build emits next to the bundle. fn asset_manifest() -> serde_json::Value { - let asset = crate::assets::UiAssets::get("manifest.json") + let asset = UiAssets::get("manifest.json") .unwrap_or_else(|| panic!("the UI build emits manifest.json")); serde_json::from_slice(&asset.data) .unwrap_or_else(|error| panic!("manifest.json is valid JSON: {error}")) @@ -135,7 +181,7 @@ async fn program_icon_2x_is_served_as_png() { /// The code-split chunks have content-hashed names, so the test discovers /// one through the embedded asset listing rather than naming it. fn first_chunk_name(extension: &str) -> String { - crate::assets::UiAssets::iter() + UiAssets::iter() .map(std::borrow::Cow::into_owned) .find(|name| name.starts_with("chunks/") && name.ends_with(extension)) .unwrap_or_else(|| panic!("the UI build emits a chunks/*{extension} chunk")) @@ -195,7 +241,7 @@ async fn the_manifest_maps_logical_names_to_hashed_bundle_files() { "{logical} maps to a content-hashed bundle file, got {target:?}" ); assert!( - crate::assets::UiAssets::get(target).is_some(), + UiAssets::get(target).is_some(), "the manifest target {target:?} exists in the bundle" ); } @@ -232,8 +278,8 @@ async fn the_logical_app_routes_serve_the_hashed_bytes() { "no-cache", "{uri} is a stable URL and must revalidate" ); - let expected = crate::assets::UiAssets::get(&manifest_target(logical)) - .expect("the manifest target exists"); + let expected = + UiAssets::get(&manifest_target(logical)).expect("the manifest target exists"); assert_eq!( &body_bytes(response).await[..], &expected.data[..], diff --git a/crates/workshop/server/src/assets.rs b/crates/workshop/server/src/assets.rs index 11b9f768..9921b12b 100644 --- a/crates/workshop/server/src/assets.rs +++ b/crates/workshop/server/src/assets.rs @@ -1,8 +1,13 @@ -//! The embedded workshop UI assets and the file-serving helper; the routes -//! that expose them sit in [`crate::routes::assets`]. +//! The embedded workshop UI assets and the routes that serve them. +use std::path; + +use axum::Router; +use axum::extract::Path; use axum::http::header; use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use serde_json::Value; use crate::error::AppError; @@ -12,11 +17,11 @@ use crate::error::AppError; /// recompile; release builds embed them into the binary. #[derive(rust_embed::Embed)] #[folder = "$OUT_DIR/ui-dist/"] -pub(crate) struct UiAssets; +struct UiAssets; /// How long a cache may hold one asset. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum CachePolicy { +enum CachePolicy { /// A stable URL whose content changes between builds (`index.html`, /// the logical `app.js` route): force revalidation on every load, so /// a heuristic cache never serves a stale script against a newer @@ -38,118 +43,130 @@ impl CachePolicy { } } -/// The build's logical-to-hashed name map, parsed from the UI build's -/// `manifest.json`. The server resolves the stable routes (`/app.js`, -/// `/app.css`) through it to the current hashed files. -#[derive(Clone, Debug)] -pub(crate) struct AssetManifest { - /// The hashed bundle path serving the logical `app.js`. - app_js: String, - /// The hashed bundle path serving the logical `app.css`. - app_css: String, -} - -impl AssetManifest { - /// The hashed target for one logical name, or None when the manifest - /// does not map it. - pub(crate) fn resolve(&self, logical: &str) -> Option<&str> { - match logical { - "app.js" => Some(&self.app_js), - "app.css" => Some(&self.app_css), - _ => None, - } - } -} - -/// The server's webview asset layer: the embedded UI bundle. -pub(crate) struct EmbeddedAssets; - -impl EmbeddedAssets { - /// Returns one asset's bytes, or None when the name is absent. - pub(crate) fn get(path: &str) -> Option> { - UiAssets::get(path).map(|asset| asset.data.into_owned()) - } - - /// The build's asset manifest, or None when the build emitted none. - pub(crate) fn manifest() -> Option { - let asset = UiAssets::get("manifest.json")?; - // A parse failure is safe to ignore: the build writes the manifest - // itself and embeds it beside the assets, so malformed JSON means a - // corrupt build output rather than user input. Treating it as "no - // manifest" degrades the logical routes to the same AssetMissing - // 404 a missing manifest produces, instead of panicking the server. - let value: serde_json::Value = serde_json::from_slice(&asset.data).ok()?; - let target = |logical: &str| value.get(logical)?.as_str().map(str::to_string); - Some(AssetManifest { - app_js: target("app.js")?, - app_css: target("app.css")?, - }) - } +/// The UI asset routes: the index page, the bundled script and styles +/// (stable logical routes resolving through the build's manifest, plus +/// the content-hashed `bundle/` files the stamped index page loads +/// directly), the code-split chunks the bundle lazy-loads, the PCM +/// worklet, and the program icon at 1x and 2x. Stateless: every response +/// comes straight from [`UiAssets`]. +pub(crate) fn routes() -> Router { + Router::new() + .route( + "/", + get(|| async { + ui_asset( + "index.html", + "text/html; charset=utf-8", + CachePolicy::Revalidate, + ) + }), + ) + .route( + "/app.js", + get(|| async { logical_asset("app.js", "text/javascript; charset=utf-8") }), + ) + .route( + "/app.css", + get(|| async { logical_asset("app.css", "text/css; charset=utf-8") }), + ) + .route( + "/style.css", + get(|| async { + ui_asset( + "style.css", + "text/css; charset=utf-8", + CachePolicy::Revalidate, + ) + }), + ) + .route( + "/pcm-worklet.js", + get(|| async { + ui_asset( + "pcm-worklet.js", + "text/javascript; charset=utf-8", + CachePolicy::Revalidate, + ) + }), + ) + .route( + "/bundle/{*name}", + get(|Path(name): Path| async move { hashed_asset("bundle", &name) }), + ) + .route( + "/chunks/{*name}", + get(|Path(name): Path| async move { hashed_asset("chunks", &name) }), + ) + .route( + "/icons/runvil-icon.png", + get(|| async { + ui_asset( + "icons/runvil-icon.png", + "image/png", + CachePolicy::Revalidate, + ) + }), + ) + .route( + "/icons/runvil-icon@2x.png", + get(|| async { + ui_asset( + "icons/runvil-icon@2x.png", + "image/png", + CachePolicy::Revalidate, + ) + }), + ) } /// Serves one embedded UI asset with the given content type and cache /// policy. -pub(crate) fn ui_asset(path: &str, content_type: &'static str, cache: CachePolicy) -> Response { - match EmbeddedAssets::get(path) { - Some(data) => ( +fn ui_asset(path: &str, content_type: &'static str, cache: CachePolicy) -> Response { + match UiAssets::get(path) { + Some(asset) => ( [ (header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, cache.header_value()), ], - data, + asset.data, ) .into_response(), None => AppError::AssetMissing(path.to_string()).into_response(), } } -#[cfg(test)] -mod tests { - use axum::http::StatusCode; - - use super::*; - - /// Asserts an asset name answers 404 rather than file contents. - fn assert_asset_misses(path: &str) { - let response = ui_asset(path, "text/plain; charset=utf-8", CachePolicy::Revalidate); - assert_eq!( - response.status(), - StatusCode::NOT_FOUND, - "{path:?} must not escape the asset root" - ); - } - - // These pin traversal parity between the two build profiles: release - // misses the embed map by construction, while a debug build reads - // `$OUT_DIR/ui-dist/` from disk at request time and must refuse names - // resolving outside it. That guarantee covers request-supplied names - // only: rust-embed 8.12.0 deliberately still serves an out-of-root - // symlink planted inside the asset root, a bypass outside the parity - // pinned here. The absolute target names this crate's own manifest - a - // file that exists on disk - so it can only fail on containment; the - // relative targets may also fail on absence. - - #[test] - fn relative_traversal_answers_not_found() { - assert_asset_misses("../../Cargo.toml"); - } - - #[test] - fn backslash_traversal_answers_not_found() { - assert_asset_misses(r"..\..\Cargo.toml"); - } - - #[test] - fn absolute_path_answers_not_found() { - assert_asset_misses(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml")); +/// Serves one logical bundle route by resolving the build's `manifest.json` +/// to the current content-hashed file. A parse failure or missing manifest +/// degrades to the same `AssetMissing` 404 rather than panicking. +fn logical_asset(logical: &str, content_type: &'static str) -> Response { + let manifest = UiAssets::get("manifest.json") + .and_then(|asset| serde_json::from_slice::(&asset.data).ok()); + match manifest + .as_ref() + .and_then(|value| value.get(logical)) + .and_then(Value::as_str) + { + Some(target) => ui_asset(target, content_type, CachePolicy::Revalidate), + None => AppError::AssetMissing(logical.to_string()).into_response(), } +} - #[test] - fn the_cache_policies_render_their_header_values() { - assert_eq!(CachePolicy::Revalidate.header_value(), "no-cache"); - assert_eq!( - CachePolicy::Immutable.header_value(), - "public, max-age=31536000, immutable" - ); - } +/// Serves one content-hashed entry or code-split chunk under `prefix` +/// (`bundle` or `chunks`). Only the two kinds esbuild emits (`.js`, `.css`) +/// are served, and the responses are cached immutably. +fn hashed_asset(prefix: &str, name: &str) -> Response { + let full = format!("{prefix}/{name}"); + let extension = path::Path::new(name).extension(); + let content_type = if extension.is_some_and(|ext| ext.eq_ignore_ascii_case("js")) { + "text/javascript; charset=utf-8" + } else if extension.is_some_and(|ext| ext.eq_ignore_ascii_case("css")) { + "text/css; charset=utf-8" + } else { + return AppError::AssetMissing(full).into_response(); + }; + ui_asset(&full, content_type, CachePolicy::Immutable) } + +#[cfg(test)] +#[path = "assets-tests.rs"] +mod tests; diff --git a/crates/workshop/server/src/cross_site.rs b/crates/workshop/server/src/cross_site.rs index 84064305..5ee3eeaf 100644 --- a/crates/workshop/server/src/cross_site.rs +++ b/crates/workshop/server/src/cross_site.rs @@ -1,4 +1,5 @@ -//! Cross-site request blocking for the loopback workshop server. +//! Cross-site request blocking and Content-Security-Policy headers for +//! the loopback workshop server. //! //! Any webpage the user visits can issue requests to `127.0.0.1`, so //! without these checks the workspace-write and WebSocket endpoints are @@ -21,14 +22,77 @@ //! is a native client, not a browser, and passes. `/health` and the UI //! assets stay outside the guard so the desktop app probe and heartbeat keep //! working. +//! +//! The desktop app loads the UI as an External-origin Tauri webview, so +//! the page's Content-Security-Policy is the server's to set via +//! [`csp_header`]: there is no `tauri.conf.json` CSP for a remote +//! document. The policy keeps the SPA self-contained - scripts and +//! workers from this origin only - while `connect-src` admits the two +//! IPC endpoints Tauri calls from an External origin (`ipc:` on the +//! custom-protocol platforms, `http://ipc.localhost` under WebView2) and +//! the loopback WebSocket spellings. WebKit does not treat `connect-src +//! 'self'` as covering WebSockets, so the `ws://` sources are spelled +//! out for WebKitGTK and WKWebView; the port wildcard covers the desktop +//! app's OS-assigned bind. + +use std::net::{IpAddr, Ipv6Addr}; use axum::extract::Request; -use axum::http::{HeaderMap, Method, header}; +use axum::http::uri::Authority; +use axum::http::{HeaderMap, HeaderValue, Method, header}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; +use url::{Host, Url}; use crate::error::AppError; +/// Shares the common Content-Security-Policy directive prefix across the +/// strict and self-frameable variants. +macro_rules! csp_policy { + ($frame_ancestors:literal) => { + concat!( + "default-src 'self'; script-src 'self'; ", + "style-src 'self' 'unsafe-inline'; ", + "connect-src 'self' ipc: http://ipc.localhost ws://127.0.0.1:* ", + "ws://localhost:* ws://[::1]:*; img-src 'self' data: blob: https:; ", + "worker-src 'self'; object-src 'none'; base-uri 'none'; ", + "frame-ancestors ", + $frame_ancestors, + ) + }; +} + +/// The policy value, one header for every response. +/// +/// `img-src` keeps `https:` so model-written markdown can still render +/// remote images. `style-src` keeps `'unsafe-inline'` because the UI's +/// styling is partly runtime-injected and cannot be nonced: CodeMirror 6 +/// mounts its modules as `