diff --git a/CHANGELOG.md b/CHANGELOG.md index a1ff69f6..38e15aca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,36 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **Restart, Rebuild, Cold** ([ADR-0072](docs/adr/0072-a-restart-is-warm-a-rebuild-or-cold.md)): + every restart button in the dashboard (a service row, a group's head, a + lane's header) is a split button. A click restarts warm, from the build + there is for the inputs, the data kept; its arrow offers Rebuild (built + again even for inputs built before, the data kept) and, for a lane, + Cold (built again and seeded again; asks first). The command palette has + them too. +- **A lane restarts where it runs**: `POST /v1/lanes/{lane}/restart` with + `{"mode": "warm" | "rebuild" | "cold"}`. On a node a warm restart and a + rebuild go through the lane's own API, so its lease, node and ports + stay; a cold restart stops it, throws its data away and starts it again + at the same place. A group has `rebuild` too + (`POST /v1/groups/{name}/rebuild`, `devstack restart --rebuild `). +- **A lane's actions in one menu**: the header's Restart (Start for a + stopped lane) has Rebuild, Cold…, Stop, Discard data… and Remove + worktree… in its menu; the same menu opens from a lane's "…" button or a + right click on its row in the branch picker. The separate "Stop + worktree" and "Discard data" buttons are gone. + +### Changed + +- **A group's start and stop take its containers along**, as its restart + did: `devstack start|stop ` and the group's buttons start its + containers before its services and stop them after (a lane leaves the + main tree's `shared` ones alone). A group of containers only gets its + buttons in the overview now. A lane on a node needs a node with devstack + 0.28.0 or later for this. + ### Fixed - **A lane on a node keeps its journal** (#287): the requester's take of diff --git a/crates/devstack-daemon/src/api.rs b/crates/devstack-daemon/src/api.rs index 98b8dbd8..ca664f04 100644 --- a/crates/devstack-daemon/src/api.rs +++ b/crates/devstack-daemon/src/api.rs @@ -79,6 +79,7 @@ pub fn router(state: AppState) -> axum::Router { .route("/v1/lanes", get(lanes_list).post(lanes_start)) .route("/v1/lanes/{lane}/stop", post(lanes_stop)) .route("/v1/lanes/{lane}/reset", post(lanes_reset)) + .route("/v1/lanes/{lane}/restart", post(lanes_restart)) .route("/v1/lanes/prune", post(lanes_prune)) .route("/v1/lanes/{lane}/move", post(lanes_move)) .route("/v1/lanes/{lane}/share", post(lanes_share)) @@ -878,6 +879,49 @@ async fn lanes_reset(State(s): State, Path(lane): Path) -> Res } } +#[derive(Deserialize, Default)] +struct LaneRestart { + /// `warm` (absent), `rebuild` or `cold`. + #[serde(default)] + mode: Option, +} + +/// `POST /v1/lanes/{lane}/restart` with `{"mode"}`: restart a started lane +/// where it runs (`warm`: its running services, from the artifacts there +/// are; `rebuild`: built again; `cold`: stopped, its data thrown away and +/// started again at the same place). `warm` and `rebuild` answer when the +/// services ran, `cold` once the lane is started again (its services start +/// after, on a node its `moving` shows the start). The lanes after it. +async fn lanes_restart( + State(s): State, + Path(lane): Path, + body: Option>, +) -> Response { + let lanes = match lanes_of(&s) { + Ok(l) => l.clone(), + Err(r) => return r, + }; + let mode = body.and_then(|b| b.0.mode).unwrap_or_else(|| "warm".into()); + if !matches!(mode.as_str(), "warm" | "rebuild" | "cold") { + return err( + StatusCode::BAD_REQUEST, + format!("mode `{mode}`: `warm`, `rebuild` or `cold`"), + ); + } + let main = s.sup.clone(); + let usage = s.usage.clone(); + let res = tokio::task::spawn_blocking(move || { + let need = lane_estimate(&main, &usage); + lanes.restart(&lane, &mode, need).map(|()| lanes.list()) + }) + .await; + match res { + Ok(Ok(v)) => Json(v).into_response(), + Ok(Err(e)) => err(StatusCode::CONFLICT, e), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + #[derive(Deserialize, Default)] struct Prune { /// Also kept lanes on nodes not used for this long (`7d`, `36h`). @@ -1117,8 +1161,8 @@ async fn service_env( } } -/// `POST /v1/groups/{name}/{start|stop|restart}`: every member; `409` names -/// the members that failed (the others ran). +/// `POST /v1/groups/{name}/{start|stop|restart|rebuild}`: every member, +/// its containers too; `409` names the members that failed (the others ran). /// The node's agent acted on the containers this request names already /// (a lane on a node, #128): its daemon, which has no Docker, leaves them. fn node_acted(headers: &axum::http::HeaderMap) -> bool { @@ -1134,7 +1178,7 @@ async fn group_action( if !s.sup.stack.groups.contains_key(&name) { return err(StatusCode::NOT_FOUND, format!("no group `{name}`")); } - if !matches!(action.as_str(), "start" | "stop" | "restart") { + if !matches!(action.as_str(), "start" | "stop" | "restart" | "rebuild") { return err( StatusCode::NOT_FOUND, format!("unknown group action `{action}`"), diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index 0f4dbd1b..2ee0f9e9 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -2137,6 +2137,123 @@ impl Lanes { result } + /// Restart a started lane where it runs (`POST /v1/lanes/{lane}/restart`): + /// `warm` restarts its running services in place, from the artifacts + /// there are for their inputs, its data kept; `rebuild` builds them + /// again even so. On a node through the lane's own API: the lease, the + /// node and the ports stay. `cold` stops it, throws its data away + /// ([`Self::reset`]) and starts it again at the same place, with the + /// same profile and workers: built again and seeded again, as a lane + /// that moves is (ADR-0038). Its containers stay up on `warm` and + /// `rebuild`. `need`: what a start on a node is expected to take. + pub fn restart( + self: &Arc, + name: &str, + mode: &str, + need: crate::remote::Expected, + ) -> Result<(), String> { + let t0 = std::time::Instant::now(); + let remote = self.remote(name); + if mode != "cold" { + let rebuild = mode == "rebuild"; + let r = match &remote { + Some(r) => r.restart_services(&self.rt, rebuild), + None => self.started(name)?.sup.restart_running(rebuild), + }; + crate::diag::info( + "lane_restarted", + serde_json::json!({ "lane": name, "mode": mode, + "place": if remote.is_some() { "remote" } else { "local" }, + "ms": t0.elapsed().as_millis() as u64, "ok": r.is_ok() }), + ); + return r; + } + // Cold: where it runs, and how, before the stop forgets it. + let on = remote.as_ref().map(|r| r.node.name.clone()); + let (path, workers) = match &remote { + Some(_) => ( + self.known + .lock() + .unwrap() + .get(name) + .map(|k| k.entry.path.clone()) + .ok_or_else(|| format!("no lane `{name}` (see `devstack lane list`)"))?, + self.workers.lock().unwrap().contains(name), + ), + None => { + let l = self.started(name)?; + (l.entry.path.clone(), l.sup.lane_workers()) + } + }; + let profile = self.profiles.lock().unwrap().get(name).cloned(); + self.stop(name)?; + let failed: Vec = self + .reset(name)? + .into_iter() + .filter(|p| !p.removed) + .map(|p| { + format!( + "{}: {}", + p.place, + p.error.unwrap_or_else(|| "not removed".into()) + ) + }) + .collect(); + if !failed.is_empty() { + return Err(format!( + "lane `{name}` is stopped, but not all of its data went ({}): it was not started again", + failed.join("; ") + )); + } + crate::diag::info( + "lane_restarted", + serde_json::json!({ "lane": name, "mode": mode, + "place": if on.is_some() { "remote" } else { "local" } }), + ); + match on { + Some(node) => { + self.activate_remote(&path, &node, need, profile.as_deref(), workers)?; + // Its services start once it runs there; `moving` shows the + // start meanwhile, and its error if it fails. + let lanes = self.clone(); + let lane = name.to_string(); + std::thread::Builder::new() + .name(format!("lane-cold-{name}")) + .spawn(move || { + while lanes.pending.lock().unwrap().contains(&lane) { + std::thread::sleep(std::time::Duration::from_secs(1)); + } + if let Some(r) = lanes.remote(&lane) + && let Err(e) = r.up(&lanes.rt) + { + crate::diag::warn( + "lane_restart_failed", + serde_json::json!({ "lane": lane, "mode": "cold", "error": e }), + ); + } + }) + .map_err(|e| format!("lane `{name}`: {e}"))?; + } + None => { + let lane = self.activate(&path, profile.as_deref())?; + lane.sup.set_lane_workers(workers); + let sup = lane.sup.clone(); + std::thread::Builder::new() + .name(format!("lane-cold-{name}")) + .spawn(move || { + if let Err(e) = sup.up() { + sup.emit(crate::state::EventBody::Infra { + group: "*".into(), + message: format!("up stopped: {e}"), + }); + } + }) + .map_err(|e| format!("lane `{name}`: {e}"))?; + } + } + Ok(()) + } + /// `devstack lane stop`: the lane's services stop and it is no longer /// started; its snapshot and builds stay for the next start. The worktree /// is git's business and stays as it is. diff --git a/crates/devstack-daemon/src/remote.rs b/crates/devstack-daemon/src/remote.rs index 829a5740..0775d668 100644 --- a/crates/devstack-daemon/src/remote.rs +++ b/crates/devstack-daemon/src/remote.rs @@ -1223,6 +1223,89 @@ impl RemoteLane { } } + /// Restart the services that run on the node now, in place, at the same + /// time, through the lane's own API: `restart`, with `rebuild` a + /// `rebuild` of those that run a build. The lease, the node and the + /// ports stay. Errors name the services that failed. Blocking. + pub fn restart_services( + &self, + rt: &tokio::runtime::Handle, + rebuild: bool, + ) -> Result<(), String> { + let (status, body) = rt + .block_on(self.client.api(&self.lease, "GET", "/v1/stack", None)) + .map_err(|e| format!("lane `{}` on {}: {e}", self.name, self.node.name))?; + if status != 200 { + return Err(format!( + "lane `{}` on {} answered {status}: {body}", + self.name, self.node.name + )); + } + let v: serde_json::Value = serde_json::from_str(&body).map_err(|e| e.to_string())?; + let running: Vec<(String, bool)> = v["services"] + .as_array() + .cloned() + .unwrap_or_default() + .iter() + .filter(|s| matches!(s["status"]["state"].as_str(), Some("healthy" | "running"))) + .filter_map(|s| { + let name = s["name"].as_str()?.to_string(); + // A service that runs a build has its id; one without a + // `build` cannot be rebuilt, only restarted. + Some((name, s["build_id"].as_str().is_some())) + }) + .collect(); + let failed: Vec = std::thread::scope(|scope| { + let handles: Vec<_> = running + .iter() + .map(|(name, built)| { + let action = if rebuild && *built { + "rebuild" + } else { + "restart" + }; + let path = format!("/v1/services/{name}/{action}"); + ( + name, + scope.spawn(move || { + rt.block_on(self.client.api(&self.lease, "POST", &path, None)) + }), + ) + }) + .collect(); + handles + .into_iter() + .filter_map(|(name, h)| match h.join() { + Ok(Ok((200, _))) => None, + Ok(Ok((_, body))) => Some(format!( + "{name}: {}", + serde_json::from_str::(&body) + .ok() + .and_then(|v| v["error"].as_str().map(str::to_string)) + .unwrap_or(body) + )), + Ok(Err(e)) => Some(format!("{name}: {e}")), + Err(_) => Some(format!("{name}: panicked")), + }) + .collect() + }); + if failed.is_empty() { + Ok(()) + } else { + Err(failed.join("\n")) + } + } + + /// Start the lane's services on the node (`POST /v1/up` there), as a + /// client does after the lane was started. Blocking. + pub fn up(&self, rt: &tokio::runtime::Handle) -> Result<(), String> { + match rt.block_on(self.client.api(&self.lease, "POST", "/v1/up", None)) { + Ok((s, _)) if s < 300 => Ok(()), + Ok((s, body)) => Err(format!("starting its services: {s} {body}")), + Err(e) => Err(e.to_string()), + } + } + /// Its services that run now (healthy or running), read from the lane /// at once rather than from the last poll. Blocking. pub fn active_now(&self, rt: &tokio::runtime::Handle) -> Vec { @@ -1923,7 +2006,8 @@ impl RemoteLane { /// The release a node needs to act on the containers `method path` names /// (`/v1/...` of the lane daemon's API): `/v1/infra/{group}/{service}/…` /// since #101, a service route that names containers (a group's restart, -/// a Compose service by its name) since #128. `None`: it names none. +/// a Compose service by its name) since #128, a group's start, stop and +/// rebuild that name containers since 0.28.0. `None`: it names none. fn containers_need( stack: &devstack_config::Stack, method: &axum::http::Method, @@ -1943,7 +2027,17 @@ fn containers_need( } else { Named::Groups }; - (!named(stack, route, name, action).is_empty()).then_some("0.12.0") + if named(stack, route, name, action).is_empty() { + return None; + } + // A group's start and stop took its containers along from + // 0.28.0 on, and its rebuild was new then. + let group = stack.groups.contains_key(*name); + Some(if group && *action != "restart" { + "0.28.0" + } else { + "0.12.0" + }) } _ => None, } @@ -2390,9 +2484,16 @@ members = ["api"] ] { assert_eq!(need(&Method::POST, p), Some("0.12.0"), "{p}"); } + for p in [ + "/v1/groups/server/start", + "/v1/groups/server/stop", + "/v1/groups/server/rebuild", + "/v1/services/server/stop", + ] { + assert_eq!(need(&Method::POST, p), Some("0.28.0"), "{p}"); + } for (m, p) in [ (Method::POST, "/v1/services/api/restart"), - (Method::POST, "/v1/services/server/stop"), (Method::POST, "/v1/groups/front/restart"), (Method::GET, "/v1/infra/app/db/logs"), (Method::GET, "/v1/services/web/restart"), diff --git a/crates/devstack-daemon/src/supervisor/infra.rs b/crates/devstack-daemon/src/supervisor/infra.rs index 9bebab4a..603cceb2 100644 --- a/crates/devstack-daemon/src/supervisor/infra.rs +++ b/crates/devstack-daemon/src/supervisor/infra.rs @@ -1201,7 +1201,7 @@ impl Supervisor { } /// A Compose service a lane uses from the main tree (`shared`, ADR-0030). - fn is_shared(&self, group: &str, service: &str) -> bool { + pub(super) fn is_shared(&self, group: &str, service: &str) -> bool { !self.lane.is_empty() && self .stack diff --git a/crates/devstack-daemon/src/supervisor/lifecycle.rs b/crates/devstack-daemon/src/supervisor/lifecycle.rs index cd7c9d02..243ba2ef 100644 --- a/crates/devstack-daemon/src/supervisor/lifecycle.rs +++ b/crates/devstack-daemon/src/supervisor/lifecycle.rs @@ -1285,13 +1285,16 @@ impl Supervisor { .map_err(|e| e.to_string()) } - /// `start`, `stop` or `restart` for every member of a group (plan §6). - /// Services start one after the other in member order (their `after` - /// pulls dependencies first) and stop in reverse; restarts build at the - /// same time. `restart` also restarts container members; commands are - /// left out. Errors name the members that failed, the others still ran. - /// In a lane on a node its agent restarts the container members - /// (`node_acted`, #128): this daemon has no Docker. + /// `start`, `stop`, `restart` or `rebuild` for every member of a group + /// (plan §6). Services start one after the other in member order (their + /// `after` pulls dependencies first) and stop in reverse; restarts build + /// at the same time, `rebuild` builds even when an artifact for the same + /// inputs exists (a member without `build` restarts). Container members + /// go with them: they start before the services and stop after them; a + /// lane's `shared` ones are the main tree's and are left alone. + /// Commands are left out. Errors name the members that failed, the + /// others still ran. In a lane on a node its agent acts on the container + /// members (`node_acted`, #128): this daemon has no Docker. pub fn group_action( self: &Arc, group: &str, @@ -1309,18 +1312,11 @@ impl Supervisor { .filter(|m| self.stack.services.contains_key(m.as_str())) .cloned() .collect(); - let containers: Vec<(String, String)> = g - .members - .iter() - .filter_map(|m| { - let rest = m.strip_prefix("compose.")?; - let (grp, svc) = rest.split_once('.')?; - Some((grp.to_string(), svc.to_string())) - }) - .collect(); + let containers = self.stack.group_containers(group); let mut failed: Vec = Vec::new(); match action { "start" => { + self.group_containers(&containers, "start", node_acted, &mut failed); for s in &services { if let Err(e) = self.start(s) { failed.push(format!("{s}: {e}")); @@ -1333,12 +1329,31 @@ impl Supervisor { failed.push(format!("{s}: {e}")); } } + self.group_containers(&containers, "stop", node_acted, &mut failed); } - "restart" => { + "restart" | "rebuild" => { + let rebuild = action == "rebuild"; let results: Vec<(String, Result<(), String>)> = std::thread::scope(|scope| { let handles: Vec<_> = services .iter() - .map(|s| (s.clone(), scope.spawn(|| self.restart(s)))) + .map(|s| { + let built = rebuild + && self + .stack + .services + .get(s) + .is_some_and(|v| v.build.is_some()); + ( + s.clone(), + scope.spawn(move || { + if built { + self.rebuild(s) + } else { + self.restart(s) + } + }), + ) + }) .collect(); handles .into_iter() @@ -1350,27 +1365,7 @@ impl Supervisor { .into_iter() .filter_map(|(s, r)| r.err().map(|e| format!("{s}: {e}"))), ); - if self.external_infra().is_some() { - // Never `docker compose` here: the lane container has - // no Docker, and the project would be the main tree's. - if !containers.is_empty() && !node_acted { - let names: Vec<&str> = containers.iter().map(|(_, s)| s.as_str()).collect(); - failed.push(format!( - "{}: {}", - names.join(", "), - super::infra::NODE_DID_NOT_ACT - )); - } - } else { - for (grp, svc) in &containers { - if let Err(e) = self.docker.restart(&self.compose_group(grp), svc) { - failed.push(format!("{svc}: {e}")); - } - } - } - if !containers.is_empty() { - self.refresh_containers(); - } + self.group_containers(&containers, "restart", node_acted, &mut failed); } _ => return Err(format!("unknown group action `{action}`")), } @@ -1381,6 +1376,106 @@ impl Supervisor { } } + /// Restart every service that runs now, at the same time, in place: a + /// lane's `restart` (warm), with `rebuild` building those with a `build` + /// even when an artifact for the same inputs exists. Stopped services + /// stay stopped; containers stay up. Errors name the services that + /// failed, the others still ran. + pub fn restart_running(self: &Arc, rebuild: bool) -> Result<(), String> { + let running: Vec = self + .stack + .services + .keys() + .filter(|n| self.service_running(n)) + .cloned() + .collect(); + let failed: Vec = std::thread::scope(|scope| { + let handles: Vec<_> = running + .iter() + .map(|s| { + let built = rebuild + && self + .stack + .services + .get(s) + .is_some_and(|v| v.build.is_some()); + ( + s, + scope.spawn(move || { + if built { + self.rebuild(s) + } else { + self.restart(s) + } + }), + ) + }) + .collect(); + handles + .into_iter() + .filter_map(|(s, h)| { + h.join() + .unwrap_or_else(|_| Err("panicked".into())) + .err() + .map(|e| format!("{s}: {e}")) + }) + .collect() + }); + if failed.is_empty() { + Ok(()) + } else { + Err(failed.join("\n")) + } + } + + /// `action` (`start`, `stop`, `restart`) on a group's container members, + /// what failed added to `failed`. A lane's `shared` ones are left out: + /// the main tree runs them (ADR-0030). In a lane on a node its agent did + /// it before the request came (`node_acted`); this daemon never runs + /// `docker compose` there (the lane container has no Docker, and the + /// project would be the main tree's). + fn group_containers( + &self, + containers: &[(String, String)], + action: &str, + node_acted: bool, + failed: &mut Vec, + ) { + if containers.is_empty() { + return; + } + if self.external_infra().is_some() { + if !node_acted { + let names: Vec<&str> = containers.iter().map(|(_, s)| s.as_str()).collect(); + failed.push(format!( + "{}: {}", + names.join(", "), + super::infra::NODE_DID_NOT_ACT + )); + } + } else { + for (grp, svc) in containers { + if self.is_shared(grp, svc) { + continue; + } + let g = self.compose_group(grp); + let r = match action { + "start" => { + let mut one = g.clone(); + one.services = vec![svc.clone()]; + self.docker.up(&one, std::time::Duration::from_secs(300)) + } + "stop" => self.docker.stop(&g, svc), + _ => self.docker.restart(&g, svc), + }; + if let Err(e) = r { + failed.push(format!("{svc}: {e}")); + } + } + } + self.refresh_containers(); + } + /// Start what `svc` comes after and is not ready yet (services, jobs that /// have not completed). Compose services are the infra plane's job (`up`). fn ensure_after(self: &Arc, svc: &Service) -> Result<(), String> { diff --git a/crates/devstack-node/src/laneinfra.rs b/crates/devstack-node/src/laneinfra.rs index 0521465d..205057e6 100644 --- a/crates/devstack-node/src/laneinfra.rs +++ b/crates/devstack-node/src/laneinfra.rs @@ -284,28 +284,27 @@ pub enum Named { /// The containers a `named` route acts on with `action`, `(group, /// service)`, as the lane's daemon reads the name (#128): none for one of -/// its services; a group's Compose members on `restart` (a group's `start` -/// and `stop` leave its containers alone); one Compose service named -/// `.`, `compose..` or, unambiguous, -/// ``. +/// its services; a group's Compose members on `start`, `stop`, `restart` +/// and `rebuild` (restarted); one Compose service named `.`, +/// `compose..` or, unambiguous, ``, on `start`, +/// `stop` and `restart`. pub fn named( stack: &devstack_config::Stack, route: Named, name: &str, action: &str, ) -> Vec<(String, String)> { - if !matches!(action, "start" | "stop" | "restart") { + if !matches!(action, "start" | "stop" | "restart" | "rebuild") { return Vec::new(); } if route == Named::Services && stack.services.contains_key(name) { return Vec::new(); } if stack.groups.contains_key(name) { - return if action == "restart" { - stack.group_containers(name) - } else { - Vec::new() - }; + return stack.group_containers(name); + } + if action == "rebuild" { + return Vec::new(); } match route { Named::Services => stack.compose_service(name).into_iter().collect(), @@ -493,8 +492,15 @@ members = ["compose.app.db", "compose.app.web", "api"] named(&s, Named::Groups, "server", "restart"), vec![pair("app", "db"), pair("app", "web")] ); - // A group's start and stop leave its containers alone, as locally. - assert!(named(&s, Named::Groups, "server", "stop").is_empty()); + // A group's start, stop and rebuild take its containers along, as + // locally. + for action in ["start", "stop", "rebuild"] { + assert_eq!( + named(&s, Named::Groups, "server", action), + vec![pair("app", "db"), pair("app", "web")], + "{action}" + ); + } // The daemon's own: a service, another action, an unknown name. assert!(named(&s, Named::Services, "api", "restart").is_empty()); assert!(named(&s, Named::Services, "web", "rebuild").is_empty()); diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index 9fbebe1c..9ece5cbd 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -2592,7 +2592,7 @@ async fn proxy( } /// `POST v1/services/{name}/{action}` or `POST v1/groups/{name}/{action}` -/// of the lane daemon's API, for `start`, `stop` and `restart`. +/// of the lane daemon's API, for `start`, `stop`, `restart` and `rebuild`. fn named_route( method: &hyper::Method, rest: &str, @@ -2608,7 +2608,7 @@ fn named_route( (Named::Groups, rest.strip_prefix("groups/")?) }; let (name, action) = rest.split_once('/')?; - (!name.is_empty() && matches!(action, "start" | "stop" | "restart")) + (!name.is_empty() && matches!(action, "start" | "stop" | "restart" | "rebuild")) .then(|| (route, name.to_string(), action.to_string())) } @@ -2638,6 +2638,12 @@ fn act_named( return None; } let single = route == laneinfra::Named::Services && !stack.groups.contains_key(name); + // A group's `rebuild` restarts its containers: nothing of theirs is built. + let action = if action == "rebuild" { + "restart" + } else { + action + }; let mut failed = Vec::new(); for (group, service) in &targets { let r = laneinfra::may_act(&stack, group, service, action) @@ -4197,9 +4203,15 @@ mod tests { named_route(&Method::POST, "v1/groups/server/restart"), some(Named::Groups, "server", "restart") ); + // A rebuild may name a group (its containers restart): the stack + // file says whether it does. + assert_eq!( + named_route(&Method::POST, "v1/services/server/rebuild"), + some(Named::Services, "server", "rebuild") + ); for (m, p) in [ (Method::GET, "v1/services/web/restart"), - (Method::POST, "v1/services/web/rebuild"), + (Method::POST, "v1/services/web/promote"), (Method::POST, "v1/services/web/logs/x"), (Method::POST, "v1/services//restart"), (Method::POST, "v1/commands/seed"), diff --git a/crates/devstack/tests/daemon_lifecycle.rs b/crates/devstack/tests/daemon_lifecycle.rs index 11802f7d..c3fb3150 100644 --- a/crates/devstack/tests/daemon_lifecycle.rs +++ b/crates/devstack/tests/daemon_lifecycle.rs @@ -2312,6 +2312,17 @@ fn a_worktree_runs_as_a_lane() { s.diag() ); assert_eq!(s.info()["build"], main_build.as_str(), "main is untouched"); + // A warm restart of the lane: its services restart from the artifact + // there is, in place; the main tree is not touched. + let lane_build = lane_info()["build"].as_str().unwrap().to_string(); + assert_eq!( + s.daemon_post(&format!("/v1/lanes/{lane}/restart")), + 200, + "{}", + s.diag() + ); + assert_eq!(lane_info()["build"], lane_build.as_str(), "the same build"); + assert_eq!(s.info()["build"], main_build.as_str(), "main is untouched"); // 4. promote --lane: the main ports answer from the lane, the dev server's // through a TCP forward, and the workers move with them. The static diff --git a/crates/devstack/tests/remote_lane.rs b/crates/devstack/tests/remote_lane.rs index acb96d18..cfbd8b3c 100644 --- a/crates/devstack/tests/remote_lane.rs +++ b/crates/devstack/tests/remote_lane.rs @@ -351,6 +351,19 @@ fn a_lane_runs_on_a_node_of_the_pool() { .expect("the lane answers"); assert!(!again.contains("daemon_start"), "taken once: {again}"); + // A warm restart restarts its running services on the node, through + // the lane's own API: the lane stays where it is. + let node_of = || { + api("/v1/lanes") + .and_then(|v| v.as_array()?.iter().find(|l| l["name"] == "wt").cloned()) + .map(|l| l["node"].clone()) + }; + let before = node_of(); + let (st, body) = api_request(&main, state.path(), "POST", "/v1/lanes/wt/restart") + .expect("the daemon answers"); + assert_eq!(st, 200, "{body}"); + assert_eq!(node_of(), before, "the lane stays on its node"); + // What `prepare` made is linked into the worktree here, from a copy on // this machine (ADR-0063), and a git hook there finds it (#277). let until = Instant::now() + Duration::from_secs(120); diff --git a/docs/adr/0072-a-restart-is-warm-a-rebuild-or-cold.md b/docs/adr/0072-a-restart-is-warm-a-rebuild-or-cold.md new file mode 100644 index 00000000..b842c6ed --- /dev/null +++ b/docs/adr/0072-a-restart-is-warm-a-rebuild-or-cold.md @@ -0,0 +1,102 @@ +# ADR-0072: A restart is warm, a rebuild or cold; a group acts on its containers too + +- **Status:** Accepted (2026-10-28) +- **Date:** 2026-10-28 +- **Deciders:** project owner +- **Related:** [ADR-0038](0038-a-lanes-data-outlives-its-lease.md) ("cold": no artifacts, no data), [ADR-0025](0025-a-lane-can-run-on-another-node.md) (a lane on a node; a move is a cold start), [ADR-0030](0030-each-lane-has-its-own-infrastructure.md) (`shared` containers), [ADR-0062](0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md) (what is kept for the same inputs), [ADR-0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) + +## Context + +The dashboard had one restart: a service's, a group's, and none for a lane. +`devstack restart --rebuild` (build again although a build for the same +inputs exists) was in the CLI and the service page only. A lane could be +stopped from the header and its data thrown away from there once stopped, +but restarted only by stopping and starting it again, which on a node ends +its lease and may place it on another node; its worktree was removed from +the branch picker only. + +A group's `start` and `stop` left its container members alone, while its +`restart` restarted them: a group of containers only (an observability +group) got no buttons at all, since they would have done nothing. + +The owner asked for warm and cold restarts in the dashboard. "Cold" had a +meaning in devstack already: ADR-0038 and `lane move` call a start without +artifacts **and** without data (seeded again) cold. A choice between warm +and cold alone would either name a rebuild cold or throw data away without +saying so. + +## Decision + +1. **A restart has three levels, named as ADR-0038 names them.** + **Restart** (warm): from the build there is for the inputs (else built), + the data kept. **Rebuild**: built again even for inputs built before, the + data kept (`restart --rebuild`, `POST /v1/services/{name}/rebuild`). + **Cold**: built again and its data seeded again; for a lane only, never + for the main working tree (whose data a profile with `data = "fresh"` + throws away, ADR-0041). +2. **Each restart button is a split button.** A click restarts warm; its + arrow offers Rebuild, and Cold… for a lane. Only Cold asks first: it + throws data away. A service row, a group's head and the lane's header + have one; the command palette has the same actions. +3. **A lane restarts where it runs:** `POST /v1/lanes/{lane}/restart` with + `{"mode": "warm" | "rebuild" | "cold"}` on the requester's daemon. Warm + and rebuild restart its running services in place, its containers stay + up; on a node through the lane's own API, so the lease, the node and the + ports stay. Cold stops the lane, throws its data away as `reset` does, + and starts it again at the same place (this machine or its node) with the + same profile and workers. A group has `rebuild` as well + (`POST /v1/groups/{name}/rebuild`). +4. **A group's `start` and `stop` take its containers along**, as its + `restart` did: `start` starts its containers before its services, `stop` + stops them after its services. A lane leaves the main tree's `shared` + containers alone; on a node the node's agent acts on them (#128), and + the requester asks for a node of 0.28.0 or later for these. So every + stack-file group with services or containers has its buttons. +5. **A lane's actions are in one menu.** At the top right of the header the + main button restarts a started lane and starts a stopped one; its menu + has Rebuild, Cold…, Stop, and for a stopped lane Discard data… and + Remove worktree…. The same menu opens from a lane's "…" button and by a + right click on its row in the branch picker. The separate "Stop + worktree" and "Discard data" buttons are gone; Remove worktree stays in + the branch picker too. + +The [card](https://github.com/nuetzliches/devstack/pull/351) and its approval (2026-10-28, points 1–5) are in the pull request that built this. + +## Consequences + +- A group's `stop` (`devstack stop `, its dashboard button) stops + its databases too where it lists them; before, it stopped its services + only. A group meant as a view of services only should not list + containers. +- A cold restart of a lane on a node starts it on the same node only if the + node takes it again (a new lease); if not, it stays stopped and its + `moving` says why. Its data is gone either way. +- The CLI keeps `restart --rebuild`; there is no `--cold` and no CLI or MCP + command for a lane restart yet. + +## Alternatives considered + +- **Warm and cold only.** Rejected: either "cold" is a rebuild under the + name ADR-0038 gives a start without data, or every cold restart throws + data away. +- **A confirmation dialog with the choice on every restart.** Rejected: the + warm restart is the common one and would take a click more each time; + only the level that throws data away asks. +- **A lane restart as stop and start in the client.** Rejected: on a node + the stop ends the lease, and the start may land on another node, a cold + start there. +- **Buttons only for groups with services.** Rejected: a group of + containers is a unit worth starting and stopping, and the buttons did + nothing for its containers only because `start` and `stop` left them out. + +## Where it lives + +`crates/devstack-daemon/src/supervisor/lifecycle.rs` (`group_action`, +`group_containers`, `restart_running`), `crates/devstack-daemon/src/lanes.rs` +(`Lanes::restart`), `crates/devstack-daemon/src/remote.rs` +(`RemoteLane::restart_services`, `containers_need`), +`crates/devstack-daemon/src/api.rs` (`lanes_restart`), +`crates/devstack-node/src/laneinfra.rs` (`named`), `node.rs` +(`named_route`, `act_named`); `ui/src/components/SplitButton.vue`, +`ui/src/lib/laneActions.ts`, `StackHeader.vue`, `BranchPicker.vue`, +`ServiceRow.vue`, `OverviewView.vue`, `CommandPalette.vue`. diff --git a/docs/adr/README.md b/docs/adr/README.md index 4ca8337f..f7ee9355 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -154,3 +154,4 @@ stay. | [0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) | `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub | Accepted ([card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)): a proxy in the hub, per user; amended 2026-10-27 (keychain via `keyring`, a file on Linux without a Secret Service) | | [0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) | A review card comes before the code; an ADR records what was built | Accepted (supersedes ADR-0001); point 1 amended 2026-10-28 (the card in the conversation and the pull request, no issue) | | [0071](0071-the-dashboard-writes-no-file-of-a-repository.md) | The dashboard writes no file of a repository; a change to one is a prompt for a coding agent | Accepted | +| [0072](0072-a-restart-is-warm-a-rebuild-or-cold.md) | A restart is warm, a rebuild or cold; a group acts on its containers too | Accepted ([card](https://github.com/nuetzliches/devstack/pull/351)) | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 094a2c7f..2e911a36 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -379,6 +379,7 @@ type StoreView = { | `GET /v1/lanes` | JSON, the lanes: the repository's other worktrees ([ADR-0024](adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md)), `[{name, path, branch, number, port_offset, active, owns_main, running, services, containers_running, containers, node?, pool?, shared_with?, profile?, workers?, node_error?, node_warning?, not_forwarded?}]`; `active`: started; `containers_running`/`containers`: its Compose containers devstack starts that run, and all (a stack of containers only shows by them that it runs); `node`: the node of the pool it runs on (absent: this machine), `pool`: that node's pool, `shared_with`: whom it is shared with (member ids, tags, `*`; absent: nobody), `profile`: the profile it runs with, `workers`: `true` while its background workers run (`--workers` or its profile, here or on a node, #314), `node_error`: what goes wrong with it now (a sync, a renewal, a port that cannot be forwarded here), each until it works again, several joined by `; `, `node_warning`: the node or the coordinator runs another devstack than this machine, or does not say which (from the lease on, so while it starts too; [ADR-0031](adr/0031-a-coordinator-places-lanes.md) point 8); `not_forwarded`: its containers' published ports that run on the node but are not forwarded here (`5353/udp`): UDP ports a node older than 0.20.0 does not relay ([ADR-0056](adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md)), ports of another protocol than TCP and UDP (#192; a lane daemon of an older devstack does not say), `not_forwarded_reason`: why; `moving`: `{kind: start|move, to, step, steps, what, since, phases, phase_since, error?, failed_at?}` (`phases`: `[{phase, ms}]` over so far, `phase_since`: when the current one began) while a start on a node or a move runs, and for ten minutes after one failed; `removing`: `true` while the lane of a worktree that is gone is stopped and its data removed (it leaves the list after); `main_stack_file`: `true` while its worktree has no stack file at the main one's path, so it runs with the main working tree's, here and on a node ([ADR-0055](adr/0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md)) | | `POST /v1/lanes` | `{"path", "infra"?, "workers"?, "force"?, "on"?, "profile"?}`: start the lane of that worktree, with `profile` with that profile of its stack file ([ADR-0041](adr/0041-a-profile-says-how-a-lane-runs-for-a-purpose.md); `409` when the worktree's stack file has no such profile or it does not apply); with `on` (a node's name or member id, or `pool` for the coordinator to choose; in another pool than the default one `:`, or `` for its coordinator to choose, [ADR-0034](adr/0034-a-machine-can-belong-to-several-pools.md)) on that node of the pool instead, leased, synced and started there, its API passed through under `/v1/lanes/{lane}/v1/...` ([ADR-0025](adr/0025-a-lane-can-run-on-another-node.md)) (what `devstack up` in it does; `infra` starts the main tree's `shared` Compose services if needed, the lane's own containers start with its `up`; `workers` runs its background workers; `force` skips the memory check, which otherwise answers `409` with what the lane needs and what is free, ADR-0030; with Docker Desktop its containers are checked against its VM's free memory and its services against the host's, #309), then `/v1/lanes/{lane}/v1/up` starts its services and its containers. `201` with its entry. With `on`: `202` with its entry once the lane is leased and admitted by the node; its sync and its start there (minutes on a first start: images pulled and built, containers created) go on in the background, shown as the entry's `moving` (`kind: "start"`, in `lanes` events and here). It runs there once `moving` is gone and `active` is `true`, which is once the lane's daemon answers there: its containers come up after, under it (#164; a node of an earlier release answers once they are healthy), and show as `created`, then `starting` and `healthy` in its `InfraView`s (then call `/v1/up`, which starts its services once their infrastructure is up); it failed when `moving` carries `error` (for ten minutes, until the lane stops, the main tree's `/v1/down` or a start of it here). What can be told at once is refused at once: no such worktree, a lane that runs elsewhere, no lease (`409` with the reason: no node, the coordinator or the node refuses, a node with another pool protocol). The same start asked again while it goes on answers `202` too; `201` when the lane runs on that node already. Up to 0.10.1 a start on a node answered `201` only when done. Worktrees are git's: there is no route that creates or removes one | | `POST /v1/lanes/{lane}/share` | `{"with"}`: share a lane on a node with others in its pool: member ids, tags, `*` for every member; `[]` for nobody ([ADR-0035](adr/0035-lanes-can-be-shared-with-the-pool.md)). They open its services and view it, read only ([ADR-0040](adr/0040-a-shared-lane-can-be-watched-like-ones-own.md)); `view`, a separate list up to 0.11.1, is ignored. Kept per lane, told the coordinator while it runs on a node. Answers with the lanes (`LaneView.shared_with`) | +| `POST /v1/lanes/{lane}/restart` | `{"mode"?: "warm" \| "rebuild" \| "cold"}` ([ADR-0072](adr/0072-a-restart-is-warm-a-rebuild-or-cold.md)): restart a started lane where it runs. `warm` (the default) restarts its running services from the builds there are for their inputs, `rebuild` builds them again even so; both keep its data and its containers up, and on a node go through the lane's own API (the lease, the node and the ports stay); they answer when the services ran. `cold` stops it, throws its data away as `reset` does and starts it again at the same place (this machine or its node), with its profile and workers: built again and seeded again. It answers once the lane is started again; its services start after (on a node its `moving` shows the start). The lanes after it; `400` for another mode, `409` with the reason (not started, serves the main ports for `cold`, data that did not go: then it stays stopped) | | `POST /v1/lanes/{lane}/reset` | a stopped lane's data goes, here and on the nodes it ran on (ADR-0038): `[Pruned]` (`{place, lane, bytes, why, removed, error}`; `removed: false` with `error` where it did not go, this machine's containers too); `409` while it runs | | `POST /v1/lanes/prune` | `{"older_than"?: "7d", "dry_run"?: bool}`: what this repository's lanes leave behind: on this machine the Compose projects of lanes whose worktree is gone (only those whose files are in this repository's lane state), on the pool's nodes this machine's kept lanes of this repository that are gone or not used for `older_than`; `[Pruned]` | | `POST /v1/lanes/{lane}/move` | `{"to"}`: a node of the pool (name or member id, `:` in another pool) or `local`; the started lane moves there, a cold start that takes over once its autostart services are ready ([ADR-0025](adr/0025-a-lane-can-run-on-another-node.md) point 10). Answers when done, with the lanes; `409` with the reason when it could not (the lane stays where it was) | @@ -409,7 +410,7 @@ type StoreView = { | `GET /v1/tunnel/{port}` with `Upgrade: devstack-tcp` | a raw TCP connection to that port on the daemon's machine (ADR-0029 point 4): a service's port on its loopback, or a lane's container port on the lane's network; other ports `403`. How the requester reaches the services of its lane on a node: each port it forwards here connects, through the node agent, to the lane daemon's tunnel there | | `GET /v1/tunnel/{port}` with `Upgrade: devstack-udp` | a UDP session to the lane's container published on `port` as UDP ([ADR-0056](adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md)): each datagram a frame, its length as two bytes big-endian, then its bytes, both ways; the daemon sends them from a socket of the session's own. Other ports `403`, a container that does not resolve yet `502`. The requester opens one per client address of a UDP port it relays, and ends it after 60 s without a datagram either way | | `POST /v1/services/{name}/start` \| `stop` \| `restart` \| `rebuild` \| `promote` \| `rollback` | `200 StackView`, or `409 {"error": "..."}` (e.g. compiler errors; the running instance stays). `rebuild` is `restart` that builds even when an artifact for the same inputs exists (`devstack restart --rebuild`; the build gets the id `-`). A `stop` ends a start in progress (a build, a health wait, a job) at once. For a name that is no service but a group, `start`/`stop`/`restart` act on the group; for a name that is neither but a Compose service (`.`, the member form `compose..`, or `` when exactly one compose group lists it in `services`) they act on that container as `/v1/infra/{group}/{service}/…` does, and answer `200 StackView`. `404` for a name that is none of these. `hot-reload-on` / `hot-reload-off` switch a service with `hot_reload` in the stack file into and out of hot-reload mode (`ServiceView.hot_reload`, `hot_reload_available`) | -| `POST /v1/groups/{name}/start` \| `stop` \| `restart` | every member service of the group: start in member order, stop in reverse, restart (build) at the same time; `restart` also restarts container members, commands are left out. `200 StackView`, or `409` naming each member that failed (the others ran) | +| `POST /v1/groups/{name}/start` \| `stop` \| `restart` \| `rebuild` | every member of the group, its containers too ([ADR-0072](adr/0072-a-restart-is-warm-a-rebuild-or-cold.md)): `start` its containers first, then its services in member order; `stop` its services in reverse, then its containers; `restart` its services (built when no build for their inputs exists) at the same time, then its containers; `rebuild` as `restart`, building the services with a `build` even when a build exists. A lane leaves the main tree's `shared` containers alone; commands are left out. `200 StackView`, or `409` naming each member that failed (the others ran) | | `POST /v1/infra/{group}/{service}/{start\|stop\|restart}` | `204`; one container (in a lane its own; a `shared` one: `409`). `{service}` is the Compose service name, as `ContainerView.service` gives it, never the container name (`container_name:`). The routes accept every container the view shows: one the group does not start (`managed: false`: started by hand, of a profile, left from an earlier stack file) can be stopped (`docker stop` by its name), `start` and `restart` answer `409` with the reason; a service that is neither in `services` nor a container of the project: `404` with the reason; another action: `400`. The dashboard shows each container on a page of its own (`/s//infra//`) with its log | | `POST /v1/commands/{name}` with `{"confirm": false}` | `202 {"run": 7}`, or `428 {"confirm": "text"}` (ask the user, then send `confirm: true`), `409 {"error"}` (a required service is not ready) | | `GET /v1/commands/{name}/runs` | `[Run]` | @@ -423,8 +424,9 @@ paths (`/v1/lanes//v1/...` on the requester's daemon). It answers lists in `services` (on a node its `shared` ones are the lane's own too), `stop` for any container of the lane's project. For `POST /v1/services/{name}/{start|stop|restart}` and -`POST /v1/groups/{name}/restart` that name containers (a Compose service by -its name, a group's container members on `restart`) it acts on them, by +`POST /v1/groups/{name}/{start|stop|restart|rebuild}` that name containers +(a Compose service by its name, a group's container members; `rebuild` +restarts them) it acts on them, by container name in the projects it started for the lease, then passes the request on with `X-Devstack-Node-Acted: 1` for the daemon's answer (#128); a container it could not act on makes the answer `409` naming it. The daemon @@ -432,7 +434,8 @@ never runs Compose for them itself: a request that names containers and lacks the header (it came past an agent that could not read the stack file, or an older one) is answered `409`. The requester's daemon answers `409` with what to update when the node's devstack is older than the release that -does this (0.12.0; 0.11.0 for `/v1/infra/...`). +does this (0.12.0; 0.11.0 for `/v1/infra/...`; 0.28.0 for a group's +`start`, `stop` and `rebuild` that name containers). Its daemon answers before its containers run (#164): the agent starts them after, a Compose group at a time, and `POST /v1/up` there waits for each diff --git a/docs/stack-file.md b/docs/stack-file.md index 97e40af6..5be37fa0 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -933,7 +933,10 @@ members = ["api", "web", "compose.app.db", "command.seed"] Labels for the dashboard and `devstack status`, not dependencies: a member may be in several groups, and members of no group appear under "Other". `label` defaults to the group's key; groups without `order` follow those -with one, alphabetically. +with one, alphabetically. `devstack start|stop|restart ` and the +group's buttons in the dashboard act on every member, its containers too +(a lane leaves the main tree's `shared` ones alone); `restart --rebuild` +builds its services again even for inputs built before. `members` is required, not empty, lists each member once, and names what exists (a `compose..` member is a service its group starts). diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index 77971fe2..9937a014 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -70,7 +70,7 @@ Run from the repository root (devstack looks for `{{devstack:stack_file}}` there | `devstack pool connect ` / `devstack pool disconnect ` | forward all of a shared lane's services here, on its owner's ports if free; close them again and free the ports | | `devstack logs --daemon` | devstack's own log: every decision with its reason (`--grep `, `--hub` for the dashboard hub) | | `devstack restart ` | rebuild now; the running instance stays until the new one is healthy. `--rebuild` builds again although an artifact for the same inputs exists (an input devstack does not see changed: the SDK, a file outside the repository) | -| `devstack restart ` | every service of a group from the stack file, built at the same time, and its containers (`start`/`stop` take a group too) | +| `devstack restart ` | every service of a group from the stack file, built at the same time, and its containers (`start`/`stop` take a group too, its containers with it; `--rebuild` builds its services again even for inputs built before) | | `devstack restart .` | one Compose container (`compose.app.web` or `web` work too; `start`/`stop` as well); in a lane its own container, on a node through the node | | `devstack promote ` | take over a candidate that is held (schema change, see below) | | `devstack rollback ` | back to the build before the last replacement, without building | diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index 49ee73bf..3bbc5496 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -756,6 +756,15 @@ export class MockTransport implements Transport { return json(200, []); } if (/^\/v1\/lanes\/[^/]+\/reset$/.test(p) && method === 'POST') return json(200, []); + // A lane restarts where it runs (warm, rebuild), or cold: stopped, its + // data gone, started again there. + const rs = /^\/v1\/lanes\/([^/]+)\/restart$/.exec(p); + if (rs && method === 'POST') { + const name = decodeURIComponent(rs[1]); + if (!s.startedLanes.has(name)) return json(409, { error: `lane \`${name}\` is not started` }); + await sleep(body?.mode === 'cold' ? 2500 : 1500); + return json(200, lanes()); + } const fw = /^\/v1\/lanes\/[^/]+(\/v1\/.*)$/.exec(p); if (fw) p = fw[1]; const view = () => json(200, s.view); @@ -807,11 +816,11 @@ export class MockTransport implements Transport { return text(200, `info: started\nwarn: something went wrong in ${q.get('file')}\nfail: Unhandled exception`); } - const ga = /^\/v1\/groups\/([^/]+)\/(start|stop|restart)$/.exec(p); + const ga = /^\/v1\/groups\/([^/]+)\/(start|stop|restart|rebuild)$/.exec(p); if (ga) { const g = s.view.groups.find((x) => x.name === decodeURIComponent(ga[1])); if (!g) return json(404, { error: `no group ${ga[1]}` }); - await sleep(ga[2] === 'restart' ? 2500 : 900); + await sleep(ga[2] === 'restart' || ga[2] === 'rebuild' ? 2500 : 900); for (const m of g.members) { const svc = s.view.services.find((x) => x.name === m); if (!svc) continue; @@ -820,7 +829,7 @@ export class MockTransport implements Transport { } return view(); } - let m = /^\/v1\/services\/([^/]+)\/(start|stop|restart|promote|rollback|build-log|logs|hot-reload-on|hot-reload-off)$/.exec(p); + let m = /^\/v1\/services\/([^/]+)\/(start|stop|restart|rebuild|promote|rollback|build-log|logs|hot-reload-on|hot-reload-off)$/.exec(p); if (m) { const name = decodeURIComponent(m[1]); const action = m[2]; @@ -853,6 +862,7 @@ export class MockTransport implements Transport { if (svc.proxy) svc.proxy = { ...svc.proxy, upstream: null, active: 0 }; s.setStatus(name, { state: 'stopped' }); return view(); + case 'rebuild': case 'restart': { if (s.failedBuild.has(name) && name === 'api') { s.cand(name, 'building'); diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index 5da3f97c..2c1914f4 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -139,6 +139,7 @@ export const v1 = { lane: (lane: string) => `/v1/lanes/${enc(lane)}`, laneStop: (lane: string) => `/v1/lanes/${enc(lane)}/stop`, laneReset: (lane: string) => `/v1/lanes/${enc(lane)}/reset`, + laneRestart: (lane: string) => `/v1/lanes/${enc(lane)}/restart`, laneMove: (lane: string) => `/v1/lanes/${enc(lane)}/move`, events: '/v1/events', journal: (since = 0) => `/v1/journal?since=${since}`, @@ -165,7 +166,9 @@ export const v1 = { }; export type ServiceAction = 'start' | 'stop' | 'restart' | 'rebuild' | 'promote' | 'rollback' | 'hot-reload-on' | 'hot-reload-off'; -export type GroupAction = 'start' | 'stop' | 'restart'; +export type GroupAction = 'start' | 'stop' | 'restart' | 'rebuild'; +/** How a lane restarts: `warm` from the artifacts there are, `rebuild` built again, `cold` built again with its data seeded again. */ +export type RestartMode = 'warm' | 'rebuild' | 'cold'; function enc(s: string): string { return encodeURIComponent(s); diff --git a/ui/src/components/BranchPicker.vue b/ui/src/components/BranchPicker.vue index 55a5ffee..02d199c7 100644 --- a/ui/src/components/BranchPicker.vue +++ b/ui/src/components/BranchPicker.vue @@ -8,6 +8,7 @@ import { computed, nextTick, ref } from 'vue'; import type { BranchView, LaneView } from '@/api/types'; import { ago, useNow } from '@/lib/format'; +import { laneActions, type LaneAction } from '@/lib/laneActions'; import { laneLabel, samePath } from '@/lib/lanes'; import { usePopover } from '@/lib/popover'; import { useHub } from '@/stores/hub'; @@ -103,10 +104,25 @@ function remove(r: Row) { void stack.removeWorktree(r.b.worktree!, r.lane ? laneLabel(r.lane) : r.b.name); } +// A lane's actions, as the header's menu has them: by its "…" button or a +// right click on its row, under the row. +const actionsOf = ref(null); +function toggleActions(r: Row) { + if (!r.lane || stack.readOnly) return; + creating.value = null; + actionsOf.value = actionsOf.value === r.b.name ? null : r.b.name; +} +function laneAct(r: Row, a: LaneAction) { + close(); + actionsOf.value = null; + if (r.lane) void stack.laneAction(r.lane, a); +} + // A new branch from the one chosen, and a lane on it. const creating = ref(null); const newName = ref(''); function startNew(r: Row) { + actionsOf.value = null; creating.value = r.b.name; newName.value = ''; void nextTick(() => root.value?.querySelector('[data-testid="branch-new-name"]')?.focus()); @@ -161,7 +177,15 @@ function create() {