diff --git a/CHANGELOG.md b/CHANGELOG.md index ac3da9a5..5197dce4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ and listed with their assets on the [GitHub Desktop] · Manage programs…", the Git clients checked in the path menu's programs. Paste a repository's `https://` address instead of a folder, and its clone dialog opens with it filled in; then paste the - folder it was cloned to. New: `POST /hub/clone`. + folder it was cloned to. New: `POST /hub/clone`; an address with a query + or fragment, also percent-encoded, is refused. ### Changed @@ -24,8 +25,8 @@ and listed with their assets on the pages, such as the .NET runtime's, no longer count again with every process of a tree: Linux takes the proportional set (`Pss`) instead of the resident set, and a cgroup's `memory.current` without the file cache the - kernel may drop; Windows the private working set; macOS the physical - footprint. The numbers in the dashboard, `devstack top` and a lane's + kernel may drop; Windows the private working set (the whole one on a + Windows before 10 21H2, which lacks it); macOS the physical footprint. The numbers in the dashboard, `devstack top` and a lane's need for the pool are lower, for a .NET stack by about a third. - **The dashboard names the builds' memory** (ADR-0119). The lane card says "of it builds …", and the overview lists *Builds* below the groups: the @@ -34,21 +35,27 @@ and listed with their assets on the - **A lane's need for the pool names its builds** (ADR-0119). The lease step says "… memory (of it builds …)" and `remote_lane_need` in `daemon.log` logs `builds`: the most the lane's build job took, as its - daemon measured it (a node asks each lane's daemon). Placement still takes + daemon measured it (a node asks each lane's daemon and reads at most + 1 MiB of its answer). Placement still takes the whole memory; a node before this release sends no part. - **main is stopped when only what serves its lanes runs** (ADR-0119). A - `singleton` the stop of main keeps for running lanes no longer shows main - as running with a Stop button; the stop says what keeps running, and for - which lanes. + `singleton` the stop of main keeps for running lanes, and what it comes + `after`, no longer shows main as running with a Stop button; the stop says + what keeps running, and for which lanes. A service's view says + `kept_for_lanes`. - **`prepare` runs in the main tree too** (#630). Before a service starts there (`up`, `start`, `restart`), its `prepare` runs in place when the files of its `inputs` changed since it last ran there, or a directory of its `outputs` is gone; the first start after this release runs it once. A merge that brought new packages no longer leaves the dev server on the old `node_modules`. The running instance is stopped first, so `npm ci` - can replace the files Windows keeps locked. A failing `prepare` stops the - start with its tail. While a service runs, here or in a lane, a change to - its `inputs` is a notice naming `devstack restart`; `restart_on` with the + can replace the files Windows keeps locked, and so are other running + services with the same `outputs` (they start again after it); a start + that would prepare under such a service is refused and says so. A failing + `prepare` stops the start with its tail. A `prepare` that rewrites its own + inputs (`npm install` and the lockfile) is not due again. While a service + runs, here or in a lane, a change to its `inputs` is a notice naming + `devstack restart` (gone when it stops); `restart_on` with the lockfile makes it happen on every change. The main tree still does not use the store (ADR-0062, amendment 2026-11-26). diff --git a/crates/devstack-daemon/src/state.rs b/crates/devstack-daemon/src/state.rs index 4204aee2..14fa27a4 100644 --- a/crates/devstack-daemon/src/state.rs +++ b/crates/devstack-daemon/src/state.rs @@ -101,6 +101,9 @@ pub struct ServiceView { /// = true`, or the deprecated `lanes = false`, ADR-0080): the stack /// page lists it as the stack's, not a lane's. Older daemons omit it. pub singleton: bool, + /// The main tree's stop keeps it while lanes run: a `singleton`, or a + /// service one comes `after` (`supervisor::kept_for_lanes`). + pub kept_for_lanes: bool, /// Where its last `prepare` outputs came from (ADR-0062): the store or /// a run. Since this daemon started; none before its first `prepare`. #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/devstack-daemon/src/supervisor/copy.rs b/crates/devstack-daemon/src/supervisor/copy.rs index 22e5a271..bd2ee619 100644 --- a/crates/devstack-daemon/src/supervisor/copy.rs +++ b/crates/devstack-daemon/src/supervisor/copy.rs @@ -505,30 +505,86 @@ impl Supervisor { svc: &Service, cancel: &dyn Fn() -> bool, ) -> Result<(), String> { - if let Some(job) = self.tree_prepare_job(name, svc)? - && let Some(view) = self.run_prepare(name, job, cancel)? - { - self.set_prepare(name, view); + if let Some(job) = self.tree_prepare_job(name, svc)? { + // What another running service reads is not replaced under it. + let sharers = self.sharers(name, svc); + if !sharers.is_empty() { + return Err(format!( + "`prepare` of {name} would replace what {} runs on (the same `outputs`): `devstack restart {name}` stops {} first, or stop {} and start {name} again", + sharers.join(", "), + if sharers.len() == 1 { "it" } else { "them" }, + sharers.join(", "), + )); + } + let (mark, shared) = ( + job.mark.clone(), + job.shared.as_ref().map(|s| s.mark.clone()), + ); + if let Some(view) = self.run_prepare(name, job, cancel)? { + self.set_prepare(name, view); + } + // The inputs as `prepare` left them (`npm install` rewrites the + // lockfile): otherwise its own write makes it due again. + if let Some(key) = self.tree_key(svc)? { + for m in std::iter::once(mark).chain(shared) { + std::fs::write(&m, &key).map_err(|e| e.to_string())?; + } + } } self.clear_notice(&format!("prepare.inputs.{name}")); Ok(()) } + /// The key of `svc`'s `prepare` over the inputs as they are in the tree + /// (the main tree, or a lane's worktree); `None` without `prepare`. + fn tree_key(&self, svc: &Service) -> Result, String> { + let Some(p) = &svc.prepare else { + return Ok(None); + }; + let files = self + .snapshot + .lock() + .unwrap() + .list() + .map_err(|e| e.to_string())?; + let inputs = devstack_build::watch_set(&p.inputs).map_err(|e| e.to_string())?; + let hashed: Vec<(String, String)> = files + .into_iter() + .filter(|rel| inputs.as_ref().is_some_and(|g| g.is_match(rel))) + .filter_map(|rel| { + let bytes = std::fs::read(self.repo.join(&rel)).ok()?; + Some((rel, blake3::hash(&bytes).to_hex().to_string())) + }) + .collect(); + prepare_key(p, svc, hashed.iter().map(|(r, h)| (r.as_str(), h.clone()))).map(Some) + } + + /// Where the key of `name`'s last `prepare` is kept: in the main tree's + /// state, or in the lane's copy. + fn prepare_mark(&self, name: &str) -> PathBuf { + if self.runs_from_copy() { + self.layout.lane("main").join("prepared").join(name) + } else { + self.state_dir.join("prepared-tree").join(name) + } + } + /// `rel`, a file of the `inputs` of `name`'s `prepare`, changed: while it /// runs, it runs on what `prepare` made before, until its next start - /// prepares again (#630). Said, unless its `restart_on` restarts it. - pub fn prepare_inputs_changed(&self, name: &str, rel: &str) { + /// prepares again (#630). Said, unless its `restart_on` restarts it + /// (`restarts`, as the watcher matched it). + pub fn prepare_inputs_changed(&self, name: &str, rel: &str, restarts: bool) { + let running = self.slots.lock().unwrap().get(name).is_some_and(from_tree); + if !running || restarts { + return; + } + // Its own `prepare` wrote it, or it came back to what was prepared. let Some(svc) = self.stack().services.get(name).cloned() else { return; }; - let running = self.slots.lock().unwrap().get(name).is_some_and(from_tree); - let restarts = devstack_build::watch_set(&svc.restart_on) - .ok() - .flatten() - .is_some_and(|g| { - g.is_match(rel) || rel.match_indices('/').any(|(i, _)| g.is_match(&rel[..i])) - }); - if !running || restarts { + if let Ok(Some(key)) = self.tree_key(&svc) + && std::fs::read_to_string(self.prepare_mark(name)).is_ok_and(|k| k == key) + { return; } self.set_notice( @@ -540,6 +596,33 @@ impl Supervisor { ); } + /// The other services that run from the tree and whose `prepare` makes + /// some of the same `outputs` as `svc`'s. + pub(super) fn sharers(&self, name: &str, svc: &Service) -> Vec { + let norm = |o: &String| o.replace('\\', "/").trim_matches('/').to_string(); + let Some(mine) = svc + .prepare + .as_ref() + .map(|p| p.outputs.iter().map(norm).collect::>()) + else { + return Vec::new(); + }; + let stack = self.stack(); + let slots = self.slots.lock().unwrap(); + stack + .services + .iter() + .filter(|(n, _)| n.as_str() != name) + .filter(|(_, s)| { + s.prepare + .as_ref() + .is_some_and(|p| p.outputs.iter().map(norm).any(|o| mine.contains(&o))) + }) + .filter(|(n, _)| slots.get(n.as_str()).is_some_and(from_tree)) + .map(|(n, _)| n.clone()) + .collect() + } + /// The `prepare` of `svc` the main tree needs before it starts there; /// `None` when it has none, or it ran for these inputs and its outputs /// are there. @@ -548,25 +631,9 @@ impl Supervisor { name: &str, svc: &Service, ) -> Result, String> { - let Some(p) = &svc.prepare else { + let (Some(p), Some(key)) = (&svc.prepare, self.tree_key(svc)?) else { return Ok(None); }; - let files = self - .snapshot - .lock() - .unwrap() - .list() - .map_err(|e| e.to_string())?; - let inputs = devstack_build::watch_set(&p.inputs).map_err(|e| e.to_string())?; - let hashed: Vec<(String, String)> = files - .into_iter() - .filter(|rel| inputs.as_ref().is_some_and(|g| g.is_match(rel))) - .filter_map(|rel| { - let bytes = std::fs::read(self.repo.join(&rel)).ok()?; - Some((rel, blake3::hash(&bytes).to_hex().to_string())) - }) - .collect(); - let key = prepare_key(p, svc, hashed.iter().map(|(r, h)| (r.as_str(), h.clone())))?; let marks = self.state_dir.join("prepared-tree"); let mark = marks.join(name); let outputs: Vec = p.outputs.iter().map(|o| self.repo.join(o)).collect(); @@ -2021,6 +2088,71 @@ mod tests { assert_eq!(lock(), "{\"v\":2}"); } + // Review before 0.54.0, Nr. 5: a `prepare` that rewrites one of its own + // inputs (`npm install` normalises the lockfile) is not due again, and + // its own write is no change to tell about. + #[cfg(windows)] + #[test] + fn a_prepare_that_rewrites_its_inputs_is_not_due_again() { + use crate::state::Status; + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let d = tempfile::tempdir().unwrap(); + let stack = "version = 1\n[stack]\nname = \"t\"\n[services.web]\nkind = \"devserver\"\nrun = \"x\"\nport = 4200\nprepare = { run = \"mkdir deps 2>nul & echo normalised> package-lock.json\", inputs = [\"package-lock.json\"], outputs = [\"deps\"] }\n"; + let sup = warm_repo(d.path(), stack, &[("package-lock.json", "{}")], &rt); + let svc = sup.stack().services["web"].clone(); + sup.tree_ready("web", &svc, &|| false).unwrap(); + assert!( + sup.tree_prepare_job("web", &svc).unwrap().is_none(), + "due again after its own write" + ); + sup.set_status("web", Status::Starting); + sup.prepare_inputs_changed("web", "package-lock.json", false); + assert!(sup.notices().is_empty(), "{:?}", sup.notices()); + // A change of somebody else's is one. + std::fs::write(d.path().join("package-lock.json"), "{\"v\":2}").unwrap(); + sup.prepare_inputs_changed("web", "package-lock.json", false); + assert_eq!(sup.notices().len(), 1); + // Gone with the service (Nr. 6). + sup.stop("web").unwrap(); + assert!(sup.notices().is_empty(), "{:?}", sup.notices()); + } + + // Review before 0.54.0, Nr. 2: outputs another running service shares + // are not prepared under it (Windows keeps its files locked; elsewhere + // they vanish under it). + #[cfg(windows)] + #[test] + fn outputs_a_running_service_shares_are_not_prepared_under_it() { + use crate::state::Status; + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let d = tempfile::tempdir().unwrap(); + let prep = "prepare = { run = \"mkdir deps 2>nul & copy /y package-lock.json deps\\\\lock.json\", inputs = [\"package-lock.json\"], outputs = [\"deps\"] }"; + let stack = format!( + "version = 1\n[stack]\nname = \"t\"\n[services.web]\nkind = \"devserver\"\nrun = \"x\"\nport = 4200\n{prep}\n[services.admin]\nkind = \"devserver\"\nrun = \"x\"\nport = 4201\n{prep}\n" + ); + let sup = warm_repo(d.path(), &stack, &[("package-lock.json", "{\"v\":1}")], &rt); + let services = sup.stack().services.clone(); + sup.tree_ready("web", &services["web"], &|| false).unwrap(); + sup.set_status("admin", Status::Starting); + std::fs::write(d.path().join("package-lock.json"), "{\"v\":2}").unwrap(); + let e = sup + .tree_ready("web", &services["web"], &|| false) + .unwrap_err(); + assert!(e.contains("admin"), "{e}"); + assert_eq!( + sup.sharers("web", &services["web"]), + vec!["admin".to_string()] + ); + sup.set_status("admin", Status::Stopped); + sup.tree_ready("web", &services["web"], &|| false).unwrap(); + } + // #630: a `prepare` that fails in the main tree stops the start with its // tail, and the next start tries again. #[cfg(windows)] diff --git a/crates/devstack-daemon/src/supervisor/lifecycle.rs b/crates/devstack-daemon/src/supervisor/lifecycle.rs index 4d23d7eb..7cb9e08c 100644 --- a/crates/devstack-daemon/src/supervisor/lifecycle.rs +++ b/crates/devstack-daemon/src/supervisor/lifecycle.rs @@ -98,6 +98,40 @@ pub(super) fn run_stop( } } +/// What the main tree's stop keeps while lanes run (ADR-0080, ADR-0119): the +/// `singleton` services and every service and Compose container one of them +/// comes `after`, transitively. The view marks the services +/// (`kept_for_lanes`), so the dashboard counts the same ones as the daemon. +pub(crate) fn kept_for_lanes( + stack: &devstack_config::Stack, +) -> (BTreeSet, BTreeSet<(String, String)>) { + let mut keep: BTreeSet = stack + .services + .iter() + .filter(|(_, s)| s.singleton()) + .map(|(n, _)| n.clone()) + .collect(); + let mut containers: BTreeSet<(String, String)> = BTreeSet::new(); + let mut todo: Vec = keep.iter().cloned().collect(); + while let Some(n) = todo.pop() { + for dep in stack + .services + .get(&n) + .map(|s| s.after.clone()) + .unwrap_or_default() + { + if let Some(rest) = dep.strip_prefix("compose.") + && let Some((g, s)) = rest.split_once('.') + { + containers.insert((g.to_string(), s.to_string())); + } else if stack.services.contains_key(&dep) && keep.insert(dep.clone()) { + todo.push(dep); + } + } + } + (keep, containers) +} + impl Supervisor { /// Infra, then every autostart service for this platform, in order; a /// service that fails holds back only what comes `after` it. @@ -334,32 +368,7 @@ impl Supervisor { infra: bool, local_lanes: bool, ) -> (Vec, Vec, Vec) { - let mut keep: BTreeSet = self - .stack() - .services - .iter() - .filter(|(_, s)| s.singleton()) - .map(|(n, _)| n.clone()) - .collect(); - let mut containers: BTreeSet<(String, String)> = BTreeSet::new(); - let mut todo: Vec = keep.iter().cloned().collect(); - while let Some(n) = todo.pop() { - for dep in self - .stack() - .services - .get(&n) - .map(|s| s.after.clone()) - .unwrap_or_default() - { - if let Some(rest) = dep.strip_prefix("compose.") - && let Some((g, s)) = rest.split_once('.') - { - containers.insert((g.to_string(), s.to_string())); - } else if self.stack().services.contains_key(&dep) && keep.insert(dep.clone()) { - todo.push(dep); - } - } - } + let (keep, containers) = kept_for_lanes(&self.stack()); let mut failed = self.down_keeping(false, &keep); let mut kept = Vec::new(); if infra && self.external_infra().is_none() { @@ -1356,6 +1365,8 @@ impl Supervisor { self.end(&mut i, Some(Duration::from_secs(20))); } self.set_status(name, Status::Stopped); + // Nothing runs on what `prepare` made before any more. + self.clear_notice(&format!("prepare.inputs.{name}")); Ok(()) } @@ -1615,6 +1626,23 @@ fn port_freed(port: u16) -> bool { true } +#[cfg(test)] +mod kept_tests { + // Code review before 0.54.0, Nr. 1: what a singleton comes after is kept + // for the lanes too, and the view says so for each service. + #[test] + fn what_a_singleton_comes_after_is_kept_for_the_lanes() { + let text = "version = 1\n[stack]\nname = \"t\"\n[compose.app]\nproject = \"t\"\nfiles = [\"c.yml\"]\nservices = [\"db\"]\n[services.tray]\nsingleton = true\nrun = \"x\"\nafter = [\"auth\"]\n[services.auth]\nrun = \"x\"\nafter = [\"compose.app.db\"]\n[services.api]\nrun = \"x\"\n"; + let stack = devstack_config::from_str(text, std::path::Path::new("t")).unwrap(); + let (kept, containers) = super::kept_for_lanes(&stack); + assert_eq!(kept.into_iter().collect::>(), ["auth", "tray"]); + assert_eq!( + containers.into_iter().collect::>(), + [("app".to_string(), "db".to_string())] + ); + } +} + #[cfg(all(test, windows))] mod tests { use super::*; diff --git a/crates/devstack-daemon/src/supervisor/mod.rs b/crates/devstack-daemon/src/supervisor/mod.rs index 556377dd..ff29fca0 100644 --- a/crates/devstack-daemon/src/supervisor/mod.rs +++ b/crates/devstack-daemon/src/supervisor/mod.rs @@ -442,6 +442,7 @@ impl Supervisor { .map(|(k, _)| k.clone()) .collect() }; + let (kept, _) = lifecycle::kept_for_lanes(&stack); let mut slots = BTreeMap::new(); let mut op_locks = BTreeMap::new(); let mut reruns = BTreeMap::new(); @@ -471,6 +472,7 @@ impl Supervisor { hot_reload: false, hot_reload_available: svc.hot_reload.is_some(), singleton: svc.singleton(), + kept_for_lanes: kept.contains(name), prepare: None, last_action: None, public_link: None, @@ -709,9 +711,11 @@ impl Supervisor { // A profile changes how services run, never which there are: the // slots stay, what they show of the stack file follows. { + let (kept, _) = lifecycle::kept_for_lanes(&stack); let mut slots = self.slots.lock().unwrap(); for (name, svc) in &stack.services { if let Some(slot) = slots.get_mut(name) { + slot.view.kept_for_lanes = kept.contains(name); slot.view.kind = format!("{:?}", svc.kind).to_lowercase(); slot.view.autostart = svc.autostart; slot.view.hot_reload_available = svc.hot_reload.is_some(); diff --git a/crates/devstack-daemon/src/supervisor/replace.rs b/crates/devstack-daemon/src/supervisor/replace.rs index 6f02fe7c..79982a10 100644 --- a/crates/devstack-daemon/src/supervisor/replace.rs +++ b/crates/devstack-daemon/src/supervisor/replace.rs @@ -95,15 +95,41 @@ The running instance was left as it was." // what `prepare` replaces (Windows locks open files), so it stops // first instead of serving until a candidate took over. let prepares_in_place = artifact.is_none() + && svc.prepare.is_some() && !self.runs_from_copy() - && self.tree_prepare_job(name, &svc)?.is_some(); - if svc.proxied() && running && !prepares_in_place { - self.replace(name, &svc, artifact)?; + && match self.tree_prepare_job(name, &svc) { + Ok(job) => job.is_some(), + Err(e) => { + self.restart_failed(name, epoch, &e); + return Err(e); + } + }; + // So do the others that run on the same outputs; they start again + // after it (review before 0.54.0, Nr. 2). + let sharers = if prepares_in_place { + self.sharers(name, &svc) + } else { + Vec::new() + }; + for s in &sharers { + self.stop(s)?; + } + let restarted = if svc.proxied() && running && !prepares_in_place { + self.replace(name, &svc, artifact) } else { self.set_candidate(name, None); - self.stop(name)?; - self.start_with(name, artifact)?; + self.stop(name) + .and_then(|()| self.start_with(name, artifact)) + }; + for s in &sharers { + if let Err(e) = self.start(s) { + crate::diag::warn( + "prepare_sharer_not_started", + serde_json::json!({ "lane": self.lane, "service": s, "after": name, "error": e }), + ); + } } + restarted?; if svc.kind == Kind::Job && let Some(s) = self.slots.lock().unwrap().get_mut(name) { diff --git a/crates/devstack-daemon/src/watch.rs b/crates/devstack-daemon/src/watch.rs index ab4e6ce3..2477f412 100644 --- a/crates/devstack-daemon/src/watch.rs +++ b/crates/devstack-daemon/src/watch.rs @@ -465,7 +465,9 @@ fn watch(sup: Arc) -> Result { } for (n, g) in &prepared { if g.is_match(&rel) { - me.prepare_inputs_changed(n, &rel); + let restarts = + devservers.iter().any(|(d, r)| d == n && covers(r, &rel)); + me.prepare_inputs_changed(n, &rel, restarts); } } } diff --git a/crates/devstack-hub/src/open.rs b/crates/devstack-hub/src/open.rs index aabab1f7..86bf870e 100644 --- a/crates/devstack-hub/src/open.rs +++ b/crates/devstack-hub/src/open.rs @@ -238,7 +238,11 @@ pub fn clone_url(s: &str) -> Option<&str> { let rest = s.strip_prefix("https://")?; let host = rest.split('/').next()?; let allowed = |c: char| c.is_ascii_alphanumeric() || "-._~/:@%+".contains(c); - (!host.is_empty() && s.len() <= 2048 && rest.chars().all(allowed)).then_some(s) + // Encoded, too: a client that decodes before it parses reads them + // (`%3F`, `%23`, and `%25` for a second round). + let lower = rest.to_ascii_lowercase(); + let encoded = ["%3f", "%23", "%25"].iter().any(|e| lower.contains(e)); + (!host.is_empty() && s.len() <= 2048 && rest.chars().all(allowed) && !encoded).then_some(s) } /// Start the agent `id` in `tree` with `prompt` (written by the hub, never by @@ -457,6 +461,16 @@ mod tests { assert_eq!(clone_url("https://github.com/acme/shop#x"), None); assert_eq!(clone_url("https://github.com/acme/my shop"), None); assert_eq!(clone_url("https://github.com/a\"b"), None); + // Security review before 0.54.0, S2: a query or fragment, encoded. + assert_eq!(clone_url("https://github.com/acme/shop%3Fbranch=x"), None); + assert_eq!(clone_url("https://github.com/acme/shop%3fbranch=x"), None); + assert_eq!(clone_url("https://github.com/acme/shop%23x"), None); + assert_eq!(clone_url("https://github.com/acme/shop%253Fx"), None); + // An encoded space stays (Azure DevOps project names). + assert_eq!( + clone_url("https://dev.azure.com/org/My%20Project/_git/shop"), + Some("https://dev.azure.com/org/My%20Project/_git/shop") + ); } #[test] diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index ecdde033..ee070da2 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -3319,10 +3319,16 @@ async fn shared_tunnel( } } +/// The most of a lane daemon's usage report the node reads: what answers on +/// that port is the lane's, whatever runs in it (security review before +/// 0.54.0, S1). +const USAGE_MAX: usize = 1 << 20; + /// What the lane's build job takes of its memory now, as its daemon /// measures it (`builds` of `/v1/usage`, ADR-0119 point 3): the node sees /// the lane as one container and cannot tell its builds apart. `None` when -/// the daemon does not answer within a few seconds. +/// the daemon does not answer within a few seconds, or says more than +/// [`USAGE_MAX`]. async fn lane_builds(d: &DaemonAddr) -> Option { use http_body_util::BodyExt; let ask = async { @@ -3342,7 +3348,11 @@ async fn lane_builds(d: &DaemonAddr) -> Option { if !res.status().is_success() { return None; } - let body = res.into_body().collect().await.ok()?.to_bytes(); + let body = http_body_util::Limited::new(res.into_body(), USAGE_MAX) + .collect() + .await + .ok()? + .to_bytes(); builds_of(&body) }; tokio::time::timeout(Duration::from_secs(3), ask) @@ -4515,6 +4525,22 @@ mod tests { }; assert_eq!(lane_builds(&gone).await, None); assert_eq!(builds_of(br#"{"services":[]}"#), None); + + // Security review before 0.54.0, S1: what runs in the lane answers + // on its daemon's port; a body beyond the limit is not read whole. + let big = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let big_addr = big.local_addr().unwrap().to_string(); + let padded = format!( + r#"{{"pad":"{}","builds":{{"memory":1}}}}"#, + "x".repeat(USAGE_MAX + 1) + ); + let app = axum::Router::new().route("/v1/usage", get(move || async move { padded })); + tokio::spawn(async move { axum::serve(big, app).await.unwrap() }); + let flood = DaemonAddr { + addr: big_addr, + ..d("t0k") + }; + assert_eq!(lane_builds(&flood).await, None, "a body past the limit"); } #[test] diff --git a/crates/devstack-proc/src/macos.rs b/crates/devstack-proc/src/macos.rs index 68aa3f08..3fb96c4b 100644 --- a/crates/devstack-proc/src/macos.rs +++ b/crates/devstack-proc/src/macos.rs @@ -367,10 +367,12 @@ mod tests { let me = std::process::id(); let (before, footprint) = process_usage(me); assert!(footprint >= 1 << 20, "{footprint}"); - assert_eq!( - phys_footprint(me as i32), - Some(footprint), - "not the resident set" + // Two readings of a live footprint: close, not equal (code review + // before 0.54.0, Nr. 4). + let again = phys_footprint(me as i32).unwrap(); + assert!( + again.abs_diff(footprint) <= (32 << 20).max(footprint / 10), + "not the footprint: {footprint} against {again}" ); let t0 = Instant::now(); let mut x = 0u64; diff --git a/crates/devstack-proc/src/windows.rs b/crates/devstack-proc/src/windows.rs index b67763cb..c06a0303 100644 --- a/crates/devstack-proc/src/windows.rs +++ b/crates/devstack-proc/src/windows.rs @@ -351,7 +351,7 @@ fn working_set(pid: u32) -> u64 { if K32GetProcessMemoryInfo(h, &mut x as *mut _ as *mut PROCESS_MEMORY_COUNTERS, x.cb) != 0 { - x.PrivateWorkingSetSize as u64 + private_or_whole(x.PrivateWorkingSetSize as u64, x.WorkingSetSize as u64) } else { let mut c: PROCESS_MEMORY_COUNTERS = mem::zeroed(); c.cb = mem::size_of::() as u32; @@ -366,6 +366,14 @@ fn working_set(pid: u32) -> u64 { } } +/// The private working set, or the whole one where the call filled only the +/// older fields (a Windows before 10 21H2 takes the larger struct and leaves +/// `PrivateWorkingSetSize` as it was, zero): a running process never has +/// none of its own (code review before 0.54.0, Nr. 3). +fn private_or_whole(private: u64, whole: u64) -> u64 { + if private == 0 { whole } else { private } +} + pub(crate) fn ensure_console() -> Result { // SAFETY: plain Win32 calls. unsafe { @@ -648,6 +656,12 @@ pub(crate) fn cpu_times() -> Option<(u64, u64)> { #[cfg(test)] mod tests { + #[test] + fn a_windows_without_the_private_figure_gives_the_whole_working_set() { + assert_eq!(super::private_or_whole(0, 5_000), 5_000); + assert_eq!(super::private_or_whole(3_000, 5_000), 3_000); + } + #[test] fn a_process_counts_its_private_working_set() { use windows_sys::Win32::System::ProcessStatus::{ diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 642ec670..a94173b9 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -284,6 +284,7 @@ type ServiceView = { // (StackView.public_link_domain: the named tunnel's domain, when one is set up (ADR-0091); // links then answer at https://{service}-{lane}-{stack}., and open once the hub's connector carries them) singleton?: boolean; // it runs once per machine, in the main working tree only (`singleton = true`, or the deprecated `lanes = false`, ADR-0080); the dashboard's stack page lists it (ADR-0081). Since 0.33.0; older daemons omit it + kept_for_lanes?: boolean; // the main tree's stop keeps it while lanes run: a singleton, or a service one comes `after`, transitively (ADR-0119). Since 0.54.0; older daemons omit it prepare?: PrepareView; // where its last `prepare` outputs came from (ADR-0062), since the daemon started; absent before its first `prepare` (and from older daemons) last_action?: { via: Client; at: number; action: string }; // the last `/v1/services//` that succeeded, and its client (ADR-0067), from the journal not_forwarded_here?: string; // a lane on a node: its port is held here by something else, so this machine reaches that instead (#615); why, as the lane says it. Since 0.53.0 diff --git a/docs/stack-file.md b/docs/stack-file.md index d17099d5..576a3742 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -693,7 +693,9 @@ with its tail. The main working tree runs dev servers in place: there `prepare` runs in the tree itself before the service starts (`up`, `start`, `restart`), when the files of `inputs` changed since it last ran there or a directory of `outputs` is gone (#630). A restart then stops the running -instance first, so `npm ci` can replace files it holds open. The main tree +instance first, so `npm ci` can replace files it holds open, and the other +running services whose `prepare` names the same `outputs` (they start again +after it); a plain start that would prepare under one of them is refused. The main tree does not use the store (`outputs` below) and links nothing. While a service runs, here or in a lane, a change to a file of its `inputs` is a notice: it runs on what `prepare` made before until its next start. To have that start diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index bbb31104..3ae2bad8 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -478,6 +478,8 @@ export type ServiceView = { last_action?: Change; /** It runs once per machine, in the main working tree only (`singleton = true`, ADR-0080): the stack's, not a lane's. Older daemons omit it. */ singleton?: boolean; + /** The main tree's stop keeps it while lanes run: a `singleton`, or a service one comes `after`. Older daemons omit it. */ + kept_for_lanes?: boolean; /** Its public link (a Cloudflare Quick Tunnel to its port), while one is open or failed; absent otherwise. */ public_link?: PublicLink; /** A public link may be opened to it (a `port`, no `tunnel = false`). Older daemons omit it. */ diff --git a/ui/src/stores/stack.ts b/ui/src/stores/stack.ts index 7523eec8..518b5346 100644 --- a/ui/src/stores/stack.ts +++ b/ui/src/stores/stack.ts @@ -343,11 +343,13 @@ export const useStack = defineStore('stack', () => { } } /** - * A service that runs only because lanes do: a `singleton` the main tree's - * stop keeps for them (ADR-0080, the daemon's `down` names it in `kept`). + * A service that runs only because lanes do: what the main tree's stop + * keeps for them (ADR-0080, the daemon's `down` names it in `kept`), a + * `singleton` and what one comes `after`, as the daemon marks it; older + * daemons mark the singletons only. */ function keptForLanes(s: ServiceView) { - return !!s.singleton && runningLanes.value.length > 0; + return !!(s.kept_for_lanes ?? s.singleton) && runningLanes.value.length > 0; } /** * Whether the main working tree runs something: its services (not those diff --git a/ui/src/stores/stores.test.ts b/ui/src/stores/stores.test.ts index b1fc10c3..ea8152bf 100644 --- a/ui/src/stores/stores.test.ts +++ b/ui/src/stores/stores.test.ts @@ -580,6 +580,10 @@ describe('stack store', () => { // Another of its services runs: it runs. events.handlers.onMessage({ type: 'snapshot', stack: view([svc('api', 'healthy'), tray]) } as never); expect(stack.mainActive).toBe(true); + // What a singleton comes after is kept too, as the daemon marks it. + const auth = { ...svc('auth', 'healthy'), kept_for_lanes: true }; + events.handlers.onMessage({ type: 'snapshot', stack: view([svc('api', 'stopped'), auth, { ...tray, kept_for_lanes: true }]) } as never); + expect(stack.mainActive).toBe(false); fake.on('/hub/stacks/shop/api/v1/down?infra=true', ok({ lanes: ['feat'], kept: ['tray'], containers: [] })); await stack.laneAction(stack.mainLane!, 'stop'); expect(useUi().toasts.map((t) => t.title)).toContain('main stopped; tray keeps running for lane feat'); diff --git a/ui/src/views/StackPage.vue b/ui/src/views/StackPage.vue index 76a110d0..c8447159 100644 --- a/ui/src/views/StackPage.vue +++ b/ui/src/views/StackPage.vue @@ -80,7 +80,7 @@ const mainState = computed(() => { if (!stack.running || hubDown.value) return null; const profile = stack.mainView?.profile; if (!stack.mainActive) { - const kept = (stack.mainView?.services ?? []).filter((s) => s.singleton && statusBucket(s) !== 'idle').map((s) => s.name); + const kept = (stack.mainView?.services ?? []).filter((s) => (s.kept_for_lanes ?? s.singleton) && statusBucket(s) !== 'idle').map((s) => s.name); return { tone: '', label: 'main stopped',