diff --git a/.agents/skills/layerfs-js-sdk/references/methods/store.md b/.agents/skills/layerfs-js-sdk/references/methods/store.md index 036a08ac92..57ab3f96ac 100644 --- a/.agents/skills/layerfs-js-sdk/references/methods/store.md +++ b/.agents/skills/layerfs-js-sdk/references/methods/store.md @@ -13,9 +13,9 @@ store.list({ machine, with: ["stats"] }) store.get(store, { with: ["live", "stats"] }) store.create(name, { machine }) -store.connect(store, url, { user, password, synchronous_commit }) +store.connect(store, url, { user, password, synchronous_commit, dry_run }) store.disconnect(store) -store.attach(store, { machine }) +store.attach(store, { machine, dry_run }) store.detach(store, { machine }) store.move(store, machine, { on_progress }) store.remove(store) @@ -78,9 +78,9 @@ $ layerfs store get shop --with live,stats # | Call | What it does | Notes | | --- | --- | --- | | `create(name)` | An empty sqlite Store | `{"ok":true}` (seen). A taken name is `Exists` (seen: `a Store named shop exists`). `machine` makes it on that running machine through its worker | -| `connect(store, url, …)` | Connects a PostgreSQL database as a Store (`user` and `password` required the first time, checked before anything is saved; `synchronous_commit` defaults to `local`); on a connected Store, changes its address, user, password or `synchronous_commit` (an omitted user or password keeps the saved one; the same Store must be reached) | The URL holds host, port, database and TLS settings only: one naming a user, password or `passfile` is `InvalidInput` with the `fix` `layerfs store connect --user --password-stdin`. Shell: `--user U --password-stdin`; the password is never answered, logged or traced. Short `{ projects, projects_count? }`, or `{"ok":true}`; long `outcome` `connected` or `updated` | +| `connect(store, url, …)` | Connects a PostgreSQL database as a Store (`user` and `password` required the first time, checked before anything is saved; `synchronous_commit` defaults to `local`); on a connected Store, changes its address, user, password or `synchronous_commit` (an omitted user or password keeps the saved one; the same Store must be reached) | The URL holds host, port, database and TLS settings only: one naming a user, password or `passfile` is `InvalidInput` with the `fix` `layerfs store connect --user --password-stdin`. Shell: `--user U --password-stdin`; the password is never answered, logged or traced. Short `{ projects, projects_count? }`, or `{"ok":true}`; long `outcome` `connected` or `updated`. A new address, user or password is checked from each attached machine first: one that fails refuses `Conflict` with `machines` and a detach `fix`, nothing saved. `dry_run: true` checks and saves nothing: `{ ok, outcome: "tested", here, machines }`. A refused check names its `step` | | `disconnect(store)` | Forgets a PostgreSQL Store with its saved password and attachments, its data staying | `InUse` while a Sandbox or Workspace uses it | -| `attach(store, { machine })` | Lets a machine run Sandboxes of a PostgreSQL Store, checked from that machine with the saved URL and login first | Short `{ ok, outcome, latency_ms? }`; `outcome` `attached`, or `checked` when already attached. A sqlite Store is `InvalidInput`; machine native is attached like any other. `sandbox.create` on a machine not attached is refused with `layerfs store attach --machine ` as its `fix` | +| `attach(store, { machine })` | Lets a machine run Sandboxes of a PostgreSQL Store, checked from that machine with the saved URL and login first | Short `{ ok, outcome, latency_ms? }`; `outcome` `attached`, or `checked` when already attached, or `tested` for `dry_run: true` (records nothing). A refused check names its `step` and `machine`. A sqlite Store is `InvalidInput`; machine native is attached like any other. `sandbox.create` on a machine not attached is refused with `layerfs store attach --machine ` as its `fix` | | `detach(store, { machine })` | Stops a machine running Sandboxes of a PostgreSQL Store | `InUse` while a Sandbox of the Store's projects is on it; `NotFound` when not attached | | `move(store, machine)` | Moves a sqlite Store between this computer and a machine | To or from `native` only (seen when already there: `store move, check: Store shop is already on native`, `InvalidInput`; moving off a machine whose record lacks `vm_name` is `Unavailable` with `blocked_by`). Progress `check`, `snapshot`, `send`, `verify`, `install`, `record`, `retire`. Short `{ moved_bytes }`. A sqlite Store's Sandboxes run only on its machine | | `remove(store)` | Deletes a sqlite Store with every project in it | `{"ok":true}`. `NotFound` for an unknown name (seen). A PostgreSQL Store is disconnected instead. A record this build does not read, or a Store on a machine whose record has no 2.0 name, goes by its records alone, with `left` saying what may remain | diff --git a/api/crates/layerfs-api/src/calls/guide.rs b/api/crates/layerfs-api/src/calls/guide.rs index 056c5cffb1..bd908429bb 100644 --- a/api/crates/layerfs-api/src/calls/guide.rs +++ b/api/crates/layerfs-api/src/calls/guide.rs @@ -487,11 +487,21 @@ const ARGS: &[(&str, &str, &str)] = &[ "password", "the role's password, read from stdin; needed on a Store's first connect", ), + ( + "store.connect", + "dry_run", + "check from this computer and each attached machine, and save nothing", + ), ( "store.attach", "machine", "the machine that may run the Store's Sandboxes", ), + ( + "store.attach", + "dry_run", + "check from the machine as attach does, and record nothing", + ), ( "store.detach", "machine", diff --git a/api/crates/layerfs-api/src/store/attach.rs b/api/crates/layerfs-api/src/store/attach.rs index 5a8c657005..9ea2efe9ba 100644 --- a/api/crates/layerfs-api/src/store/attach.rs +++ b/api/crates/layerfs-api/src/store/attach.rs @@ -1,14 +1,16 @@ //! `store.attach`: let a machine run Sandboxes of a PostgreSQL Store, //! dialling the URL and login this computer saved; checked from it first. -use crate::calls::table::Kind::Name; +//! `--dry-run` makes the check alone and records nothing. +use crate::calls::table::Kind::{Bool, Name}; use crate::calls::table::{a, call, opt, Call}; use crate::calls::{Context, Form}; use layerfs_bridge::control::SdkValue; use layerfs_home::names::{MachineName, StoreName}; use layerfs_home::outcome::Outcome; -/// Its answer: `ok` and the outcome (`attached`, or `checked` for an -/// attached machine checked again), with what the check measured. +/// Its answer: `ok` and the outcome (`attached`, `checked` for an +/// attached machine checked again, or `tested` for a dry run), with what +/// the check measured. const FORM: Form = Form::of( &["ok", "outcome"], &["latency_ms"], @@ -27,7 +29,7 @@ pub(crate) const CALL: Call = call( "store", "attach", &[a("store", Name)], - &[opt("machine", Name).required()], + &[opt("machine", Name).required(), opt("dry_run", Bool)], "let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first", run, ) @@ -38,5 +40,6 @@ fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { let store = StoreName::parse(args.get_text("store").unwrap_or(""))?; let machine = MachineName::parse(args.get_text("machine").unwrap_or(""))?; let (home, events) = context.parts(); - layerfs_control::store::attach(home, events, &store, &machine) + let dry_run = args.get_bool("dry_run"); + layerfs_control::store::attach(home, events, &store, &machine, dry_run) } diff --git a/api/crates/layerfs-api/src/store/connect.rs b/api/crates/layerfs-api/src/store/connect.rs index c0eb1892b7..9f02d10958 100644 --- a/api/crates/layerfs-api/src/store/connect.rs +++ b/api/crates/layerfs-api/src/store/connect.rs @@ -1,8 +1,9 @@ //! `store.connect`: connect a PostgreSQL database as a Store, or change a //! connected one's address, login or `synchronous_commit`. This computer //! is the one place a Store's URL and login are saved; machines attach to -//! the Store (`store.attach`) and dial both. -use crate::calls::table::Kind::{Content, Name, Text}; +//! the Store (`store.attach`) and dial both. `--dry-run` makes the checks +//! alone, from this computer and each attached machine, and saves nothing. +use crate::calls::table::Kind::{Bool, Content, Name, Text}; use crate::calls::table::{a, call, opt, Call}; use crate::calls::{Context, Form}; use layerfs_bridge::control::SdkValue; @@ -11,10 +12,18 @@ use layerfs_home::outcome::{refused, Outcome}; use layerfs_store::postgresql::connect::StoreConnect; /// Its answer: the projects a first connect found, else `ok`; never the -/// password. +/// password. A dry run's (`outcome: tested`) shows the checks in the +/// short form too: `here`, this computer's, and `machines`, one row each. const FORM: Form = Form::of( &[], - &["ok", "projects", "projects_count"], + &[ + "ok", + "outcome", + "projects", + "projects_count", + "here", + "machines", + ], &[ "ok", "projects", @@ -26,9 +35,42 @@ const FORM: Form = Form::of( "user", "synchronous_commit", "machines", + "here", ], ) -.parts(&[("machines", crate::calls::Part::Scalars("machine"))]); +.parts(&[ + ("machines", crate::calls::Part::Scalars("machine")), + ("here", crate::calls::Part::Rows(&TESTED)), +]) +.short_when(&[("outcome", tested), ("here", tested), ("machines", tested)]); + +/// One check of a dry run: `ok` (false kept in the short form), what it +/// measured, or the step it stopped at, the refusal's code and why. +const TESTED: Form = Form::of( + &["ok"], + &[ + "latency_ms", + "server_version", + "empty", + "step", + "code", + "message", + ], + &[ + "ok", + "latency_ms", + "server_version", + "empty", + "step", + "code", + "message", + ], +); + +/// Whether the answer is a dry run's. +fn tested(fields: &[(String, SdkValue)], _asked: &[&str]) -> bool { + (fields.iter()).any(|(key, value)| key == "outcome" && *value == SdkValue::text("tested")) +} /// Its table entry: the password is a secret the shell reads from stdin. pub(crate) const CALL: Call = call( @@ -39,6 +81,7 @@ pub(crate) const CALL: Call = call( opt("user", Text), opt("password", Content).from_stdin("--password-stdin"), opt("synchronous_commit", Text), + opt("dry_run", Bool), ], "connect a PostgreSQL database as a Store, or change a connected one's address, login or setting", run, @@ -61,6 +104,8 @@ fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { user: text("user"), password, synchronous_commit: text("synchronous_commit"), + dry_run: args.get_bool("dry_run"), }; - layerfs_control::store::connect(&context.home, &request) + let (home, events) = context.parts(); + layerfs_control::store::connect(home, events, &request) } diff --git a/api/crates/layerfs-api/tests/postgres_connect.rs b/api/crates/layerfs-api/tests/postgres_connect.rs index fddbd00984..b8d64b16ab 100644 --- a/api/crates/layerfs-api/tests/postgres_connect.rs +++ b/api/crates/layerfs-api/tests/postgres_connect.rs @@ -271,7 +271,8 @@ fn connect_read_and_disconnect() { } /// A database the server does not have is a session the server refused, -/// not a server that took no connection (#535 terminal pass, lane K3). +/// not a server that took no connection (#535 terminal pass, lane K3): it +/// is refused at the connection step `database`, in the server's words. #[test] fn a_missing_database_is_a_refused_session() { let (Ok(url), Ok(_)) = ( @@ -288,12 +289,18 @@ fn a_missing_database_is_a_refused_session() { let missing = format!("{server}/lfs_no_such_database"); let mut args = vec![("store", t("gone")), ("url", t(&missing))]; args.extend(login); - let (code, message) = call(&home, "store.connect", &args).unwrap_err(); - assert_eq!(code, "Unavailable", "{message}"); - assert!( - message.contains("the server refused the session"), - "{message}" + let args = SdkValue::Map( + args.iter() + .map(|(n, v)| ((*n).to_owned(), v.clone())) + .collect(), ); + let refusal = layerfs_api::call(Some(&home), "store.connect", args, &mut |_| {}).unwrap_err(); + let message = &refusal.message; + assert_eq!(refusal.code, "Unavailable", "{message}"); + assert!(message.contains("refused the connection"), "{message}"); + assert!(message.contains("lfs_no_such_database"), "{message}"); + let next = refusal.detail.get("next").cloned().unwrap_or_default(); + assert_eq!(next.get_text("step"), Some("database"), "{refusal:?}"); assert!(!paths::store_dir(&home, "gone").exists()); std::fs::remove_dir_all(&home).unwrap(); } diff --git a/api/crates/layerfs-api/tests/postgres_login.rs b/api/crates/layerfs-api/tests/postgres_login.rs index e6681df121..b1694e072e 100644 --- a/api/crates/layerfs-api/tests/postgres_login.rs +++ b/api/crates/layerfs-api/tests/postgres_login.rs @@ -76,6 +76,18 @@ impl Server { }) } + /// The admin URL's start, `postgres://user@host:port` (its user and any + /// password), in place of [`Self::base`]. + fn admin_base(&self) -> String { + let config: postgres::Config = self.admin.parse().unwrap(); + let host = match config.get_hosts().first() { + Some(postgres::config::Host::Tcp(host)) => host.clone(), + other => panic!("a TCP test server: {other:?}"), + }; + let port = config.get_ports().first().copied().unwrap_or(5432); + format!("postgresql://{}@{host}:{port}", self.user) + } + /// A new empty database's address, no user and no password. fn database(&mut self, tag: &str) -> String { let name = format!("pglogin_{tag}_{}", std::process::id()); @@ -166,7 +178,7 @@ fn connect_checks_and_saves_the_login_and_a_reconnect_keeps_what_it_is_not_given assert_eq!( layerfs_api::json::print(&connected), format!( - r#"{{"ok":true,"projects":[],"projects_count":null,"outcome":"connected","store":"pg","engine":"postgresql","url":"{url}","user":"{user}","synchronous_commit":"local","machines":[]}}"# + r#"{{"ok":true,"projects":[],"projects_count":null,"outcome":"connected","store":"pg","engine":"postgresql","url":"{url}","user":"{user}","synchronous_commit":"local","machines":[],"here":null}}"# ) ); let file = password_file(&home, "pg").expect("the password is saved"); @@ -435,3 +447,237 @@ fn the_doctor_checks_attached_machines_only_after_this_computer() { assert_eq!(froms(&report), Vec::::new(), "{report:?}"); std::fs::remove_dir_all(&home).unwrap(); } + +/// A refusal's flat field `key` (its `next`), as the call boundary +/// answers it beside `error` and `message`. +fn flat(refusal: &layerfs_bridge::control::SdkRefusal, key: &str) -> SdkValue { + let next = refusal.detail.get("next").cloned().unwrap_or_default(); + next.get(key).cloned().unwrap_or_default() +} + +/// The full refusal of a call. +fn refusal( + home: &Path, + name: &str, + args: &[(&str, SdkValue)], +) -> layerfs_bridge::control::SdkRefusal { + let args = SdkValue::Map( + args.iter() + .map(|(n, v)| ((*n).to_owned(), v.clone())) + .collect(), + ); + match layerfs_api::call(Some(home), name, args, &mut |_| {}) { + Ok(answer) => panic!("{name} answered {answer:?}"), + Err(refusal) => refusal, + } +} + +/// A connect refusal names the connection step it stopped at, as the +/// doctor's `store.connection.`: nothing answering is `transport`, +/// a role the server does not know `authentication`, a database it does +/// not have `database`; a dry run answers the same steps in `here` and +/// saves nothing, and a first connect's dry run of an empty database +/// says so (`empty`) without making the schema. +#[test] +fn connect_refusals_and_dry_runs_name_the_step() { + let Some(mut server) = Server::new() else { + return; + }; + let url = server.database("step"); + let empty_db = server.database("stepempty"); + let user = server.user.clone(); + let home = tempdir("step"); + home::open(&home).unwrap(); + let new = |address: &str, role: &str| { + vec![ + ("store", t("pg")), + ("url", t(address)), + ("user", t(role)), + ("password", t("pw")), + ] + }; + let nowhere = "postgresql://127.0.0.1:1/db?sslmode=disable&connect_timeout=5"; + let missing_db = url.replace("pglogin_step_", "pglogin_nosuchdb_"); + for (address, role, step) in [ + (nowhere, user.as_str(), "transport"), + (url.as_str(), "layerfs_no_such_role", "authentication"), + (missing_db.as_str(), user.as_str(), "database"), + ] { + let refused = refusal(&home, "store.connect", &new(address, role)); + assert_eq!(flat(&refused, "step"), t(step), "{}", refused.message); + let mut dry = new(address, role); + dry.push(("dry_run", SdkValue::Bool(true))); + let tested = long(&home, "store.connect", &dry); + assert_eq!(tested.get_text("outcome"), Some("tested"), "{tested:?}"); + assert_eq!(tested.get("ok"), Some(&SdkValue::Bool(false)), "{tested:?}"); + let here = tested.get("here").unwrap(); + assert_eq!(here.get("ok"), Some(&SdkValue::Bool(false)), "{tested:?}"); + assert_eq!(here.get_text("step"), Some(step), "{tested:?}"); + assert_eq!( + here.get_text("code"), + Some(refused.code.as_str()), + "{tested:?}" + ); + assert!(!paths::store_dir(&home, "pg").exists()); + } + // an empty database: tested, empty, and still without the schema + let mut dry = new(&empty_db, &user); + dry.push(("dry_run", SdkValue::Bool(true))); + let tested = long(&home, "store.connect", &dry); + assert_eq!(tested.get("ok"), Some(&SdkValue::Bool(true)), "{tested:?}"); + let here = tested.get("here").unwrap(); + assert_eq!(here.get("empty"), Some(&SdkValue::Bool(true)), "{tested:?}"); + assert!(here.get_int("latency_ms").is_some(), "{tested:?}"); + assert_eq!(tested.get("machines"), Some(&SdkValue::List(vec![]))); + assert!(!paths::store_dir(&home, "pg").exists()); + assert!(password_file(&home, "pg").is_none()); + let admin = empty_db.replace(&server.base, &server.admin_base()); + let mut client = postgres::Client::connect(&admin, postgres::NoTls).unwrap(); + let schemas = client + .query_one( + "SELECT count(*) FROM pg_namespace WHERE nspname = 'layerfs'", + &[], + ) + .unwrap(); + assert_eq!(schemas.get::<_, i64>(0), 0, "a dry run made the schema"); + // connected, a new address where nothing answers: refused at + // `transport` with nothing saved; its dry run says the same + ok(&home, "store.connect", &new(&url, &user)); + let record = || std::fs::read(paths::store_record(&home, "pg")).unwrap(); + let before = record(); + let again = [("store", t("pg")), ("url", t(nowhere))]; + let refused = refusal(&home, "store.connect", &again); + assert_eq!(refused.code, "Unavailable", "{}", refused.message); + assert_eq!( + flat(&refused, "step"), + t("transport"), + "{}", + refused.message + ); + let mut dry = again.to_vec(); + dry.push(("dry_run", SdkValue::Bool(true))); + let tested = long(&home, "store.connect", &dry); + let here = tested.get("here").unwrap(); + assert_eq!(here.get_text("step"), Some("transport"), "{tested:?}"); + assert_eq!(record(), before); + std::fs::remove_dir_all(&home).unwrap(); +} + +/// `store.attach --dry-run` makes attach's check from the machine and +/// records nothing: not the attachment, not the reach. A connect that +/// changes the address is checked from every attached machine first and +/// refused `Conflict`, nothing saved, when one fails (here a stopped lima +/// machine), naming it in `machines` with the detach as its fix; its dry +/// run answers each machine's check; a change of the setting alone checks +/// no machine. +#[cfg(feature = "machine")] +#[test] +fn dry_runs_record_nothing_and_an_address_change_checks_attached_machines() { + let Some(mut server) = Server::new() else { + return; + }; + let url = server.database("machines"); + let user = server.user.clone(); + let home = tempdir("machines"); + home::open(&home).unwrap(); + ok(&home, "machine.list", &[]); + let connect = [ + ("store", t("pg")), + ("url", t(&url)), + ("user", t(&user)), + ("password", t("pw")), + ]; + ok(&home, "store.connect", &connect); + let seen_file = paths::store_record(&home, "pg").with_file_name("observed.json"); + let seen = || std::fs::read(&seen_file).unwrap_or_default(); + let record = || std::fs::read(paths::store_record(&home, "pg")).unwrap(); + // a dry run from native: tested, nothing recorded + let (record_before, seen_before) = (record(), seen()); + let on_native = [ + ("store", t("pg")), + ("machine", t("native")), + ("dry_run", SdkValue::Bool(true)), + ]; + let tested = long(&home, "store.attach", &on_native); + assert_eq!(tested.get_text("outcome"), Some("tested"), "{tested:?}"); + assert_eq!(tested.get_text("machine"), Some("native"), "{tested:?}"); + assert!(tested.get_int("latency_ms").is_some(), "{tested:?}"); + assert_eq!(record(), record_before, "a dry run attached"); + assert_eq!(seen(), seen_before, "a dry run recorded a reach"); + ok(&home, "store.attach", &on_native[..2]); + // a stopped lima machine, attached as `store.attach` records it + home::write_record( + &paths::machine_record(&home, "dev"), + &SdkValue::map([ + ("name", t("dev")), + ("platform", t("lima")), + ("vm_name", t("layerfs-test-dev")), + ]), + ) + .unwrap(); + let path = paths::store_record(&home, "pg"); + let held = home::read_record(&path).unwrap().unwrap(); + let attached = SdkValue::List(vec![t("native"), t("dev")]); + home::write_record(&path, &home::with_field(held, "attached", attached)).unwrap(); + // its dry run is refused as its attach would be, naming the machine + let on_dev = [ + ("store", t("pg")), + ("machine", t("dev")), + ("dry_run", SdkValue::Bool(true)), + ]; + let refused = refusal(&home, "store.attach", &on_dev); + assert_eq!(flat(&refused, "machine"), t("dev"), "{refused:?}"); + // the same Store at another address: refused, dev named, nothing saved + let moved = url.replacen("127.0.0.1", "localhost", 1); + assert_ne!(moved, url, "the test server is at 127.0.0.1"); + let (record_before, seen_before) = (record(), seen()); + let change = [("store", t("pg")), ("url", t(&moved))]; + let refused = refusal(&home, "store.connect", &change); + assert_eq!(refused.code, "Conflict", "{}", refused.message); + assert!(refused.message.contains("dev"), "{}", refused.message); + assert!(!refused.message.contains("native"), "{}", refused.message); + let machines = flat(&refused, "machines"); + let SdkValue::List(rows) = &machines else { + panic!("{refused:?}"); + }; + assert_eq!(rows.len(), 1, "{rows:?}"); + assert_eq!(rows[0].get_text("machine"), Some("dev")); + assert_eq!(rows[0].get("ok"), Some(&SdkValue::Bool(false))); + assert_eq!( + refused.detail.get_text("fix"), + Some("layerfs store detach pg --machine dev") + ); + assert_eq!(record(), record_before, "a refused connect saved"); + // its dry run: this computer and each machine, nothing saved or seen + let mut dry = change.to_vec(); + dry.push(("dry_run", SdkValue::Bool(true))); + let tested = long(&home, "store.connect", &dry); + assert_eq!(tested.get_text("outcome"), Some("tested"), "{tested:?}"); + assert_eq!(tested.get("ok"), Some(&SdkValue::Bool(false)), "{tested:?}"); + let here = tested.get("here").unwrap(); + assert_eq!(here.get("ok"), Some(&SdkValue::Bool(true)), "{tested:?}"); + let Some(SdkValue::List(rows)) = tested.get("machines") else { + panic!("{tested:?}"); + }; + let row = |name: &str| { + let found = rows + .iter() + .find(|row| row.get_text("machine") == Some(name)); + found.unwrap_or_else(|| panic!("{name}: {rows:?}")).clone() + }; + assert_eq!(row("native").get("ok"), Some(&SdkValue::Bool(true))); + assert!(row("native").get_int("latency_ms").is_some(), "{rows:?}"); + assert_eq!(row("dev").get("ok"), Some(&SdkValue::Bool(false))); + assert!(row("dev").get_text("message").is_some(), "{rows:?}"); + assert_eq!(record(), record_before, "a dry run saved"); + assert_eq!(seen(), seen_before, "a dry run recorded a reach"); + // the setting alone: no machine is dialled, so dev does not refuse it + let setting = [ + ("store", t("pg")), + ("url", t(&url)), + ("synchronous_commit", t("on")), + ]; + let updated = long(&home, "store.connect", &setting); + assert_eq!(updated.get_text("outcome"), Some("updated"), "{updated:?}"); + std::fs::remove_dir_all(&home).unwrap(); +} diff --git a/api/node/src/index.d.ts b/api/node/src/index.d.ts index 424089932e..8b8bf17716 100644 --- a/api/node/src/index.d.ts +++ b/api/node/src/index.d.ts @@ -505,11 +505,13 @@ export interface StoreConnectOptions extends CallOptions { user?: string; password?: Content; synchronous_commit?: string; + dry_run?: boolean; } /** Options of `store.attach`; an unknown option is refused. */ export interface StoreAttachOptions extends CallOptions { machine: string; + dry_run?: boolean; } /** Options of `store.detach`; an unknown option is refused. */ diff --git a/control/crates/layerfs-control/src/store.rs b/control/crates/layerfs-control/src/store.rs index 4b78cf10c1..7d6f029135 100644 --- a/control/crates/layerfs-control/src/store.rs +++ b/control/crates/layerfs-control/src/store.rs @@ -9,8 +9,9 @@ use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_home::events::Events; use layerfs_home::names::{MachineName, StoreName}; use layerfs_home::outcome::shell_word; -use layerfs_home::outcome::{refused, with_fix, Outcome, FIX}; +use layerfs_home::outcome::{refused, with_fix, with_next, Outcome, FIX}; use layerfs_machine::worker::Unreached; +use layerfs_store::diagnostic::ConnectionStep; use layerfs_store::open_args::OpenArgs; use layerfs_store::place::{self, Executor}; use layerfs_store::postgresql::check; @@ -225,11 +226,109 @@ pub fn disconnect(home: &Path, name: &StoreName) -> Outcome { connect::disconnect(home, name, RELATED) } -/// `store.connect(store, url, { user, password, synchronous_commit })`: -/// a new PostgreSQL Store, or a connected one's address, login or setting, -/// checked from this process before anything is saved. -pub fn connect(home: &Path, request: &StoreConnect) -> Outcome { - connect::run(home, request) +/// `store.connect(store, url, { user, password, synchronous_commit, +/// dry_run })`: a new PostgreSQL Store, or a connected one's address, +/// login or setting, checked from this process before anything is saved. +/// A change of a connected Store's address, user or password is then +/// checked from every machine attached to it, one after another, as its +/// Sandboxes would dial the new values: one that fails refuses the +/// connect `Conflict` ([`cut_off`]), nothing saved, so no attached machine +/// is cut off unseen. A dry run makes the same checks (the machines' for +/// any change, and only once this computer passed), saves and records +/// nothing and is refused by none of them: it answers +/// [`connect::tested`]. +pub fn connect(home: &Path, events: &mut Events<'_>, request: &StoreConnect) -> Outcome { + let Some(update) = connect::prepare(home, request)? else { + return connect::connect(home, request); + }; + if !request.dry_run { + if let Err(refusal) = &update.here { + return Err(refusal.clone()); + } + } + let machines = update.trial().attached(); + let mut checked = Vec::new(); + if update.here.is_ok() && (request.dry_run || update.redials()) { + for machine in &machines { + let url = update.dial().to_owned(); + let seen = check_dialling(home, events, update.trial(), machine, url).1; + checked.push((machine.as_str(), seen)); + } + } + let name = request.store.as_str(); + if request.dry_run { + let row = |machine: &str, tested: SdkValue| { + let mut fields = vec![("machine".to_owned(), SdkValue::text(machine))]; + if let SdkValue::Map(tested) = tested { + fields.extend(tested); + } + SdkValue::Map(fields) + }; + let rows = match update.here.is_ok() { + true => (checked.iter()) + .map(|(machine, seen)| row(machine, check::tested(seen))) + .collect(), + // this computer not let in: each machine would only repeat it + false => (machines.iter()) + .map(|machine| row(machine, not_checked())) + .collect(), + }; + let here = check::tested(&update.here); + return Ok(connect::tested(name, &request.url, here, rows)); + } + let failed: Vec<_> = (checked.iter()) + .filter_map(|(machine, seen)| seen.as_ref().err().map(|refusal| (*machine, refusal))) + .collect(); + if !failed.is_empty() { + return Err(cut_off(name, &failed)); + } + update.save(home, request) +} + +/// A dry run's row of a machine not checked: this computer's check failed +/// first. +fn not_checked() -> SdkValue { + SdkValue::map([ + ("ok", SdkValue::Null), + ( + "message", + SdkValue::text("not checked: this computer's check failed first"), + ), + ]) +} + +/// The `Conflict` of a connect whose new address or login the attached +/// machines `failed` do not reach: their names in the message, `machines` +/// `[{ machine, ok: false, step, message }]` beside it, and as its fix the +/// detach of the first (or connect it with values they reach). +fn cut_off(store: &str, failed: &[(&str, &SdkRefusal)]) -> SdkRefusal { + let names: Vec<_> = failed.iter().map(|(machine, _)| *machine).collect(); + let message = format!( + "the new connection of PostgreSQL Store {store} does not reach attached machine(s) {}; nothing was saved", + names.join(", ") + ); + let rows = failed.iter().map(|(machine, refusal)| { + SdkValue::map([ + ("machine", SdkValue::text(*machine)), + ("ok", SdkValue::Bool(false)), + ("step", SdkValue::opt_text(check::step_of(refusal))), + ("message", SdkValue::text(&refusal.message)), + ]) + }); + let refusal = with_next( + refused("Conflict", message), + "machines", + SdkValue::List(rows.collect()), + ); + let first = names.first().copied().unwrap_or_default(); + with_fix( + refusal, + format!( + "layerfs store detach {} --machine {}", + shell_word(store), + shell_word(first) + ), + ) } /// The PostgreSQL Store `name` a machine attaches to or detaches from: a @@ -249,25 +348,32 @@ fn attachable(home: &Path, name: &StoreName, machine: &str) -> Result, name: &StoreName, machine: &MachineName, + dry_run: bool, ) -> Outcome { let machine = machine.as_str(); let record = attachable(home, name, machine)?; runs_postgresql_sandboxes(home, name, machine)?; let attached = record.is_attached(machine); let checked = check_from(home, events, &record, machine).1; + if dry_run { + return Ok(attach_answer("tested", name, machine, &checked?)); + } if attached || checked.is_ok() { let seen = layerfs_store::observed::Reach::of(&checked); layerfs_store::observed::record(home, name, Some(machine), &seen); @@ -275,15 +381,20 @@ pub fn attach( let checked = checked?; let new = check::attach(home, name, machine, record.binding())?; let outcome = if new { "attached" } else { "checked" }; + Ok(attach_answer(outcome, name, machine, &checked)) +} + +/// `store.attach`'s answer for the check `checked` of `machine`. +fn attach_answer(outcome: &str, name: &StoreName, machine: &str, checked: &SdkValue) -> SdkValue { let copied = |key: &str| checked.get(key).cloned().unwrap_or_default(); - Ok(SdkValue::map([ + SdkValue::map([ ("ok", SdkValue::Bool(true)), ("outcome", SdkValue::text(outcome)), ("store", SdkValue::text(name.as_str())), ("machine", SdkValue::text(machine)), ("latency_ms", copied("latency_ms")), ("server_version", copied("server_version")), - ])) + ]) } /// `store.detach(store, { machine })`: machine `machine` no longer runs @@ -351,21 +462,24 @@ fn runs_postgresql_sandboxes(home: &Path, store: &str, machine: &str) -> Result< /// `refusal` of the check from machine `machine`, naming it, the Store and /// the host it dialled (never the URL), with the platform's `hint` only /// when no connection was made (a server that answered, with a refused -/// login or another Store, was reached). A worker from a bundle without -/// the check says how to update it. +/// login or another Store, was reached), and the step the check named. A +/// worker from a bundle without the check says how to update it. fn from_machine( refusal: SdkRefusal, (store, machine, host): (&str, &str, &str), hint: Option<&str>, ) -> SdkRefusal { + let step = check::step_of(&refusal).map(str::to_owned); let message = refusal.message; - match refusal.code.as_str() { - "InvalidInput" if message.contains("no operation store.reach") => refused( - "Unsupported", - format!( - "machine {machine}'s worker predates this check; `layerfs machine stop {machine}` and `layerfs machine start {machine}` update it" - ), - ), + let made = match refusal.code.as_str() { + "InvalidInput" if message.contains("no operation store.reach") => { + return refused( + "Unsupported", + format!( + "machine {machine}'s worker predates this check; `layerfs machine stop {machine}` and `layerfs machine start {machine}` update it" + ), + ) + } "Unavailable" if !message.starts_with(check::ANOTHER_STORE) => { let hint = hint .filter(|_| layerfs_store::postgresql::open::not_connected(&message)) @@ -382,38 +496,81 @@ fn from_machine( code, format!("machine {machine}, PostgreSQL Store {store} at {host}: {message}"), ), + }; + match step { + Some(step) => with_next(made, check::STEP, SdkValue::text(step)), + None => made, } } /// The check of machine `machine`'s connection to PostgreSQL Store /// `record` (the Store's URL with its login), run from that machine: in -/// this process, or in its worker as -/// `store.reach`. The URL is built as the machine's Sandboxes' calls build -/// it. Answers the check, `{ at, server_version, latency_ms }`, or its -/// refusal; either way with the host it dialled, once known. +/// this process, or in its worker as `store.reach`. Answers the check, +/// `{ at, server_version, latency_ms }`, or its refusal, which names the +/// `machine` and, once the check began, the connection `step` it stopped +/// at (`configuration` for a login this computer does not hold, or an +/// address the machine cannot dial); either way with the host it +/// dialled, once known. pub(crate) fn check_from( home: &Path, events: &mut Events<'_>, record: &StoreRecord, machine: &str, ) -> (Option, Result) { - let name = record.name(); - let (postgresql, hint) = match layerfs_sandbox::route::reached(home, machine, record) { - Ok(reached) => reached, - #[cfg(feature = "machine")] + match layerfs_store::record::url(record) { + Ok(url) => check_dialling(home, events, record, machine, url), Err(refusal) => { - let refusal = crate::machine::RELATED.nameless_fix(home, machine, refusal); - return (None, Err(refusal)); + let refusal = check::at_step(refusal, ConnectionStep::Configuration); + (None, Err(on_machine(refusal, machine))) } - #[cfg(not(feature = "machine"))] - Err(refusal) => return (None, Err(refusal)), + } +} + +/// `refusal` of a check from machine `machine`, naming it. +fn on_machine(refusal: SdkRefusal, machine: &str) -> SdkRefusal { + with_next(refusal, "machine", SdkValue::text(machine)) +} + +/// [`check_from`] dialling `url`, the Store's address with a login in it, +/// as the machine's Sandboxes' calls build it (`store.connect` checks new +/// values before it saves them). +fn check_dialling( + home: &Path, + events: &mut Events<'_>, + record: &StoreRecord, + machine: &str, + url: String, +) -> (Option, Result) { + let (host, checked) = dial_from(home, events, record, machine, url); + ( + host, + checked.map_err(|refusal| on_machine(refusal, machine)), + ) +} + +/// [`check_dialling`] before its refusal names the machine. +fn dial_from( + home: &Path, + events: &mut Events<'_>, + record: &StoreRecord, + machine: &str, + url: String, +) -> (Option, Result) { + let name = record.name(); + let configuration = |refusal| check::at_step(refusal, ConnectionStep::Configuration); + let (postgresql, hint) = match layerfs_sandbox::route::dialled(home, machine, record, url) { + Ok(Ok(reached)) => reached, + // an address this machine cannot dial (a loopback of this host it + // does not share), refused before any dial + Ok(Err(refusal)) => return (None, Err(configuration(nameless(home, machine, refusal)))), + Err(refusal) => return (None, Err(nameless(home, machine, refusal))), }; // the host named is read from the address the machine dials, with no // login: the URL dialled holds the password let address = record.text("url").unwrap_or_default(); let host = match connect::target(address) { Ok((host, _, _)) => host, - Err(refusal) => return (None, Err(refusal)), + Err(refusal) => return (None, Err(configuration(refusal))), }; let executor = match place::on_machine(home, machine) { Ok(executor) => executor, @@ -441,6 +598,19 @@ pub(crate) fn check_from( (Some(host), checked) } +/// `refusal` with the fix of a machine that has no VM name, when it is one. +fn nameless(home: &Path, machine: &str, refusal: SdkRefusal) -> SdkRefusal { + #[cfg(feature = "machine")] + { + crate::machine::RELATED.nameless_fix(home, machine, refusal) + } + #[cfg(not(feature = "machine"))] + { + let _ = (home, machine); + refusal + } +} + /// `store.reach` in a machine's worker: `{ store, store_record, postgresql }` /// from the caller, which put the saved login into the URL this machine /// dials. Answers the check `store.attach` and `store.doctor` ask for. diff --git a/control/crates/layerfs-sandbox/src/route.rs b/control/crates/layerfs-sandbox/src/route.rs index 864bad3960..f30992a0d0 100644 --- a/control/crates/layerfs-sandbox/src/route.rs +++ b/control/crates/layerfs-sandbox/src/route.rs @@ -106,20 +106,22 @@ pub fn reached( machine: &str, record: &StoreRecord, ) -> Result<(PgSelection, Option)> { - dialled(home, machine, record)? + dialled(home, machine, record, layerfs_store::record::url(record)?)? } -/// [`reached`], with the refusal of a URL the machine cannot dial -/// (`layerfs_machine::platform::reach`: a loopback or socket of this host -/// it does not share, or a URL it cannot read to check) kept apart, as -/// `Ok(Err(refusal))`, from every other failure (a missing saved login, -/// a record with no URL, an unreadable machine record), which is `Err`. -fn dialled( +/// [`reached`] dialling `url`, the Store's address with a login in it +/// (`store.connect` checks a new address or login from each attached +/// machine before it saves them), with the refusal of a URL the machine +/// cannot dial (`layerfs_machine::platform::reach`: a loopback or socket +/// of this host it does not share, or a URL it cannot read to check) kept +/// apart, as `Ok(Err(refusal))`, from every other failure (an +/// unreadable machine record), which is `Err`. +pub fn dialled( home: &Path, machine: &str, record: &StoreRecord, + url: String, ) -> Result)>> { - let url = layerfs_store::record::url(record)?; // a build without machines (the guest's) runs its own Sandboxes on the // machine it is, which shares its loopback #[cfg(feature = "machine")] @@ -351,7 +353,8 @@ fn host_op( (Some(value), hint) } (StoreKind::Postgresql, StoreUrl::Cleanup) => { - match dialled(&home, machine, &target.record)? { + let url = layerfs_store::record::url(&target.record)?; + match dialled(&home, machine, &target.record, url)? { Ok((value, hint)) => (Some(value), hint), Err(_cannot_dial) => (None, None), } diff --git a/control/crates/layerfs-store/src/diagnostic.rs b/control/crates/layerfs-store/src/diagnostic.rs index e60e062c59..17c65d08f7 100644 --- a/control/crates/layerfs-store/src/diagnostic.rs +++ b/control/crates/layerfs-store/src/diagnostic.rs @@ -6,7 +6,7 @@ use layerfs_bridge::sdk_values::hex; pub use layerfs_history::LayerStackId; use layerfs_home::outcome::refused; pub use layerfs_persistence::diagnostic::{ - Observation, Options, Outcome, ProjectCoverage, PROJECT_CHECK, + ConnectionStep, Observation, Options, Outcome, ProjectCoverage, PROJECT_CHECK, }; /// How long a PostgreSQL connection may take to be made and logged in. pub use layerfs_persistence::POSTGRESQL_HANDSHAKE; diff --git a/control/crates/layerfs-store/src/postgresql/check.rs b/control/crates/layerfs-store/src/postgresql/check.rs index 2bf6f2c7e4..7e6b60cc43 100644 --- a/control/crates/layerfs-store/src/postgresql/check.rs +++ b/control/crates/layerfs-store/src/postgresql/check.rs @@ -5,13 +5,15 @@ //! machine has an address of its own. This module is the Store's part: the //! check run on the side that dials, and the attachment writes. Which side //! dials is the caller's (`layerfs-control`, through the Sandbox route). +use crate::diagnostic::ConnectionStep; use crate::open_args::PgSelection; use crate::postgresql::connect::SCHEMA; use crate::record::{StoreKind, StoreRecord}; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_home::home; use layerfs_home::names::StoreName; -use layerfs_home::outcome::refused; +use layerfs_home::outcome::{public_code, refused, with_next, NEXT}; +use layerfs_persistence::PostgresAccess; use std::path::Path; type Result = std::result::Result; @@ -35,70 +37,160 @@ pub fn postgresql_record(home: &Path, name: &str) -> Result { /// another Store (or none): reached, so no reach hint applies. pub const ANOTHER_STORE: &str = "the PostgreSQL server holds another Store than"; +/// The key a reach refusal names the connection step it stopped at by +/// (one of [`ConnectionStep`]'s words), answered flat beside `error` and +/// `message`, as the doctor's `store.connection.`. +pub const STEP: &str = "step"; + +/// `refusal` naming the connection step it stopped at. +pub fn at_step(refusal: SdkRefusal, step: ConnectionStep) -> SdkRefusal { + with_next(refusal, STEP, SdkValue::text(step.name())) +} + +/// The step a reach refusal names, when it names one. +pub fn step_of(refusal: &SdkRefusal) -> Option<&str> { + refusal + .detail + .get(NEXT) + .and_then(|next| next.get_text(STEP)) +} + +/// A check as a dry run answers it: `{ ok: true, latency_ms, +/// server_version }`, or `{ ok: false, step, code, message }`, `code` the +/// public refusal code and `step` null when nothing was dialled. +pub fn tested(checked: &Result) -> SdkValue { + match checked { + Ok(answer) => { + let copied = |key: &str| answer.get(key).cloned().unwrap_or_default(); + SdkValue::map([ + ("ok", SdkValue::Bool(true)), + ("latency_ms", copied("latency_ms")), + ("server_version", copied("server_version")), + ]) + } + Err(refusal) => SdkValue::map([ + ("ok", SdkValue::Bool(false)), + ( + "step", + SdkValue::opt_text(step_of(refusal).map(str::to_owned)), + ), + ("code", SdkValue::text(public_code(&refusal.code))), + ("message", SdkValue::text(&refusal.message)), + ]), + } +} + +/// One dial of the server at `postgresql`: what its role may do in the +/// Store's schema, or the refusal naming the step the connection stopped +/// at, as the doctor's connection check names it. The server not reached +/// is `Unavailable`, a login or database refused `Denied`. +fn access(postgresql: &PgSelection) -> Result { + use layerfs_persistence::PostgresStatusError as E; + let url = + (postgresql.url()).map_err(|refusal| at_step(refusal, ConnectionStep::Configuration))?; + layerfs_persistence::postgresql_access(url, SCHEMA).map_err(|error| { + let code = match error { + E::Denied(..) => "Denied", + E::Unreachable(..) => "Unavailable", + E::Failed(_) => "Failed", + }; + at_step(refused(code, error.to_string()), error.step()) + }) +} + +/// What a passed check answers: `{ at, server_version, latency_ms }`. +fn reached(access: &PostgresAccess) -> SdkValue { + SdkValue::map([ + ("at", SdkValue::Int(home::now_ms())), + ("server_version", SdkValue::text(&access.server_version)), + ( + "latency_ms", + SdkValue::Int(i64::try_from(access.latency.as_millis()).unwrap_or(i64::MAX)), + ), + ]) +} + +/// The binding the Store schema at `postgresql` holds, `None` when the +/// database has no such schema. A read that fails is the identity's step, +/// or the schema's when the role may not use the schema. +fn binding_of(access: &PostgresAccess, postgresql: &PgSelection) -> Result>> { + if !access.schema { + return Ok(None); + } + let usage = format!("USAGE on schema {SCHEMA}"); + let step = match access.missing.contains(&usage) { + true => ConnectionStep::Schema, + false => ConnectionStep::Identity, + }; + let binding = crate::postgresql::open::read_binding(postgresql); + binding.map(Some).map_err(|refusal| at_step(refusal, step)) +} + +/// The refusal of a database that holds another Store than `record`, or +/// none (the schema's step when it has no Store schema, else the +/// identity's). +fn another(record: &StoreRecord, step: ConnectionStep) -> SdkRefusal { + let message = format!("{ANOTHER_STORE} {}", record.name()); + at_step(refused("Unavailable", message), step) +} + /// The check of one machine's connection, run on the side that dials it: /// the schema at `postgresql` must hold Store `record`'s binding, and the /// role must have every privilege a Sandbox's writes need there. Answers /// the check, `{ at, server_version, latency_ms }`, which its caller -/// records ([`crate::observed`]). The server -/// not reached is `Unavailable`, a login refused or a privilege missing -/// `Denied`, and another Store's schema `Unavailable` naming it. +/// records ([`crate::observed`]). The server not reached is +/// `Unavailable`, a login refused or a privilege missing `Denied`, and +/// another Store's schema `Unavailable` naming it; each refusal names its +/// step ([`STEP`]). pub fn check(record: &StoreRecord, postgresql: &PgSelection) -> Result { - use layerfs_persistence::PostgresStatusError as E; - let access = - layerfs_persistence::postgresql_access(postgresql.url()?, SCHEMA).map_err(|error| { - match error { - E::Denied(_) => refused("Denied", error.to_string()), - E::Unreachable(_) => refused("Unavailable", error.to_string()), - E::Failed(_) => refused("Failed", error.to_string()), - } - })?; - let another = || refused("Unavailable", format!("{ANOTHER_STORE} {}", record.name())); + let access = access(postgresql)?; let denied = |first: &str| { - refused( - "Denied", - format!( - "role {} lacks {first} ({} privilege(s) missing in all)", - access.role, - access.missing.len() - ), - ) + let message = format!( + "role {} lacks {first} ({} privilege(s) missing in all)", + access.role, + access.missing.len() + ); + at_step(refused("Denied", message), ConnectionStep::Schema) }; if !access.schema { - return Err(another()); + return Err(another(record, ConnectionStep::Schema)); } // a role that may not use the schema cannot read its binding either if let Some(first) = access.missing.first().filter(|m| m.contains(" on schema ")) { return Err(denied(first)); } - let binding = crate::postgresql::open::read_binding(postgresql)?; - if record.binding() != Some(binding.as_slice()) { - return Err(another()); + let binding = binding_of(&access, postgresql)?; + if record.binding() != binding.as_deref() { + return Err(another(record, ConnectionStep::Identity)); } if let Some(first) = access.missing.first() { return Err(denied(first)); } - Ok(SdkValue::map([ - ("at", SdkValue::Int(home::now_ms())), - ("server_version", SdkValue::text(access.server_version)), - ( - "latency_ms", - SdkValue::Int(i64::try_from(access.latency.as_millis()).unwrap_or(i64::MAX)), - ), - ])) + Ok(reached(&access)) } -/// The light check of a connection the Store's own calls use: the server -/// at `postgresql` is reached and its schema holds Store `record`'s -/// binding. A role that may only read passes, as it does `store.connect`. -pub fn same_store(record: &StoreRecord, postgresql: &PgSelection) -> Result<()> { - let binding = crate::postgresql::open::read_binding(postgresql)?; +/// The light check of a connection the Store's own calls use (this +/// computer's, which `store.connect` makes): the server at `postgresql` is +/// reached and its schema holds Store `record`'s binding. A role that may +/// only read passes. Answers as [`check`] does, each refusal naming its +/// step. +pub fn same_store(record: &StoreRecord, postgresql: &PgSelection) -> Result { + let access = access(postgresql)?; + let binding = binding_of(&access, postgresql)?; + let binding = binding.ok_or_else(|| another(record, ConnectionStep::Schema))?; if record.binding() != Some(binding.as_slice()) { - return Err(refused( - "Unavailable", - format!("{ANOTHER_STORE} {}", record.name()), - )); + return Err(another(record, ConnectionStep::Identity)); } - Ok(()) + Ok(reached(&access)) +} + +/// The check of the database a Store's first connect names, from this +/// computer: answers as [`check`] does, with the binding its Store schema +/// holds (`None`: an empty database, which the connect gives the schema). +pub fn first(postgresql: &PgSelection) -> Result<(SdkValue, Option>)> { + let access = access(postgresql)?; + let binding = binding_of(&access, postgresql)?; + Ok((reached(&access), binding)) } /// The record of Store `name` under the home lock and the Store's, read diff --git a/control/crates/layerfs-store/src/postgresql/connect.rs b/control/crates/layerfs-store/src/postgresql/connect.rs index 9f2de3b308..00aed33680 100644 --- a/control/crates/layerfs-store/src/postgresql/connect.rs +++ b/control/crates/layerfs-store/src/postgresql/connect.rs @@ -9,7 +9,9 @@ //! attach to a Store (`layerfs-control`'s `store.attach`) and dial both. use super::address::{self, with_login}; pub use super::address::{holds_login, refuse_login, shown, target, HIDDEN}; +use super::check; use super::login; +use crate::diagnostic::ConnectionStep; use crate::open_args::{OpenArgs, PgSelection}; use crate::project::listing; use crate::project::record::ProjectRecord; @@ -18,7 +20,7 @@ use crate::record::{StoreKind, StoreRecord}; use crate::Related; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_bridge::sdk_values::hex; -use layerfs_home::home::{self, paths}; +use layerfs_home::home::{self, paths, with_field}; use layerfs_home::names::StoreName; use layerfs_home::outcome::{failed, refused, shell_word, with_fix, Outcome}; use std::path::Path; @@ -61,6 +63,8 @@ pub struct StoreConnect { pub password: Option, /// `synchronous_commit`; `local` for a new Store, else the saved one. pub synchronous_commit: Option, + /// Check as the connect would, save nothing and answer `tested`. + pub dry_run: bool, } /// [`refuse_login`]'s refusal for `store connect `, with its @@ -185,13 +189,13 @@ fn given<'a>(value: Option<&'a str>, what: &str) -> Result> { } } -/// `store.connect`: a new Store ([`connect`]), or a connected one's -/// address, login or setting ([`update`]). A sqlite Store of the name is -/// `Exists`. -pub fn run(home_dir: &Path, request: &StoreConnect) -> Outcome { +/// `store.connect` of a connected Store, checked from this computer +/// ([`Update`]), or `None` when no Store of the name exists (a first +/// connect, [`connect`]). A sqlite Store of the name is `Exists`. +pub fn prepare(home_dir: &Path, request: &StoreConnect) -> Result> { let name = request.store.as_str(); let Some(record) = StoreRecord::read(home_dir, name)? else { - return connect(home_dir, request); + return Ok(None); }; if record.kind()? != StoreKind::Postgresql { return Err(refused( @@ -199,18 +203,21 @@ pub fn run(home_dir: &Path, request: &StoreConnect) -> Outcome { format!("a sqlite Store named {name} exists"), )); } - update(home_dir, request) + update(home_dir, request).map(Some) } /// `store.connect` of a new Store: records a PostgreSQL database as Store /// `request.store`, its user and password required. Every refusal of its -/// input comes before any effect. The connection is made from this -/// process with the given login, which gives an empty database the schema -/// and a new id or reads the id the schema holds, and lists its projects, -/// before the home lock; the lock covers the re-checks and the writes -/// only: the record, then the password. A database whose id another -/// Store of this home holds is `Exists`. Once saved, the check's reach is -/// this computer's (`here`); a refused connect records nothing. +/// input comes before any effect. The connection is checked from this +/// process with the given login ([`check::first`], each refusal naming +/// its step); an empty database is then given the schema and a new id, or +/// the id the schema holds is kept, and its projects are listed, before +/// the home lock; the lock covers the re-checks and the writes only: the +/// record, then the password. A database whose id another Store of this +/// home holds is `Exists`. Once saved, the check's reach is this +/// computer's (`here`); a refused connect records nothing. A dry run stops +/// after the check, before any schema is made, and answers [`tested`]: +/// `here.empty` says the database has no Store schema yet. pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { let name = request.store.as_str(); let given_url = request.url.as_str(); @@ -232,6 +239,21 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { } let record = StoreRecord::connected(name, given_url, user, SCHEMA, sync).in_home(home_dir); let probe = selection_at(&record, with_login(given_url, user, password)?); + let checked = check::first(&probe); + if request.dry_run { + let here = match checked { + Ok((answer, Some(binding))) => { + unclaimed_by_others(home_dir, name, &binding)?; + check::tested(&Ok(answer)) + } + Ok((answer, None)) => { + with_field(check::tested(&Ok(answer)), "empty", SdkValue::Bool(true)) + } + Err(refusal) => check::tested(&Err(refusal)), + }; + return Ok(tested(name, given_url, here, Vec::new())); + } + let (checked, found) = checked?; // an empty database gets the schema, with a new binding (#533 step // 10b); an existing LayerFS schema keeps its binding, read once. The // cursor key is this home's own either way. @@ -243,13 +265,19 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { binding: layerfs_home::helpers::random()?.to_vec(), cursor_key: layerfs_home::helpers::random()?, }; - let started = std::time::Instant::now(); - let binding = if crate::project::postgres_init::create_schema(&probe, &fresh)? { - fresh.binding - } else { - crate::postgresql::open::read_binding(&probe)? + let binding = match found { + Some(binding) => binding, + None => { + let made = crate::project::postgres_init::create_schema(&probe, &fresh) + .map_err(|refusal| check::at_step(refusal, ConnectionStep::Schema))?; + match made { + true => fresh.binding.clone(), + false => crate::postgresql::open::read_binding(&probe) + .map_err(|refusal| check::at_step(refusal, ConnectionStep::Identity))?, + } + } }; - let reach = measured(started); + let reach = crate::observed::Reach::of(&Ok(checked)); unclaimed_by_others(home_dir, name, &binding)?; let record = record.with("binding", SdkValue::Bytes(binding.clone())); let record = record.with("cursor", SdkValue::Bytes(fresh.cursor_key.to_vec())); @@ -277,27 +305,50 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { Ok(answer(&record, "connected", Some(&projects))) } -/// This computer's reach from a connect's own check, begun at `started`: -/// reached, with how long the check took. It is recorded only once the -/// connect is saved, as `store.doctor` records its check (`here`). -fn measured(started: std::time::Instant) -> crate::observed::Reach { - crate::observed::Reach { - ok: true, - latency_ms: Some(i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX)), - ..crate::observed::Reach::default() - } +/// A dry run's answer: `{ ok, outcome: tested, store, url, here, machines +/// }`, `here` this computer's check ([`check::tested`]) and `machines` +/// each attached machine's, with its `machine`; `ok` when every check +/// passed. Nothing was saved or recorded. +pub fn tested(store: &str, url: &str, here: SdkValue, machines: Vec) -> SdkValue { + let passed = |row: &SdkValue| row.get("ok") == Some(&SdkValue::Bool(true)); + let ok = passed(&here) && machines.iter().all(passed); + SdkValue::map([ + ("ok", SdkValue::Bool(ok)), + ("outcome", SdkValue::text("tested")), + ("store", SdkValue::text(store)), + ("url", SdkValue::text(url)), + ("here", here), + ("machines", SdkValue::List(machines)), + ]) +} + +/// `store.connect` of a connected Store, checked from this computer and +/// not yet saved: its address, and any of a new user, password and +/// `synchronous_commit` (those not given are kept). No `Debug`: it holds +/// the password. +pub struct Update { + /// The record as it was read. + record: StoreRecord, + /// The record with the new values, its attachments as they were. + trial: StoreRecord, + /// The new address with the new login: what this computer dialled and + /// each attached machine dials. + dial: String, + /// A new password, saved with the record. + new_password: Option, + /// Whether the address, user or password changes. + redials: bool, + /// This computer's check of the new values ([`check::same_store`]): + /// `{ at, server_version, latency_ms }`, or its refusal naming its + /// step. + pub here: Result, } -/// `store.connect` of a connected Store: its address `request.url`, and -/// any of a new user, password and `synchronous_commit` (those not given -/// are kept). The new values are dialled once from this process and must -/// read this Store's id (`Unavailable` otherwise) before anything is -/// saved. The record (and a new password) are written under -/// the home lock and the Store's, `Conflict` when it was disconnected or -/// connected to another database meanwhile; this process's open sessions -/// on it are closed. A running Sandbox keeps the connection it started -/// with. Once saved, the check's reach is this computer's (`here`). -pub fn update(home_dir: &Path, request: &StoreConnect) -> Outcome { +/// Validates a `store.connect` of a connected Store and dials the new +/// values once from this process, where they must read this Store's id +/// (`Unavailable` otherwise, naming the step); nothing is saved +/// ([`Update::save`]). +fn update(home_dir: &Path, request: &StoreConnect) -> Result { let name = request.store.as_str(); let record = super::check::postgresql_record(home_dir, name)?; refuse_url(name, &request.url, false)?; @@ -327,44 +378,89 @@ pub fn update(home_dir: &Path, request: &StoreConnect) -> Outcome { if let Some(sync) = &request.synchronous_commit { synchronous_commit(sync)?; } - let changed = |record: StoreRecord| { - let record = record - .with("url", SdkValue::text(&request.url)) - .with("user", SdkValue::text(&user)); - match &request.synchronous_commit { - Some(sync) => record.with("synchronous_commit", SdkValue::text(sync)), - None => record, + let redials = record.text("url") != Some(request.url.as_str()) + || record.text("user") != Some(user.as_str()) + || saved.as_ref().map(login::Saved::password) != Some(password.as_str()); + let trial = changed(record.clone(), request, &user); + let dial = with_login(&request.url, &user, &password)?; + let probe = selection_at(&trial, dial.clone()); + let here = super::check::same_store(&trial, &probe).map_err(|refusal| SdkRefusal { + message: format!("PostgreSQL Store {name}: {}", refusal.message), + ..refusal + }); + Ok(Update { + record, + trial, + dial, + new_password: new_password.map(str::to_owned), + redials, + here, + }) +} + +/// `record` with a connect's new address, user and setting. +fn changed(record: StoreRecord, request: &StoreConnect, user: &str) -> StoreRecord { + let record = record + .with("url", SdkValue::text(&request.url)) + .with("user", SdkValue::text(user)); + match &request.synchronous_commit { + Some(sync) => record.with("synchronous_commit", SdkValue::text(sync)), + None => record, + } +} + +impl Update { + /// The record with the new values, its attachments as they were. + pub fn trial(&self) -> &StoreRecord { + &self.trial + } + + /// The new address with the new login, as each machine dials it. + pub fn dial(&self) -> &str { + &self.dial + } + + /// Whether the address, user or password changes (machines dial + /// them); a change of `synchronous_commit` alone does not. + pub fn redials(&self) -> bool { + self.redials + } + + /// Saves the checked change `request`, refused as this computer's + /// check was. The record (and a new password) are written under the + /// home lock and the Store's, `Conflict` when it was disconnected or + /// connected to another database meanwhile; this process's open + /// sessions on it are closed. A running Sandbox keeps the connection + /// it started with. Once saved, the check's reach is this computer's + /// (`here`). + pub fn save(self, home_dir: &Path, request: &StoreConnect) -> Outcome { + let name = request.store.as_str(); + let reach = crate::observed::Reach::of(&Ok(self.here?)); + let home_lock = home::lock::take(home_dir)?; + let store_lock = crate::record::lock(home_dir, name)?; + let binding = self.record.binding(); + let current = StoreRecord::read(home_dir, name)?.filter(|r| r.binding() == binding); + let Some(current) = current else { + return Err(refused( + "Conflict", + format!("Store {name} changed while its connection was checked; connect it again"), + )); + }; + current.unblocked()?; + crate::open::close(¤t.postgresql_key(home_dir, name))?; + let current = changed( + current, + request, + self.trial.text("user").unwrap_or_default(), + ); + current.write(home_dir)?; + if let Some(password) = &self.new_password { + login::save(home_dir, name, password)?; } - }; - let trial = changed(record.clone()); - let probe = selection_at(&trial, with_login(&request.url, &user, &password)?); - let started = std::time::Instant::now(); - super::check::same_store(&trial, &probe).map_err(|refusal| { - refused( - &refusal.code, - format!("PostgreSQL Store {name}: {}", refusal.message), - ) - })?; - let reach = measured(started); - let home_lock = home::lock::take(home_dir)?; - let store_lock = crate::record::lock(home_dir, name)?; - let current = StoreRecord::read(home_dir, name)?.filter(|r| r.binding() == record.binding()); - let Some(current) = current else { - return Err(refused( - "Conflict", - format!("Store {name} changed while its connection was checked; connect it again"), - )); - }; - current.unblocked()?; - crate::open::close(¤t.postgresql_key(home_dir, name))?; - let current = changed(current); - current.write(home_dir)?; - if let Some(password) = new_password { - login::save(home_dir, name, password)?; + drop((store_lock, home_lock)); + crate::observed::record(home_dir, name, None, &reach); + Ok(answer(¤t, "updated", None)) } - drop((store_lock, home_lock)); - crate::observed::record(home_dir, name, None, &reach); - Ok(answer(¤t, "updated", None)) } /// `store.disconnect`: forgets a PostgreSQL Store, its saved password and diff --git a/control/crates/layerfs-store/src/postgresql/open.rs b/control/crates/layerfs-store/src/postgresql/open.rs index fb5cb85dd1..0bc89f3903 100644 --- a/control/crates/layerfs-store/src/postgresql/open.rs +++ b/control/crates/layerfs-store/src/postgresql/open.rs @@ -235,8 +235,8 @@ pub fn status(url: &str, schemas: &[String]) -> Outcome { ), ), ])), - Err(error @ E::Unreachable(_)) => Ok(unreached("Unavailable", error.to_string())), - Err(error @ E::Denied(_)) => Ok(unreached("Denied", error.to_string())), + Err(error @ E::Unreachable(..)) => Ok(unreached("Unavailable", error.to_string())), + Err(error @ E::Denied(..)) => Ok(unreached("Denied", error.to_string())), Err(error @ E::Failed(_)) => Err(refused("Failed", error.to_string())), } } diff --git a/control/crates/layerfs-store/tests/observed_reach.rs b/control/crates/layerfs-store/tests/observed_reach.rs index 9655229b14..df7738c0c4 100644 --- a/control/crates/layerfs-store/tests/observed_reach.rs +++ b/control/crates/layerfs-store/tests/observed_reach.rs @@ -302,7 +302,8 @@ fn only_a_dial_no_server_answered_is_not_connected() { // a database the server does not hold failed_check(&database), ] { - assert!(answered.contains("db error"), "{answered}"); + // in the server's own words, which name what it refused + assert!(answered.contains("no_such"), "{answered}"); assert!(!not_connected(&answered), "{answered}"); } } diff --git a/control/crates/layerfs-store/tests/postgresql_url_corpus.rs b/control/crates/layerfs-store/tests/postgresql_url_corpus.rs index 32506c85ec..5b4b971521 100644 --- a/control/crates/layerfs-store/tests/postgresql_url_corpus.rs +++ b/control/crates/layerfs-store/tests/postgresql_url_corpus.rs @@ -851,8 +851,10 @@ fn connect_again(home: &Path) -> Result [--user U] [--password-stdin] [--synchronous-commit local]", + "cli": "layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local] [--dry-run]", "positionals": [ { "name": "store", @@ -7602,6 +7602,11 @@ "kind": "Text", "help": "off, local, remote_write, on or remote_apply; a new Store takes local", "default": "local" + }, + { + "name": "dry_run", + "kind": "Bool", + "help": "check from this computer and each attached machine, and save nothing" } ], "stdin": "secret", @@ -7614,8 +7619,11 @@ "always": [], "sometimes": [ "ok", + "outcome", "projects", - "projects_count" + "projects_count", + "here", + "machines" ] }, "long": [ @@ -7628,15 +7636,17 @@ "url", "user", "synchronous_commit", - "machines" + "machines", + "here" ], "item": null, "examples": { "short": [ "first connect: {\"projects\":[\"api\",\"web\"]}", - "an empty database, or a connected Store changed: {\"ok\":true}" + "an empty database, or a connected Store changed: {\"ok\":true}", + "a dry run: {\"outcome\":\"tested\",\"here\":{\"ok\":true,\"latency_ms\":2,\"server_version\":\"17.6\"},\"machines\":[{\"machine\":\"lab\",\"ok\":false,\"step\":\"transport\",\"code\":\"Unavailable\",\"message\":\"machine lab cannot reach PostgreSQL Store shop-pg's server at db.internal: ...\"}]}" ], - "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"synchronous_commit\":\"local\",\"machines\":[]}" + "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"synchronous_commit\":\"local\",\"machines\":[],\"here\":null}" }, "dropped": [ { @@ -7710,7 +7720,7 @@ "badge": "new", "today": [], "help": "let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first", - "cli": "layerfs store attach --machine M", + "cli": "layerfs store attach --machine M [--dry-run]", "positionals": [ { "name": "store", @@ -7723,6 +7733,11 @@ "kind": "Name", "help": "the machine; required", "required": true + }, + { + "name": "dry_run", + "kind": "Bool", + "help": "check from the machine as attach does, and record nothing" } ], "stdin": null, @@ -7752,12 +7767,13 @@ "examples": { "short": [ "{\"ok\":true,\"outcome\":\"attached\",\"latency_ms\":3}", - "an attached machine checked again: {\"ok\":true,\"outcome\":\"checked\",\"latency_ms\":2}" + "an attached machine checked again: {\"ok\":true,\"outcome\":\"checked\",\"latency_ms\":2}", + "a dry run: {\"ok\":true,\"outcome\":\"tested\",\"latency_ms\":3}" ], "long": "{\"ok\":true,\"outcome\":\"attached\",\"store\":\"shop-pg\",\"machine\":\"lab\",\"latency_ms\":3,\"server_version\":\"17.6\"}" }, "dropped": [], - "new_work": "New (owner, 2026-11-24): the Store is checked from the machine with the URL and login this computer saved, as its Sandboxes dial them; the machine is then recorded in the Store's `attached` and its reach observed. sandbox.create on a machine not attached is refused with this call as its fix." + "new_work": "New (owner, 2026-11-24): the Store is checked from the machine with the URL and login this computer saved, as its Sandboxes dial them; the machine is then recorded in the Store's `attached` and its reach observed. sandbox.create on a machine not attached is refused with this call as its fix. `--dry-run` (owner, 2026-11-24): the UI's per-machine Test, which shows the step a failure stopped at." }, { "call": "store.detach", diff --git a/core/docs/issues/call-surface-2-0/families/store.json b/core/docs/issues/call-surface-2-0/families/store.json index d4873f33ac..85de9893fc 100644 --- a/core/docs/issues/call-surface-2-0/families/store.json +++ b/core/docs/issues/call-surface-2-0/families/store.json @@ -321,12 +321,12 @@ { "call": "store.connect", "badge": "reshaped", - "note": "PostgreSQL. The URL holds host, port, database and TLS options; one with a user or a password is refused InvalidInput with the fix layerfs store connect <store> <url> --user <user> --password-stdin. First connect: --user and the password are required and are checked from this computer before anything is saved; it gives an empty database the LayerFS schema and its id, or reads them, and answers the projects found. The record keeps the URL, the user and synchronous_commit; the password is kept in the home's secret folder (kind login, by Store), never answered or logged. On a connected Store: it changes the address, user, password or synchronous_commit, keeping what it is not given, and must reach the same Store (its binding) first (Unavailable otherwise). It attaches no machine, native included. A database whose id another Store of this home holds, or a sqlite Store of that name, is Exists. projects shows the first 20 names. A running Sandbox keeps its connection.", + "note": "PostgreSQL. The URL holds host, port, database and TLS options; one with a user or a password is refused InvalidInput with the fix layerfs store connect <store> <url> --user <user> --password-stdin. First connect: --user and the password are required and are checked from this computer before anything is saved; it gives an empty database the LayerFS schema and its id, or reads them, and answers the projects found. The record keeps the URL, the user and synchronous_commit; the password is kept in the home's secret folder (kind login, by Store), never answered or logged. On a connected Store: it changes the address, user, password or synchronous_commit, keeping what it is not given, and must reach the same Store (its binding) first (Unavailable otherwise). It attaches no machine, native included. A database whose id another Store of this home holds, or a sqlite Store of that name, is Exists. projects shows the first 20 names. A running Sandbox keeps its connection. Changing the address, user or password of a connected Store checks the new values from this computer, then from every attached machine, one after another, before anything is saved: one that fails refuses the connect Conflict naming the machines, with machines [{machine, ok: false, step, message}] beside it and layerfs store detach <store> --machine <m> (the first) as its fix. A change of synchronous_commit alone checks no machine. Every refused check names its step (the doctor's connection steps). --dry-run makes the same checks, saves and records nothing and is refused by none of them; it answers {ok, outcome: tested, store, url, here, machines}, here this computer's check {ok, latency_ms, server_version} or {ok: false, step, code, message}, machines one such row per attached machine with its machine (ok: null when this computer's check failed first, so no machine was dialled); ok is whether every check passed. A first connect's dry run checks from this computer only and makes no schema: an empty database is here.empty: true. The password comes from stdin as usual; on a connected Store the saved one is used when none is given.", "today": [ "store.connect" ], "help": "connect a PostgreSQL database as a Store, or change a connected one's address, login or setting", - "cli": "layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local]", + "cli": "layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local] [--dry-run]", "positionals": [ { "name": "store", @@ -356,6 +356,11 @@ "kind": "Text", "help": "off, local, remote_write, on or remote_apply; a new Store takes local", "default": "local" + }, + { + "name": "dry_run", + "kind": "Bool", + "help": "check from this computer and each attached machine, and save nothing" } ], "stdin": "secret", @@ -368,8 +373,11 @@ "always": [], "sometimes": [ "ok", + "outcome", "projects", - "projects_count" + "projects_count", + "here", + "machines" ] }, "long": [ @@ -382,15 +390,17 @@ "url", "user", "synchronous_commit", - "machines" + "machines", + "here" ], "item": null, "examples": { "short": [ "first connect: {\"projects\":[\"api\",\"web\"]}", - "an empty database, or a connected Store changed: {\"ok\":true}" + "an empty database, or a connected Store changed: {\"ok\":true}", + "a dry run: {\"outcome\":\"tested\",\"here\":{\"ok\":true,\"latency_ms\":2,\"server_version\":\"17.6\"},\"machines\":[{\"machine\":\"lab\",\"ok\":false,\"step\":\"transport\",\"code\":\"Unavailable\",\"message\":\"machine lab cannot reach PostgreSQL Store shop-pg's server at db.internal: ...\"}]}" ], - "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"synchronous_commit\":\"local\",\"machines\":[]}" + "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"synchronous_commit\":\"local\",\"machines\":[],\"here\":null}" }, "dropped": [ { @@ -463,10 +473,10 @@ { "call": "store.attach", "badge": "new", - "note": "Owner, 2026-11-24.", + "note": "Owner, 2026-11-24. --dry-run makes the same checks and records nothing (neither attached nor the reach), answering outcome: tested; it takes no lock, so dry runs of several machines may run at once. A refused check names its step (one of the doctor's connection steps: configuration, transport, tls, authentication, database, schema, identity) and the machine, flat beside error and message; an address of this computer's loopback the machine does not share is refused Unsupported at configuration before any dial.", "today": [], "help": "let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first", - "cli": "layerfs store attach --machine M", + "cli": "layerfs store attach --machine M [--dry-run]", "positionals": [ { "name": "store", @@ -479,6 +489,11 @@ "kind": "Name", "help": "the machine; required", "required": true + }, + { + "name": "dry_run", + "kind": "Bool", + "help": "check from the machine as attach does, and record nothing" } ], "stdin": null, @@ -508,12 +523,13 @@ "examples": { "short": [ "{\"ok\":true,\"outcome\":\"attached\",\"latency_ms\":3}", - "an attached machine checked again: {\"ok\":true,\"outcome\":\"checked\",\"latency_ms\":2}" + "an attached machine checked again: {\"ok\":true,\"outcome\":\"checked\",\"latency_ms\":2}", + "a dry run: {\"ok\":true,\"outcome\":\"tested\",\"latency_ms\":3}" ], "long": "{\"ok\":true,\"outcome\":\"attached\",\"store\":\"shop-pg\",\"machine\":\"lab\",\"latency_ms\":3,\"server_version\":\"17.6\"}" }, "dropped": [], - "new_work": "New (owner, 2026-11-24): the Store is checked from the machine with the URL and login this computer saved, as its Sandboxes dial them; the machine is then recorded in the Store's `attached` and its reach observed. sandbox.create on a machine not attached is refused with this call as its fix." + "new_work": "New (owner, 2026-11-24): the Store is checked from the machine with the URL and login this computer saved, as its Sandboxes dial them; the machine is then recorded in the Store's `attached` and its reach observed. sandbox.create on a machine not attached is refused with this call as its fix. `--dry-run` (owner, 2026-11-24): the UI's per-machine Test, which shows the step a failure stopped at." }, { "call": "store.detach", diff --git a/docs/architecture/api/sdk/store.md b/docs/architecture/api/sdk/store.md index 66860a07b9..c1d37fe688 100644 --- a/docs/architecture/api/sdk/store.md +++ b/docs/architecture/api/sdk/store.md @@ -262,9 +262,9 @@ $ layerfs store create shop Connect a PostgreSQL database as a Store, or change a connected one's address, login or setting. ```text -CLI layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local] -Node await layerfs.store.connect(store, url, { user, password, synchronous_commit }) -Python layerfs.store.connect(store, url, *, user=None, password=None, synchronous_commit=None) +CLI layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local] [--dry-run] +Node await layerfs.store.connect(store, url, { user, password, synchronous_commit, dry_run }) +Python layerfs.store.connect(store, url, *, user=None, password=None, synchronous_commit=None, dry_run=None) ``` | Argument | Kind | Rule | @@ -274,11 +274,12 @@ Python layerfs.store.connect(store, url, *, user=None, password=None, synchrono | `user` option | text | the PostgreSQL role; required on a Store's first connect, else the saved one is kept | | `password` option | content | its password; required on a Store's first connect, else the saved one is kept; the shell reads it from stdin with `--password-stdin` | | `synchronous_commit` option | text | off, local, remote_write, on or remote_apply; a new Store takes `local`, a connected one keeps its own when omitted | +| `dry_run` option | bool | check from this computer and each attached machine, and save nothing | | Answer | Keys | | --- | --- | -| short | each when set: `ok`, `projects`, `projects_count` | -| long | `ok, projects, projects_count, outcome, store, engine, url, user, synchronous_commit, machines` | +| short | each when set: `ok`, `projects`, `projects_count`; a dry run's also `outcome`, `here`, `machines` | +| long | `ok, projects, projects_count, outcome, store, engine, url, user, synchronous_commit, machines, here` | | call | writes one call-log line; MCP `admin` | This computer is the one place a PostgreSQL Store's address and login are @@ -327,15 +328,48 @@ Short `{"ok":true}`, long `outcome` `updated`. A connect that is saved, first or not, records its check as this computer's reach (`store get`'s `reach`: `ok` and how long the check took), as `store doctor` does; a refused connect records nothing. Attachments are kept: each -attached machine dials the new address and login from its next connection, -and `store doctor` checks them. A sqlite Store of that name is `Exists`. +attached machine dials the new address and login from its next connection. +So a change of the address, user or password is checked from every +attached machine too, one after another, after this computer's check and +before anything is saved +([`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) +`connect`): one that fails refuses the connect `Conflict`, naming the +machines, with `machines` (`[{ machine, ok: false, step, message }]`) beside +it and `layerfs store detach --machine ` as its fix; nothing +is saved, so no attached machine is cut off unseen. A change of +`synchronous_commit` alone checks no machine. A sqlite Store of that name +is `Exists`. + +Every refused check names the connection step it stopped at as `step`, +flat beside `error` and `message`: one of the doctor's +`store.connection.` words, decided by the one classifier both use +([`layerfs-persistence` `ConnectionStep`](../../../../engine/crates/layerfs-persistence/src/diagnostic/step.rs)). +`configuration` is the address, its options or the saved login before any +dial; `transport` no server answered (the driver makes DNS, TCP and TLS as +one step, so a TLS failure is `transport` too); `authentication` a login +the server refused; `database` a database it does not have; `schema` no +Store schema, or a role that may not use it or lacks a privilege a +Sandbox needs; `identity` a schema holding another Store's id. + +`--dry-run` makes the same checks and saves and records nothing (no +record, password or reach), and no check refuses it. It answers `{ ok, +outcome: "tested", store, url, here, machines }`: `here` this computer's +check, `{ ok: true, latency_ms, server_version }` or `{ ok: false, step, +code, message }` (`code` the refusal's public code); `machines` one such row per attached machine with its +`machine` (each checked for any change, the setting alone included), or, +when this computer's check failed, each with `ok: null` and no dial; `ok` +whether every check passed. A first connect's dry run checks from this +computer only and makes no schema: an empty database answers +`here.empty: true`. The password comes from stdin as usual; a connected +Store's saved one is used when none is given. Input refusals (`InvalidInput`, +`Exists`) refuse a dry run as they do a connect. | Refusal | When | | --- | --- | | `InvalidInput` | a URL that is not PostgreSQL, names a user or holds a password, holds an `@` or `#`, or that the PostgreSQL client does not read; a bad `--synchronous-commit`; `--user` or the password missing on a first connect; a connected Store whose record names no user or whose password this home does not hold, when none is given | | `Exists` | a sqlite Store of that name, or another Store of this home with that database's id | -| `Unavailable` | no session (no database, a refused login, no server); a connected Store's new address that holds another Store | -| `Conflict` | the Store was disconnected or connected to another database meanwhile | +| `Unavailable` | no server answered, the server refused the login or the database, or the address holds another Store; `step` says which | +| `Conflict` | an attached machine does not reach a new address or login (`machines`); the Store was disconnected or connected to another database meanwhile | Run on macOS native against a local `postgres:17`, with a debug build: @@ -381,15 +415,16 @@ lease, or a call in this process is running on it; Let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first. ```text -CLI layerfs store attach --machine M -Node await layerfs.store.attach(store, { machine }) -Python layerfs.store.attach(store, *, machine) +CLI layerfs store attach --machine M [--dry-run] +Node await layerfs.store.attach(store, { machine, dry_run }) +Python layerfs.store.attach(store, *, machine, dry_run=None) ``` | Argument | Kind | Rule | | --- | --- | --- | | `store` | name | a PostgreSQL Store | | `machine` option | name | the machine; required | +| `dry_run` option | bool | check from the machine as attach does, and record nothing | | Answer | Keys | | --- | --- | @@ -417,6 +452,16 @@ a loopback URL is allowed (it shares this computer's loopback on macOS and Linux); its reach is its own, apart from this computer's. `store connect` attaches nothing. +A refused check names the `machine` and the connection `step` it stopped at +(as `store connect`'s do), flat beside `error` and `message`; a loopback +address the machine does not share is refused `Unsupported` at +`configuration`, before any dial, and a machine whose worker was not reached +names no step. `--dry-run` makes the same checks (the Store, the machine's +platform, the check from the machine) and records nothing: neither +`attached` nor the reach. It answers `outcome: tested` or the refusal attach +would give, and takes no lock, so dry runs of several machines of one Store +may run at once (the UI's per-machine Test). + | Refusal | When | | --- | --- | | `InvalidInput` | a sqlite Store (`store move` moves one to a machine) | diff --git a/docs/architecture/control/machines/workers-and-reach.md b/docs/architecture/control/machines/workers-and-reach.md index 903797da1e..fd4934d4b8 100644 --- a/docs/architecture/control/machines/workers-and-reach.md +++ b/docs/architecture/control/machines/workers-and-reach.md @@ -200,7 +200,7 @@ waits at most 10 s; other operations wait as long as they run | `store.call` | one Store method on `store//store.sqlite` under the root, holding the Store's lease there | | `store.compact` | one sqlite Store's compaction on `store//store.sqlite` under the root, holding the Store's lease there; `{ store, store_record }`, each phase sent as a `progress` event; an event that cannot be written does not end the run (spec S6, #42 D5) | | `store.file` | one step of a `store.move` (either direction), `store.remove`, stat or backup, with `progress` events for hashing steps | -| `store.reach` | the check of this machine's connection to a PostgreSQL Store with the address and login the host saved, for `store.attach` | +| `store.reach` | the check of this machine's connection to a PostgreSQL Store with the address and login the host saved (or a new one `store.connect` checks before saving it), for `store.attach`, `store.connect` and `store.doctor`; a refusal names its connection `step` | | `store.diagnose`, `doctor.sandbox` | doctor's read-only observations | | `network.inspect` | doctor's read-only observation of the machine's Sandbox network for `machine.network`: `{ table, forwarding, links: [{ link, addresses, sandbox }] }`, `sandbox` the recorded Sandbox the link is named for, or null | | `sandbox.host` | a Sandbox or Workspace host operation on the machine's own `native`, decoded into its typed request first; a `sandbox.create` sweeps the run root first ([Checks: leftovers](../doctor/checks.md#leftovers)) | diff --git a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md index 1c96244b25..13ef83f84e 100644 --- a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md +++ b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md @@ -113,9 +113,9 @@ both; no machine has an address or a login of its own. | Call | Does | Refusals | Source | | --- | --- | --- | --- | -| `store.connect` | records the database as a Store in the fixed `layerfs` schema: the URL exactly as given (an address alone: no user or password), `user`, schema, `synchronous_commit`, binding, a cursor key of this home's own, no machine; the password goes to the home's secrets as kind `login` under the Store's name. On a connected Store it changes the address, user, password or `synchronous_commit`, an omitted user or password keeping the saved one; the result is checked from this process against the same binding before the record and password are written, and the Store's open connections in this process are closed | `InvalidInput`, `Exists`, `Unavailable`, `Denied`, `Conflict` | [`connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `connect` | +| `store.connect` | records the database as a Store in the fixed `layerfs` schema: the URL exactly as given (an address alone: no user or password), `user`, schema, `synchronous_commit`, binding, a cursor key of this home's own, no machine; the password goes to the home's secrets as kind `login` under the Store's name. On a connected Store it changes the address, user, password or `synchronous_commit`, an omitted user or password keeping the saved one; the result is checked from this process against the same binding, and a new address, user or password then from each attached machine (`check_from`; one that fails refuses `Conflict` with `machines` and a detach `fix`), before the record and password are written, and the Store's open connections in this process are closed. `dry_run` makes the checks only and answers `tested` (`here`, `machines`); every refused check names its `step` | `InvalidInput`, `Exists`, `Unavailable`, `Denied`, `Conflict` | [`connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `connect` | | `store.disconnect` | forgets the Store, its saved password and its attachments; its data stays | `InvalidInput` for sqlite (`store remove`); `InUse` while leased or a Sandbox uses it | same | -| `store.attach --machine ` | checks the Store from the machine with the saved URL and login (in this process on a locally executing machine, else through the worker's `store.reach`): the server answers, its schema holds this Store, and the role has what a Sandbox's reads and writes need (the schema's `USAGE` and `CREATE`, the database's `TEMP`, each table's and sequence's privileges; never what only a compaction needs, which `store compact` checks itself); the machine's platform must run PostgreSQL Sandboxes. Only then is `` added to the record's `attached` list and its reach recorded; an attached machine is checked again (`checked`) | `InvalidInput` (sqlite), `NotFound`, `Unsupported`, `Unavailable`, `Denied`, `Conflict` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `attach`, [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `attach` | +| `store.attach --machine ` | checks the Store from the machine with the saved URL and login (in this process on a locally executing machine, else through the worker's `store.reach`): the server answers, its schema holds this Store, and the role has what a Sandbox's reads and writes need (the schema's `USAGE` and `CREATE`, the database's `TEMP`, each table's and sequence's privileges; never what only a compaction needs, which `store compact` checks itself); the machine's platform must run PostgreSQL Sandboxes. Only then is `` added to the record's `attached` list and its reach recorded; an attached machine is checked again (`checked`). `dry_run` checks, takes no lock and records nothing (`tested`); a refused check names its `step` and `machine` | `InvalidInput` (sqlite), `NotFound`, `Unsupported`, `Unavailable`, `Denied`, `Conflict` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `attach`, [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `attach` | | `store.detach --machine ` | removes `` from `attached` and forgets its reach, under the home lock and the Store's, once no Sandbox of the Store's projects is on it | `InUse` (counted and named, with the removals as `fix`), `NotFound` (not attached), `InvalidInput` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `detach`, [`inventory.rs`](../../../../control/crates/layerfs-control/src/inventory.rs) `store_idle_on` | | Store calls | open the schema in this process with the URL resolved now | — | [`open.rs`](../../../../control/crates/layerfs-store/src/postgresql/open.rs) | | Host read session | one read-only session per process for Sandbox host operations: a create's reach check and a status's head read, on every route; opened with the light check on first read, checked with one empty query before each use (a dead one is replaced, not retried), closed after 60 s unused | — | [`reader.rs`](../../../../control/crates/layerfs-store/src/postgresql/reader.rs) | diff --git a/docs/versioned/2.0.0/calls.md b/docs/versioned/2.0.0/calls.md index 6bd8584610..528ade47a3 100644 --- a/docs/versioned/2.0.0/calls.md +++ b/docs/versioned/2.0.0/calls.md @@ -1563,6 +1563,17 @@ first connect, needs no privilege beyond what a Sandbox's reads and writes need: what only `store compact` needs (`pg_read_all_stats`, `CREATE` on the database) is checked when a compaction starts. +Every refused reach check, from this computer or a machine, names the +connection `step` it stopped at, flat beside `error` and `message`, with the +doctor's words (`configuration`, `transport`, `tls`, `authentication`, +`database`, `schema`, `identity`); one from a machine also names the +`machine`. `store attach --dry-run` makes attach's check and records +nothing (`outcome: "tested"`). `store connect` of a new address, user or +password is checked from each attached machine before anything is saved, +refused `Conflict` (with `machines` and a detach as its fix) when one does +not reach it; `--dry-run` makes the checks and answers `{ ok, outcome: +"tested", store, url, here, machines }`. + See [Stores](machines-and-stores.md#stores). ### `backup` (6) diff --git a/docs/versioned/2.0.0/machines-and-stores.md b/docs/versioned/2.0.0/machines-and-stores.md index 00b214266b..0878c670f8 100644 --- a/docs/versioned/2.0.0/machines-and-stores.md +++ b/docs/versioned/2.0.0/machines-and-stores.md @@ -492,12 +492,21 @@ $ layerfs store doctor shop-pg password or `synchronous_commit`; an omitted user or password keeps the saved one. The result must reach the same Store (its binding) before anything is saved. Attached machines dial the new address and login from - their next connection. + their next connection, so a new address, user or password is checked + from each of them too: one that does not reach it refuses the connect + `Conflict`, nothing saved, naming the machines (`machines`) with + `layerfs store detach --machine ` as the fix. `--dry-run` makes + the same checks and saves nothing, answering `outcome: "tested"` with + `here` (this computer's check) and one row per attached machine. - **`store attach --machine M`** lets machine `M` run Sandboxes of the Store: `M` must exist and its platform run PostgreSQL Sandboxes, and the Store is checked from `M` with the URL and login saved here before `M` is recorded as attached; the check is kept as `M`'s reach. Attaching - again checks again (`outcome: "checked"`). Machine native is attached + again checks again (`outcome: "checked"`); `--dry-run` checks and + records nothing (`outcome: "tested"`). A refused check names the + `machine` and the connection `step` it stopped at (`configuration`, + `transport`, `tls`, `authentication`, `database`, `schema`, `identity`, + the doctor's `store.connection.`). Machine native is attached like any other (`store connect` attaches nothing); its platform decides whether a loopback URL is allowed, and its reach is its own, apart from this computer's. `store detach --machine M` removes it, diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs index bda47617e1..d046959ccc 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/access.rs @@ -114,7 +114,7 @@ pub(crate) fn compaction_missing(session: &Session) -> HistoryResult Result { let connector = Connector::new(&PostgresSelection::new(url, "public")) - .map_err(|_| PostgresStatusError::Unreachable("the URL does not parse".to_owned()))?; + .map_err(|_| crate::backend::postgresql::status::unparsed())?; let mut client = connector.connect_status()?; let failed = |error: postgres::Error| PostgresStatusError::Failed(error.to_string()); let started = Instant::now(); diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs index 593b53db2f..735cba319d 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs @@ -160,16 +160,28 @@ impl Connector { }) } /// One new client for a status read: a refused login or a database that - /// does not exist is `Denied`, anything else `Unreachable`. + /// does not exist is `Denied`, anything else `Unreachable`, each with + /// the step the doctor's connection check gives it. An error the server + /// sent is said in the server's words (the driver's own text says only + /// `db error`). pub(crate) fn connect_status(&self) -> Result { + use crate::diagnostic::ConnectionStep; self.connect_raw().map_err(|dial| match dial { - Dial::Driver(error) => match error.code() { - Some(code) if code.code().starts_with("28") || code.code() == "3D000" => { - PostgresStatusError::Denied(error.to_string()) + Dial::Driver(error) => { + let why = match error.as_db_error() { + Some(db) => db.message().to_owned(), + None => error.to_string(), + }; + match ConnectionStep::of_refused_connection(error.code().map(|c| c.code())) { + ConnectionStep::Transport => { + PostgresStatusError::Unreachable(ConnectionStep::Transport, why) + } + step => PostgresStatusError::Denied(step, why), } - _ => PostgresStatusError::Unreachable(error.to_string()), - }, - Dial::Silent(_) => PostgresStatusError::Unreachable(dial.to_string()), + } + Dial::Silent(_) => { + PostgresStatusError::Unreachable(ConnectionStep::Transport, dial.to_string()) + } }) } } diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs index b23eda01c4..ab78ab7b8d 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/status.rs @@ -7,6 +7,7 @@ //! `gc_intent` — for `store.status` (T10.5): one query, with no Store open, //! schema change, artifact read or scratch-schema read. use crate::backend::postgresql::session::connection::Connector; +use crate::diagnostic::ConnectionStep; use crate::report::{CompactStatus, POSTGRES_COMPACT_PHASES}; use crate::PostgresSelection; use std::time::{Duration, Instant}; @@ -23,27 +24,49 @@ pub struct PostgresStatus { pub schemas: Vec<(String, Option)>, } -/// Why a status read did not complete. +/// Why a status read did not complete, with the connection step it +/// stopped at ([`ConnectionStep`]). #[derive(Debug)] pub enum PostgresStatusError { - /// The server was not reached, or the connection failed before a query. - Unreachable(String), - /// The server refused the credentials or the database. - Denied(String), + /// The server was not reached (`Transport`), or the address could not + /// be dialled (`Configuration`). + Unreachable(ConnectionStep, String), + /// The server refused the login (`Authentication`) or the database + /// (`Database`). + Denied(ConnectionStep, String), /// A query failed after the connection was made. Failed(String), } +impl PostgresStatusError { + /// The step it stopped at. A query after the connection was made is + /// the schema's: the first read a doctor makes once it is connected. + pub fn step(&self) -> ConnectionStep { + match self { + Self::Unreachable(step, _) | Self::Denied(step, _) => *step, + Self::Failed(_) => ConnectionStep::Schema, + } + } +} + impl std::fmt::Display for PostgresStatusError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Unreachable(why) => write!(f, "PostgreSQL server unreachable: {why}"), - Self::Denied(why) => write!(f, "PostgreSQL server refused the connection: {why}"), + Self::Unreachable(_, why) => write!(f, "PostgreSQL server unreachable: {why}"), + Self::Denied(_, why) => write!(f, "PostgreSQL server refused the connection: {why}"), Self::Failed(why) => write!(f, "PostgreSQL status query failed: {why}"), } } } +/// The refusal of an address the connector cannot read. +pub(crate) fn unparsed() -> PostgresStatusError { + PostgresStatusError::Unreachable( + ConnectionStep::Configuration, + "the URL does not parse".to_owned(), + ) +} + const SIZES: &str = "SELECT s.name, CASE WHEN n.oid IS NULL THEN NULL ELSE \ COALESCE(sum(pg_total_relation_size(c.oid)), 0)::bigint END \ FROM unnest($1::text[]) AS s(name) \ @@ -53,8 +76,8 @@ const SIZES: &str = "SELECT s.name, CASE WHEN n.oid IS NULL THEN NULL ELSE \ /// Reads the status of the server at `url` and the sizes of `schemas`. pub fn status(url: &str, schemas: &[String]) -> Result { - let connector = Connector::new(&PostgresSelection::new(url, "public")) - .map_err(|_| PostgresStatusError::Unreachable("the URL does not parse".to_owned()))?; + let connector = + Connector::new(&PostgresSelection::new(url, "public")).map_err(|_| unparsed())?; let mut client = connector.connect_status()?; let failed = |error: postgres::Error| PostgresStatusError::Failed(error.to_string()); let started = Instant::now(); @@ -185,8 +208,7 @@ pub fn compact_status( url: &str, schema: &str, ) -> Result, PostgresStatusError> { - let connector = Connector::new(&PostgresSelection::new(url, schema)) - .map_err(|_| PostgresStatusError::Unreachable("the URL does not parse".to_owned()))?; + let connector = Connector::new(&PostgresSelection::new(url, schema)).map_err(|_| unparsed())?; let mut client = connector.connect_status()?; let table = quote_ident(schema); let sql = format!( diff --git a/engine/crates/layerfs-persistence/src/diagnostic/mod.rs b/engine/crates/layerfs-persistence/src/diagnostic/mod.rs index 06ef432f0e..a7d7cb6d97 100644 --- a/engine/crates/layerfs-persistence/src/diagnostic/mod.rs +++ b/engine/crates/layerfs-persistence/src/diagnostic/mod.rs @@ -15,7 +15,9 @@ mod scan; mod scratch; mod sqlite; mod sqlite_structure; +mod step; pub use sqlite_structure::sqlite_structure; +pub use step::ConnectionStep; mod transaction; pub use postgresql::connection as postgresql_connection; pub(crate) use postgresql::with_cancellation; diff --git a/engine/crates/layerfs-persistence/src/diagnostic/postgresql.rs b/engine/crates/layerfs-persistence/src/diagnostic/postgresql.rs index ff1b2600fc..3b525b807e 100644 --- a/engine/crates/layerfs-persistence/src/diagnostic/postgresql.rs +++ b/engine/crates/layerfs-persistence/src/diagnostic/postgresql.rs @@ -1,5 +1,5 @@ //! PostgreSQL connection, coherent logical audit and supported online checks. -use super::{emit, scan, Observation, Options, Outcome}; +use super::{emit, scan, ConnectionStep, Observation, Options, Outcome}; use crate::{ backend::{ postgresql::session::driver::Driver, @@ -46,21 +46,20 @@ pub fn connection( { emit( observer, - "store.connection.configuration", + ConnectionStep::Configuration.id(), Outcome::Unknown, *reason, ); return Ok(()); } - let code = error.code().map(|c| c.code()).unwrap_or("unavailable"); - let (id, outcome) = if code.starts_with("28") { - ("store.connection.authentication", Outcome::Fail) - } else if code == "3D000" { - ("store.connection.database", Outcome::Fail) - } else { - ("store.connection.transport", Outcome::Unknown) + let code = error.code().map(|c| c.code()); + let step = ConnectionStep::of_refused_connection(code); + let outcome = match step { + ConnectionStep::Transport => Outcome::Unknown, + _ => Outcome::Fail, }; - emit(observer,id,outcome,format!("PostgreSQL connection not established; SQLSTATE {code}; credentials and driver error text omitted")); + let code = code.unwrap_or("unavailable"); + emit(observer,step.id(),outcome,format!("PostgreSQL connection not established; SQLSTATE {code}; credentials and driver error text omitted")); return Ok(()); } }; diff --git a/engine/crates/layerfs-persistence/src/diagnostic/step.rs b/engine/crates/layerfs-persistence/src/diagnostic/step.rs new file mode 100644 index 0000000000..a10cc47b83 --- /dev/null +++ b/engine/crates/layerfs-persistence/src/diagnostic/step.rs @@ -0,0 +1,66 @@ +//! The steps of a PostgreSQL connection, as the Store doctor records them +//! (`store.connection.`) and a reach refusal names them (`step`). +//! The one place that decides which step a connection the server or the +//! network refused stopped at: the doctor's connection check and every +//! status or reach check's connect both ask it. + +/// One step of a PostgreSQL connection. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ConnectionStep { + /// The address, its options or the saved login, before any dial. + Configuration, + /// Name resolution and the socket: no server answered. + Transport, + /// The TLS the address asks for. + Tls, + /// The server refused the login. + Authentication, + /// The server has no such database. + Database, + /// The Store's schema and the role's privileges in it. + Schema, + /// The Store's id in the schema. + Identity, +} + +impl ConnectionStep { + /// Its word: `configuration`, `transport`, `tls`, `authentication`, + /// `database`, `schema` or `identity`. + pub fn name(self) -> &'static str { + match self { + Self::Configuration => "configuration", + Self::Transport => "transport", + Self::Tls => "tls", + Self::Authentication => "authentication", + Self::Database => "database", + Self::Schema => "schema", + Self::Identity => "identity", + } + } + + /// The doctor's observation id for it, `store.connection.`. + pub fn id(self) -> &'static str { + match self { + Self::Configuration => "store.connection.configuration", + Self::Transport => "store.connection.transport", + Self::Tls => "store.connection.tls", + Self::Authentication => "store.connection.authentication", + Self::Database => "store.connection.database", + Self::Schema => "store.connection.schema", + Self::Identity => "store.connection.identity", + } + } + + /// The step a connection that was not made stopped at, by the + /// SQLSTATE the server answered it with (`None`: no server answered): + /// class 28 is the login, `3D000` the database, anything else the + /// transport. The driver makes DNS, TCP and TLS as one step, so a TLS + /// failure is the transport's here. + pub fn of_refused_connection(sqlstate: Option<&str>) -> Self { + match sqlstate { + Some(code) if code.starts_with("28") => Self::Authentication, + Some("3D000") => Self::Database, + _ => Self::Transport, + } + } +} diff --git a/engine/crates/layerfs-persistence/tests/connection_step.rs b/engine/crates/layerfs-persistence/tests/connection_step.rs new file mode 100644 index 0000000000..42d0d4f369 --- /dev/null +++ b/engine/crates/layerfs-persistence/tests/connection_step.rs @@ -0,0 +1,37 @@ +//! The one classifier of a connection that was not made, shared by the +//! Store doctor (`store.connection.`) and every reach refusal +//! (`step`): a login refused is `authentication`, a missing database +//! `database`, no server answer `transport`; a status read's error names +//! the same step, and a URL it cannot read is `configuration`. +use layerfs_persistence::diagnostic::ConnectionStep; + +#[test] +fn a_refused_connection_names_the_doctor_s_step() { + let of = ConnectionStep::of_refused_connection; + assert_eq!(of(Some("28P01")), ConnectionStep::Authentication); + assert_eq!(of(Some("28000")), ConnectionStep::Authentication); + assert_eq!(of(Some("3D000")), ConnectionStep::Database); + assert_eq!(of(Some("57P03")), ConnectionStep::Transport); + assert_eq!(of(None), ConnectionStep::Transport); + for (step, word) in [ + (ConnectionStep::Configuration, "configuration"), + (ConnectionStep::Transport, "transport"), + (ConnectionStep::Tls, "tls"), + (ConnectionStep::Authentication, "authentication"), + (ConnectionStep::Database, "database"), + (ConnectionStep::Schema, "schema"), + (ConnectionStep::Identity, "identity"), + ] { + assert_eq!(step.name(), word); + assert_eq!(step.id(), format!("store.connection.{word}")); + } +} + +#[test] +fn a_status_read_names_its_step() { + let unread = layerfs_persistence::postgresql_access("not a url", "layerfs").unwrap_err(); + assert_eq!(unread.step(), ConnectionStep::Configuration, "{unread}"); + let nowhere = "postgres://lfs@127.0.0.1:1/db?sslmode=disable&connect_timeout=5"; + let unreached = layerfs_persistence::postgresql_access(nowhere, "layerfs").unwrap_err(); + assert_eq!(unreached.step(), ConnectionStep::Transport, "{unreached}"); +}