From 937316a0c555cdc46bbffa1b0954a65a8d05d3f4 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 22 Nov 2026 15:32:26 -0500 Subject: [PATCH 1/2] App map: one build at a time per team, and a status the page can explain The App map's "Build the map again" pressed three times in nine seconds queued three builds and the worker ran all three: the rebuild route wrote the status with no condition (force) and the worker never checked. - common::app_map: the build status carries a build id, the turn the worker is on, when the build started, its stage (reading, parts, describing, done), the repositories it reads, and when the current map was built from how many. Every write is versioned (a conditional put on v), and the decisions are pure: queue_next refuses while a build is queued or running (unless stuck past STALE_SECS); take_turn lets each message of a build run once (a duplicate, or another build's message, is skipped; the same message again after its worker went quiet past LEASE_SECS may retake it); progress/finished/failed only touch the build that is running. estimate_secs gives a usual range from the repository count. - Gateway: POST /api/app-map/rebuild answers 409 already_building with the running build's status and sends nothing; 202 with the new status otherwise. GET /api/app-map returns started_at, stage, last_build, repos, estimate, built_at, built_repos and the server clock; graph=0 returns the status only (a HEAD for the map's date). - Worker: each message takes its turn first and skips when it isn't the build's next; steps report their stage; messages carry the build id and turn; after_push uses the same one-build rule. - Tests: three presses queue one build and send one message (fails on main: each press queued one), six concurrent presses start one, the worker skips a duplicate start and step, status_view, estimate. The AWS stand-in now records SQS messages and answers S3 reads. --- services/common/contract/worker_messages.json | 2 +- services/common/src/app_map.rs | 418 +++++++++++++++--- services/common/src/messages.rs | 8 + services/gateway/src/fake_aws.rs | 51 ++- services/gateway/src/routes/app_map.rs | 395 +++++++++++++++-- services/worker/src/passes/app_map.rs | 241 +++++++--- 6 files changed, 952 insertions(+), 163 deletions(-) diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index 313a3c1fc..1d2be9990 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -16,7 +16,7 @@ "webhook_send": {"type":"webhook_send","team_id":"TEAM#team-a","endpoint_id":"ep_01jbendpt4a7b0c3d6e9f2g5h8","event_id":"evt_01JBEVNT8M1N4P7Q0R3S6T9V2W","delivery_id":"01hzzdelivery","due_at":1792416387}, "relay_retry": {"type":"relay_retry","install_id":"ins_abcdefghijklmnopqrstuvwx","delivery_id":"01hzzdelivery","relay_delivery_id":"72d3162e-cc78-11e3-81ab-4c9367dc0958","event":"pull_request","source":"github"}, "await_merge": {"type":"await_merge","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2,"head_sha":"abc","base_branch":"main","self_authored":true,"attempts":1,"chain_id":"c","error_retries":0}, - "app_map": {"type":"app_map","team_id":"TEAM#team-a","repo":"","step":"build"}, + "app_map": {"type":"app_map","team_id":"TEAM#team-a","repo":"","step":"build","build":"0f9c2d4e8a7b4c1d9e6f3a2b1c0d9e8f","turn":2}, "graph_index": {"type":"graph_index","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","branch":"main","changed_files":["a.rs"]}, "release_notes": {"type":"release_notes","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","tag":"v1.0.0","sha":"abc","resend":"","check_branch":true}, "restack": {"type":"restack","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","branch":"coderhelm/feature-a","before":"abc","after":"def"}, diff --git a/services/common/src/app_map.rs b/services/common/src/app_map.rs index 2858907ba..61b62b6f1 100644 --- a/services/common/src/app_map.rs +++ b/services/common/src/app_map.rs @@ -83,104 +83,299 @@ pub fn job_key(team_id: &str) -> String { pub const STATUS_SK: &str = "STATUS"; /// A build queued or running this long is treated as stuck. pub const STALE_SECS: i64 = 45 * 60; +/// A turn the worker took this long ago without a word since is taken to +/// have died with its worker (a Lambda runs at most 15 minutes), so the same +/// message, delivered again, may take it again. +pub const LEASE_SECS: i64 = 16 * 60; + +/// The build's steps in order, by key; the page words each one. `done` is +/// the map written. +pub const STAGES: [&str; 4] = ["reading", "parts", "describing", "done"]; /// Where the team's map build is. +/// +/// One build at a time: a build has an id (`build`), and each message of it +/// takes its numbered turn (`turn`), so a second press of "Build the map +/// again", or a message delivered twice, finds the build already running and +/// does nothing ([`queue_next`], [`take_turn`]). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Status { /// `queued`, `building`, `ready` or `failed`. pub state: String, + /// When the status last changed (a running build's last sign of life). pub at: i64, /// What the build is doing now, in plain words. #[serde(default)] pub step: String, #[serde(default)] pub error: String, + /// The build this status is about. + #[serde(default)] + pub build: String, + /// Turns of the build taken so far. + #[serde(default)] + pub turn: u32, + /// When the build was asked for. + #[serde(default)] + pub started: i64, + /// One of [`STAGES`]. + #[serde(default)] + pub stage: String, + /// Repositories this build reads. + #[serde(default)] + pub repos: u32, + /// When the map that is there now was finished (0: not known). + #[serde(default)] + pub built: i64, + /// Repositories that map was made from. + #[serde(default)] + pub built_repos: u32, } impl Status { pub fn is_stale(&self, now: i64) -> bool { matches!(self.state.as_str(), "queued" | "building") && now - self.at > STALE_SECS } + + /// A build is queued or running (and not stuck). + pub fn is_running(&self, now: i64) -> bool { + matches!(self.state.as_str(), "queued" | "building") && !self.is_stale(now) + } +} + +/// A new build, unless one is already queued or running: `None` then, and +/// the running build stands. What is known about the last map is kept. +pub fn queue_next(cur: Option<&Status>, now: i64, build: &str) -> Option { + if cur.is_some_and(|s| s.is_running(now)) { + return None; + } + let prev = cur.cloned().unwrap_or_default(); + Some(Status { + state: "queued".into(), + at: now, + step: "Waiting to start".into(), + error: String::new(), + build: build.to_string(), + turn: 0, + started: now, + stage: STAGES[0].into(), + repos: if prev.repos > 0 { + prev.repos + } else { + prev.built_repos + }, + built: prev.built, + built_repos: prev.built_repos, + }) +} + +/// The worker taking turn `turn` of build `build` (one message of it): +/// `None` when the message is not the build's next one (a second message for +/// a build already running, a message delivered twice, a build replaced by a +/// newer one), and the worker does nothing with it. A message from before +/// builds had ids (`build` empty) carries on a build that has none. +pub fn take_turn(cur: Option<&Status>, build: &str, turn: u32, now: i64) -> Option { + let s = cur?; + if s.build != build { + return None; + } + let expected = if turn == 0 { "queued" } else { "building" }; + let next = s.turn == turn && s.state == expected; + // The same message again, after the worker that took it died. + let again = s.turn == turn + 1 && s.state == "building" && now - s.at > LEASE_SECS; + if !next && !again { + return None; + } + let mut out = s.clone(); + out.state = "building".into(); + out.turn = turn + 1; + out.at = now; + out.error.clear(); + Some(out) +} + +/// The running build's progress: `None` when `build` is no longer the one +/// running. +pub fn progress( + cur: Option<&Status>, + build: &str, + stage: Option<&str>, + step: &str, + now: i64, +) -> Option { + let s = cur.filter(|s| s.build == build && s.state == "building")?; + let mut out = s.clone(); + if let Some(st) = stage { + out.stage = st.into(); + } + out.step = step.into(); + out.at = now; + Some(out) +} + +/// The build finished: `repos` is how many repositories the map covers (0 +/// with a note when there was nothing to map). +pub fn finished( + cur: Option<&Status>, + build: &str, + repos: u32, + note: &str, + now: i64, +) -> Option { + let s = + cur.filter(|s| s.build == build && matches!(s.state.as_str(), "queued" | "building"))?; + let mut out = s.clone(); + out.state = "ready".into(); + out.stage = STAGES[3].into(); + out.step.clear(); + out.error = note.into(); + out.at = now; + if repos > 0 { + out.repos = repos; + out.built = now; + out.built_repos = repos; + } + Some(out) +} + +/// The build stopped, and why in plain words. +pub fn failed(cur: Option<&Status>, build: &str, why: &str, now: i64) -> Option { + let s = + cur.filter(|s| s.build == build && matches!(s.state.as_str(), "queued" | "building"))?; + let mut out = s.clone(); + out.state = "failed".into(); + out.error = why.into(); + out.at = now; + Some(out) +} + +/// How long a build usually takes for this many repositories, in seconds +/// (low and high): the sandbox reads and builds the map two or three times, +/// and the model works out the parts and describes each one. +pub fn estimate_secs(repos: u32) -> (i64, i64) { + let r = repos.max(1) as i64; + let low = (3 + r) * 60; + let high = ((6 + 2 * r) * 60).min(STALE_SECS); + (low.min(high), high) } type Dynamo = aws_sdk_dynamodb::Client; use aws_sdk_dynamodb::types::AttributeValue as A; -pub async fn status(dynamo: &Dynamo, table: &str, team_id: &str) -> Option { +/// The status and its version (0: an item from before versions, or none). +async fn read_status( + dynamo: &Dynamo, + table: &str, + team_id: &str, +) -> Result<(Option, Option), String> { let out = dynamo .get_item() .table_name(table) .key("pk", A::S(map_pk(team_id))) .key("sk", A::S(STATUS_SK.into())) + .consistent_read(true) .send() .await - .ok()?; - serde_json::from_str(out.item()?.get("json")?.as_s().ok()?).ok() + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e)))?; + let Some(item) = out.item() else { + return Ok((None, None)); + }; + let st = item + .get("json") + .and_then(|v| v.as_s().ok()) + .and_then(|j| serde_json::from_str(j).ok()); + let v = item + .get("v") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + Ok((st, Some(v))) } -pub async fn set_status(dynamo: &Dynamo, table: &str, team_id: &str, st: &Status) { - let _ = dynamo - .put_item() - .table_name(table) - .item("pk", A::S(map_pk(team_id))) - .item("sk", A::S(STATUS_SK.into())) - .item("json", A::S(serde_json::to_string(st).unwrap_or_default())) - .item("state", A::S(st.state.clone())) - .item("at", A::N(st.at.to_string())) - .send() - .await; +pub async fn status(dynamo: &Dynamo, table: &str, team_id: &str) -> Option { + read_status(dynamo, table, team_id).await.ok()?.0 +} + +/// What [`update_status`] did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Updated { + /// The new status was written. + Written(Status), + /// The change didn't apply to the status as it is, which is kept. + Kept(Option), } -/// Marks a build queued: once (a build queued or running is not queued -/// again unless stuck), or always with `force`. `Ok(true)`: send the message. -pub async fn mark_queued( +/// Changes the status with `change` (given the status as it is, it returns +/// the new one, or `None` to leave it), written only if nobody wrote it in +/// between: each write carries the next version, conditioned on the one it +/// read, and a write that lost the race reads again and asks `change` again. +pub async fn update_status( dynamo: &Dynamo, table: &str, team_id: &str, - force: bool, -) -> Result { - let now = chrono::Utc::now().timestamp(); - let st = Status { - state: "queued".into(), - at: now, - step: "Waiting to start".into(), - error: String::new(), - }; - let mut put = dynamo - .put_item() - .table_name(table) - .item("pk", A::S(map_pk(team_id))) - .item("sk", A::S(STATUS_SK.into())) - .item("json", A::S(serde_json::to_string(&st).unwrap_or_default())) - .item("state", A::S("queued".into())) - .item("at", A::N(now.to_string())); - if !force { - put = put - .condition_expression( - "attribute_not_exists(sk) OR NOT (#st IN (:q, :b)) OR #at < :cutoff", + change: impl Fn(Option<&Status>) -> Option, +) -> Result { + for _ in 0..5 { + let (cur, version) = read_status(dynamo, table, team_id).await?; + let Some(next) = change(cur.as_ref()) else { + return Ok(Updated::Kept(cur)); + }; + let v = version.unwrap_or(0); + let mut put = dynamo + .put_item() + .table_name(table) + .item("pk", A::S(map_pk(team_id))) + .item("sk", A::S(STATUS_SK.into())) + .item( + "json", + A::S(serde_json::to_string(&next).unwrap_or_default()), ) - .expression_attribute_names("#st", "state") - .expression_attribute_names("#at", "at") - .expression_attribute_values(":q", A::S("queued".into())) - .expression_attribute_values(":b", A::S("building".into())) - .expression_attribute_values(":cutoff", A::N((now - STALE_SECS).to_string())); - } - match put.send().await { - Ok(_) => Ok(true), - Err(e) => { - if e.as_service_error() - .map(|se| se.is_conditional_check_failed_exception()) - .unwrap_or(false) + .item("state", A::S(next.state.clone())) + .item("at", A::N(next.at.to_string())) + .item("v", A::N((v + 1).to_string())); + put = match version { + None => put.condition_expression("attribute_not_exists(pk)"), + Some(0) => put + .condition_expression("attribute_not_exists(#v)") + .expression_attribute_names("#v", "v"), + Some(v) => put + .condition_expression("#v = :v") + .expression_attribute_names("#v", "v") + .expression_attribute_values(":v", A::N(v.to_string())), + }; + match put.send().await { + Ok(_) => return Ok(Updated::Written(next)), + Err(e) + if e.as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) => { - Ok(false) - } else { - Err(format!( + continue + } + Err(e) => { + return Err(format!( "{}", aws_sdk_dynamodb::error::DisplayErrorContext(e) )) } } } + Err("the map's build status kept changing; try again".into()) +} + +/// Asks for a build: `Ok(Ok(new))` when it is queued (send its message), +/// `Ok(Err(running))` when a build is already queued or running for the +/// team, which stands. +pub async fn queue_build( + dynamo: &Dynamo, + table: &str, + team_id: &str, +) -> Result>, String> { + let now = chrono::Utc::now().timestamp(); + let build = format!("{:032x}", rand::random::()); + match update_status(dynamo, table, team_id, |cur| queue_next(cur, now, &build)).await? { + Updated::Written(s) => Ok(Ok(s)), + Updated::Kept(cur) => Ok(Err(cur)), + } } pub fn gzip(bytes: &[u8]) -> Vec { @@ -203,6 +398,15 @@ pub fn gunzip(bytes: &[u8], max: usize) -> Option> { /// The team's map as built, if any. Only ever the team's own key. pub async fn load_graph(s3: &aws_sdk_s3::Client, bucket: &str, team_id: &str) -> Option { + load_graph_dated(s3, bucket, team_id).await.map(|(g, _)| g) +} + +/// The team's map and when it was written (unix seconds, 0 if not known). +pub async fn load_graph_dated( + s3: &aws_sdk_s3::Client, + bucket: &str, + team_id: &str, +) -> Option<(Value, i64)> { let obj = s3 .get_object() .bucket(bucket) @@ -210,10 +414,32 @@ pub async fn load_graph(s3: &aws_sdk_s3::Client, bucket: &str, team_id: &str) -> .send() .await .ok()?; + let at = obj.last_modified().map(|t| t.secs()).unwrap_or(0); let bytes = obj.body.collect().await.ok()?.into_bytes(); let json = gunzip(&bytes, MAX_GRAPH_BYTES)?; let v: Value = serde_json::from_slice(&json).ok()?; - (v["schema"] == GRAPH_SCHEMA).then_some(v) + (v["schema"] == GRAPH_SCHEMA).then_some((v, at)) +} + +/// When the team's map was written (unix seconds, 0 if not known), without +/// reading it; `None` when there is no map. +pub async fn graph_written_at(s3: &aws_sdk_s3::Client, bucket: &str, team_id: &str) -> Option { + let head = s3 + .head_object() + .bucket(bucket) + .key(graph_key(team_id)) + .send() + .await + .ok()?; + Some(head.last_modified().map(|t| t.secs()).unwrap_or(0)) +} + +/// How many repositories a built map covers. +pub fn repo_count(graph: &Value) -> u32 { + graph["coderhelm"]["repos"] + .as_object() + .map(|m| m.len() as u32) + .unwrap_or(0) } /// Whether the team has a built map, without reading it (Chat offers the @@ -1046,6 +1272,90 @@ fn check_at(schema: &Value, v: &Value, at: &str, out: &mut Vec) { mod tests { use super::*; + #[test] + fn one_build_at_a_time() { + let now = 10_000; + let first = queue_next(None, now, "b1").unwrap(); + assert_eq!( + (first.state.as_str(), first.build.as_str()), + ("queued", "b1") + ); + // A second ask while it is queued, then while it runs: refused. + assert!(queue_next(Some(&first), now + 3, "b2").is_none()); + let running = take_turn(Some(&first), "b1", 0, now + 5).unwrap(); + assert!(queue_next(Some(&running), now + 8, "b3").is_none()); + // Stuck past STALE_SECS: a new build may replace it. + assert!(queue_next(Some(&running), now + 5 + STALE_SECS + 1, "b4").is_some()); + // Finished or failed: a new build, keeping when the last map was made. + let done = finished(Some(&running), "b1", 12, "", now + 300).unwrap(); + assert_eq!((done.built, done.built_repos), (now + 300, 12)); + let again = queue_next(Some(&done), now + 400, "b5").unwrap(); + assert_eq!( + (again.built, again.built_repos, again.repos), + (now + 300, 12, 12) + ); + let f = failed(Some(&again), "b5", "GitHub didn't answer", now + 401).unwrap(); + assert!(queue_next(Some(&f), now + 402, "b6").is_some()); + } + + #[test] + fn each_message_takes_its_own_turn_once() { + let now = 10_000; + let q = queue_next(None, now, "b1").unwrap(); + // Another build's message, or a turn out of order: nothing. + assert!(take_turn(Some(&q), "other", 0, now).is_none()); + assert!(take_turn(Some(&q), "b1", 1, now).is_none()); + let t1 = take_turn(Some(&q), "b1", 0, now).unwrap(); + assert_eq!((t1.state.as_str(), t1.turn), ("building", 1)); + // The same start message delivered again: skipped. + assert!(take_turn(Some(&t1), "b1", 0, now + 2).is_none()); + let t2 = take_turn(Some(&t1), "b1", 1, now + 60).unwrap(); + assert_eq!(t2.turn, 2); + assert!(take_turn(Some(&t2), "b1", 1, now + 61).is_none()); + // Delivered again after its worker went quiet past the lease: taken again. + assert!(take_turn(Some(&t2), "b1", 1, now + 60 + LEASE_SECS + 1).is_some()); + // A message from before build ids carries on a build without one. + let legacy = Status { + state: "building".into(), + at: now, + turn: 0, + ..Default::default() + }; + assert!(take_turn(Some(&legacy), "", 0, now).is_none()); + assert!(take_turn( + Some(&Status { + state: "queued".into(), + ..legacy.clone() + }), + "", + 0, + now + ) + .is_some()); + // Progress and the end only for the build that is running. + assert!(progress(Some(&t2), "other", Some("parts"), "x", now).is_none()); + assert_eq!( + progress(Some(&t2), "b1", Some("parts"), "x", now) + .unwrap() + .stage, + "parts" + ); + assert_eq!( + progress(Some(&t2), "b1", None, "y", now).unwrap().stage, + "reading" + ); + assert!(finished(Some(&t2), "other", 3, "", now).is_none()); + } + + #[test] + fn the_estimate_grows_with_the_repositories() { + assert_eq!(estimate_secs(0), estimate_secs(1)); + assert_eq!(estimate_secs(1), (4 * 60, 8 * 60)); + assert_eq!(estimate_secs(12), (15 * 60, 30 * 60)); + let (low, high) = estimate_secs(200); + assert!(low <= high && high <= STALE_SECS); + } + /// The map Floorplan builds for the made-up harbor app (a web app and an /// API in two repositories), written by /// services/worker/floorplan/make-fixture.mjs and checked against the diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index d1e2cf37b..04849fb1e 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -717,6 +717,14 @@ pub struct AppMapMessage { pub repo: String, #[serde(default)] pub step: String, + /// The build this message belongs to (`common::app_map::Status::build`); + /// empty on a message from before builds had ids. + #[serde(default)] + pub build: String, + /// Which turn of the build this message is: the worker takes it once + /// (`common::app_map::take_turn`), so a duplicate does nothing. + #[serde(default)] + pub turn: u32, } /// A coalesced release-tag sweep. Carries only routing + the batch clock; the diff --git a/services/gateway/src/fake_aws.rs b/services/gateway/src/fake_aws.rs index c7a422307..5685f7984 100644 --- a/services/gateway/src/fake_aws.rs +++ b/services/gateway/src/fake_aws.rs @@ -1,5 +1,6 @@ //! A small in-process stand-in for the AWS services sign-in calls (DynamoDB, -//! Cognito and KMS), so tests run the real handlers end to end against +//! Cognito and KMS) and the App map's (SQS messages it records, and S3 with +//! no objects), so tests run the real handlers end to end against //! records they set up. It speaks the services' JSON protocols on a local //! port; the SDK clients are pointed at it with an endpoint override. //! @@ -17,7 +18,7 @@ use axum::{ body::Bytes, extract::State, - http::{HeaderMap, StatusCode}, + http::{HeaderMap, Method, StatusCode, Uri}, response::{IntoResponse, Response}, Router, }; @@ -49,9 +50,21 @@ pub struct Store { /// Every transaction is cancelled (as when another write changed an /// item it checks in between). cancel_transactions: std::sync::atomic::AtomicBool, + /// SQS messages sent: `(queue url, body)`. + sent: Mutex>, } impl Store { + /// The bodies of the SQS messages sent so far. + pub fn sent(&self) -> Vec { + self.sent + .lock() + .unwrap() + .iter() + .map(|(_, b)| b.clone()) + .collect() + } + /// Cancels every transaction from now on. pub fn cancel_transactions(&self) { self.cancel_transactions @@ -244,18 +257,48 @@ fn ok(v: Value) -> Response { .into_response() } -async fn handle(State(store): State>, headers: HeaderMap, body: Bytes) -> Response { +async fn handle( + State(store): State>, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { let target = headers .get("x-amz-target") .and_then(|v| v.to_str().ok()) .unwrap_or("") .to_string(); + // S3 holds no objects: a read of one is not found. + if target.is_empty() && matches!(method, Method::GET | Method::HEAD) { + return ( + StatusCode::NOT_FOUND, + [("content-type", "application/xml")], + format!( + "NoSuchKeyno {}", + uri.path() + ), + ) + .into_response(); + } let req: Value = serde_json::from_slice(&body).unwrap_or(Value::Null); let (service, op) = target.split_once('.').unwrap_or(("", "")); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match service { "DynamoDB_20120810" => dynamo(&store, op, &req), "AWSCognitoIdentityProviderService" => cognito(&store, op, &req), "TrentService" => kms(&store, op, &req), + "AmazonSQS" if op == "SendMessage" => { + let mut sent = store.sent.lock().unwrap(); + sent.push(( + req["QueueUrl"].as_str().unwrap_or("").to_string(), + req["MessageBody"].as_str().unwrap_or("").to_string(), + )); + let body = req["MessageBody"].as_str().unwrap_or(""); + ok(json!({ + "MessageId": format!("m-{}", sent.len()), + "MD5OfMessageBody": format!("{:x}", md5::compute(body.as_bytes())), + })) + } // Services without a JSON target (SES's REST API: the emails a flow // sends) are accepted and not checked. "" => ok(json!({ "MessageId": "stand-in" })), @@ -892,6 +935,8 @@ pub fn state(url: &str) -> Arc { users_table_name: "users".into(), settings_table_name: "settings".into(), repos_table_name: "repos".into(), + bucket_name: "bucket".into(), + ticket_queue_url: format!("{url}/queue/tickets"), cognito_user_pool_id: "pool".into(), cognito_client_id: "client".into(), secrets_key_id: "key".into(), diff --git a/services/gateway/src/routes/app_map.rs b/services/gateway/src/routes/app_map.rs index 4407d0e14..31146cfd0 100644 --- a/services/gateway/src/routes/app_map.rs +++ b/services/gateway/src/routes/app_map.rs @@ -26,24 +26,34 @@ use tracing::{error, info}; use crate::models::Claims; use crate::AppState; -/// Queues a build: once (`force` false) or again (an admin). -async fn queue_build(state: &AppState, team_id: &str, force: bool) -> bool { +/// Asks for a build, one at a time per team: `Ok(new)` when it is queued and +/// its message sent, `Err(running)` when a build is already queued or +/// running (that build stands and nothing is sent; `None` when the status +/// couldn't be read or the message couldn't be sent, and the build is +/// marked failed). +pub async fn queue_build( + state: &AppState, + team_id: &str, +) -> Result> { let table = &state.config.settings_table_name; - match am::mark_queued(&state.dynamo, table, team_id, force).await { - Ok(true) => {} - Ok(false) => return false, + let st = match am::queue_build(&state.dynamo, table, team_id).await { + Ok(Ok(st)) => st, + Ok(Err(running)) => { + info!(team_id, "App map: a build is already queued or running"); + return Err(running); + } Err(e) => { error!("app map: could not mark a build queued: {e}"); - return false; + return Err(None); } - } + }; let msg = crate::models::WorkerMessage::AppMap(crate::models::AppMapMessage { team_id: team_id.to_string(), + build: st.build.clone(), + turn: 0, ..Default::default() }); - let Ok(body) = serde_json::to_string(&msg) else { - return false; - }; + let body = serde_json::to_string(&msg).unwrap_or_default(); match state .sqs .send_message() @@ -54,23 +64,17 @@ async fn queue_build(state: &AppState, team_id: &str, force: bool) -> bool { { Ok(_) => { info!(team_id, "App map: build queued"); - true + Ok(st) } Err(e) => { error!("app map: could not queue a build: {e}"); - am::set_status( - &state.dynamo, - table, - team_id, - &am::Status { - state: "failed".into(), - at: chrono::Utc::now().timestamp(), - step: String::new(), - error: "The build could not be started. Try again in a moment.".into(), - }, - ) + let now = chrono::Utc::now().timestamp(); + let why = "The build couldn't be started. Try again in a moment."; + let _ = am::update_status(&state.dynamo, table, team_id, |cur| { + am::failed(cur, &st.build, why, now) + }) .await; - false + Err(None) } } } @@ -78,8 +82,7 @@ async fn queue_build(state: &AppState, team_id: &str, force: bool) -> bool { /// What the page shows about the build: `building` while there is no map /// yet, else `ready` (with `updating` while an update runs). pub fn shown_state(st: Option<&am::Status>, has_map: bool, now: i64) -> (&'static str, bool) { - let running = - st.is_some_and(|s| matches!(s.state.as_str(), "queued" | "building") && !s.is_stale(now)); + let running = st.is_some_and(|s| s.is_running(now)); match (has_map, st) { (true, _) => ("ready", running), (false, _) if running => ("building", true), @@ -89,6 +92,59 @@ pub fn shown_state(st: Option<&am::Status>, has_map: bool, now: i64) -> (&'stati } } +/// The map there now, as far as the status page needs it: when it was +/// written and how many repositories it covers. +#[derive(Debug, Clone, Copy, Default)] +pub struct MapFacts { + pub has_map: bool, + pub written_at: i64, + pub repos: u32, +} + +/// The build status the page reads: the state, the running build's step, +/// when it started and how long it usually takes for `team_repos` +/// repositories, and when the map there now was built. +pub fn status_view(st: Option<&am::Status>, map: MapFacts, team_repos: u32, now: i64) -> Value { + let (shown, updating) = shown_state(st, map.has_map, now); + let s = st.cloned().unwrap_or_default(); + let running = updating; + let repos = if s.repos > 0 { s.repos } else { team_repos }; + let (low, high) = am::estimate_secs(repos); + let built_at = if s.built > 0 { s.built } else { map.written_at }; + let built_repos = if s.built_repos > 0 { + s.built_repos + } else { + map.repos + }; + json!({ + "state": shown, + "updating": updating, + "step": if running { s.step.clone() } else { String::new() }, + // Kept after a build stops, so a failure can say where it stopped. + "stage": s.stage, + // How the last build ended (`failed` with a map there: an update + // that didn't finish, and the map is the one before it). + "last_build": s.state, + "note": s.error, + "started_at": if running { s.started.max(0) } else { 0 }, + "repos": repos, + "estimate": if running { json!({ "low_secs": low, "high_secs": high }) } else { Value::Null }, + "built_at": if map.has_map { built_at } else { 0 }, + "built_repos": if map.has_map { built_repos } else { 0 }, + "now": now, + "floorplan": am::FLOORPLAN_VERSION.trim(), + }) +} + +/// The team's turned-on repositories, counted for the estimate (0 when +/// they couldn't be read). +async fn team_repo_count(state: &AppState, team_id: &str) -> u32 { + super::repo_setup::team_repos(state, team_id) + .await + .map(|r| r.len() as u32) + .unwrap_or(0) +} + #[derive(Deserialize, Default)] pub struct MapQuery { #[serde(default)] @@ -101,6 +157,9 @@ pub struct MapQuery { pub recent: Option, #[serde(default)] pub health: Option, + /// `graph=0`: the build status only, for a page watching a build. + #[serde(default)] + pub graph: Option, } /// GET /api/app-map — the build status and the map, ready for the viewer. @@ -110,24 +169,55 @@ pub async fn get_map( Query(q): Query, ) -> Result, StatusCode> { let table = &state.config.settings_table_name; - let (graph, st) = tokio::join!( - am::load_graph(&state.s3, &state.config.bucket_name, &claims.team_id), + let bucket = &state.config.bucket_name; + let status_only = q.graph == Some(0); + let (graph, written, mut st) = tokio::join!( + async { + if status_only { + None + } else { + am::load_graph_dated(&state.s3, bucket, &claims.team_id).await + } + }, + async { + if status_only { + am::graph_written_at(&state.s3, bucket, &claims.team_id).await + } else { + None + } + }, am::status(&state.dynamo, table, &claims.team_id), ); let now = chrono::Utc::now().timestamp(); - let (mut shown, mut updating) = shown_state(st.as_ref(), graph.is_some(), now); - if shown == "not_built" && queue_build(&state, &claims.team_id, false).await { - shown = "building"; - updating = true; + let facts = match (&graph, written) { + (Some((g, at)), _) => MapFacts { + has_map: true, + written_at: *at, + repos: am::repo_count(g), + }, + (None, Some(at)) => MapFacts { + has_map: true, + written_at: at, + repos: st.as_ref().map(|s| s.built_repos).unwrap_or(0), + }, + (None, None) => MapFacts::default(), + }; + // The first visit starts the first build. + if shown_state(st.as_ref(), facts.has_map, now).0 == "not_built" { + match queue_build(&state, &claims.team_id).await { + Ok(new) => st = Some(new), + Err(Some(running)) => st = Some(running), + Err(None) => st = am::status(&state.dynamo, table, &claims.team_id).await, + } } - let status = json!({ - "state": shown, - "updating": updating, - "step": st.as_ref().map(|s| s.step.clone()).unwrap_or_default(), - "note": st.as_ref().map(|s| s.error.clone()).unwrap_or_default(), - "floorplan": am::FLOORPLAN_VERSION.trim(), - }); - let Some(graph) = graph else { + let running = st.as_ref().is_some_and(|s| s.is_running(now)); + let team_repos = if running && st.as_ref().is_some_and(|s| s.repos == 0) { + team_repo_count(&state, &claims.team_id).await + } else { + 0 + }; + let status = status_view(st.as_ref(), facts, team_repos, now); + let Some((graph, _)) = graph else { return Ok(Json(json!({ "status": status, "graph": Value::Null }))); }; let days = 14; @@ -232,16 +322,43 @@ pub async fn search( } /// POST /api/app-map/rebuild — admin. Builds the map again (Floorplan's -/// refresh carries every description that still fits). +/// refresh carries every description that still fits), one build at a time: +/// while one is queued or running it answers 409 with that build's status +/// and starts nothing. pub async fn rebuild( State(state): State>, Extension(claims): Extension, -) -> Result { +) -> Result<(StatusCode, Json), StatusCode> { claims.require_role(3)?; - if queue_build(&state, &claims.team_id, true).await { - Ok(StatusCode::ACCEPTED) - } else { - Err(StatusCode::BAD_GATEWAY) + let team = &claims.team_id; + let written = am::graph_written_at(&state.s3, &state.config.bucket_name, team).await; + let facts = |s: &am::Status| MapFacts { + has_map: written.is_some(), + written_at: written.unwrap_or(0), + repos: s.built_repos, + }; + let now = chrono::Utc::now().timestamp(); + match queue_build(&state, team).await { + Ok(st) => { + let repos = if st.repos == 0 { + team_repo_count(&state, team).await + } else { + 0 + }; + Ok(( + StatusCode::ACCEPTED, + Json(json!({ "status": status_view(Some(&st), facts(&st), repos, now) })), + )) + } + Err(Some(running)) => Ok(( + StatusCode::CONFLICT, + Json(json!({ + "error": "The map is already being built. This build carries on; there is no need to start another.", + "code": "already_building", + "status": status_view(Some(&running), facts(&running), 0, now), + })), + )), + Err(None) => Err(StatusCode::BAD_GATEWAY), } } @@ -594,6 +711,194 @@ mod tests { ); } + fn admin(team: &str) -> Claims { + Claims { + sub: "USER#harbor-admin".into(), + team_id: team.into(), + email: "admin@harbor.example".into(), + role: "admin".into(), + github_login: None, + aud: "coderhelm-dashboard".into(), + exp: 9999999999, + iat: 1000000000, + support_view: None, + custom: None, + api_key: None, + held: false, + via_okta: false, + okta_sub: None, + entra: None, + } + } + + async fn press(state: &Arc, team: &str) -> (StatusCode, Value) { + let (code, Json(body)) = rebuild(State(state.clone()), Extension(admin(team))) + .await + .unwrap(); + (code, body) + } + + #[tokio::test] + async fn a_second_build_is_refused_while_one_is_queued_or_running() { + let f = crate::fake_aws::start().await; + let state = crate::fake_aws::state(&f.url); + let team = "TEAM#harbor"; + // Three presses of "Build the map again" within seconds: one build. + let (first, body) = press(&state, team).await; + assert_eq!(first, StatusCode::ACCEPTED); + assert_eq!(body["status"]["state"], "building"); + let started = body["status"]["started_at"].as_i64().unwrap(); + assert!(started > 0); + for _ in 0..2 { + let (code, body) = press(&state, team).await; + assert_eq!(code, StatusCode::CONFLICT); + assert_eq!(body["code"], "already_building"); + // The running build's own state comes back. + assert_eq!(body["status"]["state"], "building"); + assert_eq!(body["status"]["started_at"], started); + } + let sent = f.store.sent(); + assert_eq!( + sent.len(), + 1, + "one build message, not one per press: {sent:?}" + ); + let msg: Value = serde_json::from_str(&sent[0]).unwrap(); + let st = am::status(&state.dynamo, "settings", team).await.unwrap(); + assert_eq!(msg["build"], json!(st.build)); + assert_eq!(msg["turn"], 0); + + // The worker takes the start message once; the same message again + // (or another build's) is skipped. + let now = chrono::Utc::now().timestamp(); + let take = |turn: u32, build: String| { + let dynamo = state.dynamo.clone(); + async move { + am::update_status(&dynamo, "settings", team, |cur| { + am::take_turn(cur, &build, turn, now) + }) + .await + .unwrap() + } + }; + assert!(matches!( + take(0, st.build.clone()).await, + am::Updated::Written(_) + )); + assert!(matches!( + take(0, st.build.clone()).await, + am::Updated::Kept(_) + )); + assert!(matches!( + take(0, "another".into()).await, + am::Updated::Kept(_) + )); + // Still running: still refused. + assert_eq!(press(&state, team).await.0, StatusCode::CONFLICT); + // Once it has finished, a new build may start. + am::update_status(&state.dynamo, "settings", team, |cur| { + am::finished(cur, &st.build, 2, "", now) + }) + .await + .unwrap(); + assert_eq!(press(&state, team).await.0, StatusCode::ACCEPTED); + assert_eq!(f.store.sent().len(), 2); + // Another team's build is its own. + assert_eq!(press(&state, "TEAM#marina").await.0, StatusCode::ACCEPTED); + } + + #[tokio::test] + async fn presses_at_the_same_moment_still_start_one_build() { + let f = crate::fake_aws::start().await; + let state = crate::fake_aws::state(&f.url); + let team = "TEAM#harbor"; + let presses = (0..6).map(|_| press(&state, team)); + let codes: Vec = futures::future::join_all(presses) + .await + .into_iter() + .map(|(c, _)| c) + .collect(); + assert_eq!( + codes.iter().filter(|c| **c == StatusCode::ACCEPTED).count(), + 1, + "{codes:?}" + ); + assert_eq!(f.store.sent().len(), 1); + } + + #[test] + fn the_status_says_when_it_started_how_long_it_takes_and_when_the_map_was_built() { + let now = 50_000; + let q = am::queue_next(None, now - 120, "b1").unwrap(); + let running = am::take_turn(Some(&q), "b1", 0, now - 100).unwrap(); + let running = am::progress( + Some(&running), + "b1", + Some("parts"), + "Working out the app's parts", + now - 10, + ) + .unwrap(); + let v = status_view(Some(&running), MapFacts::default(), 12, now); + assert_eq!( + v, + json!({ + "state": "building", "updating": true, "step": "Working out the app's parts", "stage": "parts", + "last_build": "building", "note": "", "started_at": now - 120, "repos": 12, + "estimate": {"low_secs": 15 * 60, "high_secs": 30 * 60}, + "built_at": 0, "built_repos": 0, "now": now, "floorplan": am::FLOORPLAN_VERSION.trim(), + }) + ); + // Built: when, and from how many repositories; nothing running. + let done = am::finished(Some(&running), "b1", 12, "", now - 5).unwrap(); + let facts = MapFacts { + has_map: true, + written_at: now - 6, + repos: 12, + }; + let v = status_view(Some(&done), facts, 0, now); + assert_eq!( + (v["state"].as_str(), v["updating"].as_bool()), + (Some("ready"), Some(false)) + ); + assert_eq!( + (v["built_at"].as_i64(), v["built_repos"].as_u64()), + (Some(now - 5), Some(12)) + ); + assert_eq!( + (v["started_at"].as_i64(), v["estimate"].is_null()), + (Some(0), true) + ); + // A map from before the status kept these: the map's own date and repositories. + let v = status_view( + Some(&am::Status { + state: "ready".into(), + at: 1, + ..Default::default() + }), + facts, + 0, + now, + ); + assert_eq!( + (v["built_at"].as_i64(), v["built_repos"].as_u64()), + (Some(now - 6), Some(12)) + ); + // Failed: the reason in plain words. + let f = am::failed( + Some(&running), + "b1", + "GitHub didn't answer for harbor-api.", + now, + ) + .unwrap(); + let v = status_view(Some(&f), MapFacts::default(), 0, now); + assert_eq!( + (v["state"].as_str(), v["note"].as_str()), + (Some("failed"), Some("GitHub didn't answer for harbor-api.")) + ); + } + #[test] fn findings_and_plans_read_into_overlay_items() { let f = json!({"id": "f1", "repo": "harbor/harbor-api", "manifest": "package.json", "tier": "P1", diff --git a/services/worker/src/passes/app_map.rs b/services/worker/src/passes/app_map.rs index 7f7332dcb..67ab120b3 100644 --- a/services/worker/src/passes/app_map.rs +++ b/services/worker/src/passes/app_map.rs @@ -575,27 +575,64 @@ async fn s3_put(state: &WorkerState, key: &str, body: Vec) -> Result<(), Str .map_err(|e| format!("app map: could not keep {key}: {e}")) } -async fn set(state: &WorkerState, team_id: &str, st: &str, step: &str, error: &str) { - am::set_status( +/// Changes the running build's status; `Err` when `build` is no longer the +/// build running (a newer one replaced it), and this one stops. +async fn change( + state: &WorkerState, + team_id: &str, + f: impl Fn(Option<&am::Status>, i64) -> Option, +) -> Result<(), String> { + let now = chrono::Utc::now().timestamp(); + match am::update_status( &state.dynamo, &state.config.settings_table_name, team_id, - &am::Status { - state: st.into(), - at: chrono::Utc::now().timestamp(), - step: step.into(), - error: error.into(), - }, + |cur| f(cur, now), ) - .await; + .await? + { + am::Updated::Written(_) => Ok(()), + am::Updated::Kept(_) => Err("this build is no longer the one running".into()), + } } -/// Queues the next step (or a whole new build with `step` empty). -pub async fn queue(state: &WorkerState, team_id: &str, step: &str, delay_secs: i32) -> bool { +/// The build's step, in plain words (and its stage, one of `am::STAGES`). +async fn progress( + state: &WorkerState, + team_id: &str, + build: &str, + stage: Option<&str>, + step: &str, +) -> Result<(), String> { + change(state, team_id, |cur, now| { + am::progress(cur, build, stage, step, now) + }) + .await +} + +/// The message's turn of the build, if it is the build's next one: `None` +/// for a second message about a build already running, a message delivered +/// twice, or a build a newer one replaced, which the worker skips. +pub fn turn_to_take(msg: &AppMapMessage, cur: Option<&am::Status>, now: i64) -> Option { + am::take_turn(cur, &msg.build, msg.turn, now) +} + +/// Queues the next step of a build (or a whole new build with `step` empty +/// and `turn` 0). +pub async fn queue( + state: &WorkerState, + team_id: &str, + step: &str, + build: &str, + turn: u32, + delay_secs: i32, +) -> bool { let msg = crate::models::WorkerMessage::AppMap(AppMapMessage { team_id: team_id.to_string(), repo: String::new(), step: step.to_string(), + build: build.to_string(), + turn, }); let Ok(body) = serde_json::to_string(&msg) else { return false; @@ -617,41 +654,69 @@ pub async fn after_push(state: &WorkerState, team_id: &str) { if s3_get(state, &am::state_key(team_id)).await.is_none() { return; } - if let Ok(true) = am::mark_queued( - &state.dynamo, - &state.config.settings_table_name, - team_id, - false, - ) - .await + // A build already queued or running covers this push. + if let Ok(Ok(st)) = + am::queue_build(&state.dynamo, &state.config.settings_table_name, team_id).await { - queue(state, team_id, "", 120).await; + queue(state, team_id, "", &st.build, 0, 120).await; } } -/// One step of a team's map. +/// One step of a team's map: the message's turn of its build, taken once. pub async fn run(state: &WorkerState, msg: AppMapMessage) { let team_id = msg.team_id.clone(); - let call = step(state, msg); + let now = chrono::Utc::now().timestamp(); + let taken = am::update_status( + &state.dynamo, + &state.config.settings_table_name, + &team_id, + |cur| turn_to_take(&msg, cur, now), + ) + .await; + let st = match taken { + Ok(am::Updated::Written(st)) => st, + Ok(am::Updated::Kept(cur)) => { + info!( + team_id, + build = %msg.build, + turn = msg.turn, + running = %cur.map(|c| c.build).unwrap_or_default(), + "App map: not the build's next turn (a duplicate, or a build already running), skipped" + ); + return; + } + Err(e) => { + warn!(team_id, error = %e, "App map: the build status couldn't be read"); + return; + } + }; + let build = st.build.clone(); + let call = step(state, msg, &build, st.turn); if let Err(e) = common::usage::with_feature(common::usage::feature::APP_MAP, call).await { warn!(team_id, error = %e, "App map: the step failed"); - set(state, &team_id, "failed", "", &e).await; + let _ = change(state, &team_id, |cur, now| am::failed(cur, &build, &e, now)).await; } } -async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { +async fn step( + state: &WorkerState, + msg: AppMapMessage, + build: &str, + turn: u32, +) -> Result<(), String> { let team_id = msg.team_id.as_str(); let repos = super::plan::fetch_team_repos(state, team_id).await; if repos.is_empty() { - set( - state, - team_id, - "ready", - "", - "No repositories are turned on for this team.", - ) + return change(state, team_id, |cur, now| { + am::finished( + cur, + build, + 0, + "No repositories are turned on for this team.", + now, + ) + }) .await; - return Ok(()); } let installation = super::code_graph::team_installation_id(state, team_id) .await @@ -686,9 +751,11 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { } let have_map = s3_get(state, &am::graph_key(team_id)).await.is_some(); if have_map && heads == job.built { - set(state, team_id, "ready", "", "").await; info!(team_id, "App map: no default branch moved, nothing to redo"); - return Ok(()); + return change(state, team_id, |cur, now| { + am::finished(cur, build, 0, "", now) + }) + .await; } let built = std::mem::take(&mut job.built); job = Job { @@ -698,18 +765,27 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { ..Default::default() }; } - set( - state, - team_id, - "building", - if msg.step.is_empty() { - "Reading the repositories" - } else { - "Building the map" - }, - "", - ) - .await; + if msg.step.is_empty() { + let n = job.heads.len() as u32; + change(state, team_id, |cur, now| { + am::progress( + cur, + build, + Some(am::STAGES[0]), + "Reading the repositories", + now, + ) + .map(|mut s| { + s.repos = n; + s + }) + }) + .await?; + } else { + // The stage stays: putting the map together is part of the one + // before it. + progress(state, team_id, build, None, "Putting the map together").await?; + } // The snapshot: every repository at its head, and the last map's files. let mut budget = MAX_SNAPSHOT_BYTES; @@ -816,14 +892,14 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { match decide(&result, &job) { Next::Architecture { job: name, item } => { job.arch_attempts += 1; - set( + progress( state, team_id, - "building", - "Working out the app's parts", - "", + build, + Some(am::STAGES[1]), + "Finding the parts and how they connect", ) - .await; + .await?; // What CoderHelm already knows about each repository (its code // map) helps where Floorplan's scan summary is thin. let mut known = String::new(); @@ -886,18 +962,18 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { .ok_or("the map's parts couldn't be worked out this time")?; job.answers .insert("floorplan/architecture.json".into(), answer); - next_step(state, team_id, &job).await + next_step(state, team_id, &job, build, turn).await } Next::Describe(keys) => { job.desc_attempts += 1; - set( + progress( state, team_id, - "building", - "Describing files and endpoints", - "", + build, + Some(am::STAGES[2]), + "Describing each part, file and endpoint", ) - .await; + .await?; let style = result["describe"]["style"] .as_str() .unwrap_or("") @@ -950,7 +1026,7 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { } } } - next_step(state, team_id, &job).await + next_step(state, team_id, &job, build, turn).await } Next::Stop(why) => { s3_put( @@ -990,7 +1066,11 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { serde_json::to_vec(&job).unwrap_or_default(), ) .await?; - set(state, team_id, "ready", "", "").await; + let n = job.heads.len() as u32; + change(state, team_id, |cur, now| { + am::finished(cur, build, n, "", now) + }) + .await?; info!( team_id, files = g["files"].as_array().map(|a| a.len()).unwrap_or(0), @@ -1001,14 +1081,20 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { } } -async fn next_step(state: &WorkerState, team_id: &str, job: &Job) -> Result<(), String> { +async fn next_step( + state: &WorkerState, + team_id: &str, + job: &Job, + build: &str, + turn: u32, +) -> Result<(), String> { s3_put( state, &am::job_key(team_id), serde_json::to_vec(job).unwrap_or_default(), ) .await?; - if queue(state, team_id, "build", 0).await { + if queue(state, team_id, "build", build, turn, 0).await { Ok(()) } else { Err("the next step couldn't be queued".into()) @@ -1019,6 +1105,41 @@ async fn next_step(state: &WorkerState, team_id: &str, job: &Job) -> Result<(), mod tests { use super::*; + #[test] + fn a_duplicate_message_for_a_build_already_running_is_skipped() { + let now = 10_000; + let msg = |build: &str, step: &str, turn: u32| AppMapMessage { + team_id: "TEAM#harbor".into(), + step: step.into(), + build: build.into(), + turn, + ..Default::default() + }; + let queued = am::queue_next(None, now, "b1").unwrap(); + // The build's start message runs once. + let running = turn_to_take(&msg("b1", "", 0), Some(&queued), now).unwrap(); + assert_eq!((running.state.as_str(), running.turn), ("building", 1)); + // The same start message again, or a start for another build while + // this one runs: skipped. + assert_eq!( + turn_to_take(&msg("b1", "", 0), Some(&running), now + 3), + None + ); + assert_eq!( + turn_to_take(&msg("b2", "", 0), Some(&running), now + 3), + None + ); + // The build's next step runs once, too. + let next = turn_to_take(&msg("b1", "build", 1), Some(&running), now + 60).unwrap(); + assert_eq!(next.turn, 2); + assert_eq!( + turn_to_take(&msg("b1", "build", 1), Some(&next), now + 61), + None + ); + // No status at all (nothing asked for a build): nothing runs. + assert_eq!(turn_to_take(&msg("b1", "", 0), None, now), None); + } + #[test] fn the_steps_follow_floorplans_workflow() { let job = Job::default(); From eb1624bc82dafca61c6c472e396421cee2ef3ad5 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 22 Nov 2026 15:45:17 -0500 Subject: [PATCH 2/2] Pin the dashboard to the App map menu, build and layout release (dashboard #470) --- selfhost/versions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selfhost/versions.json b/selfhost/versions.json index 3f7fbde48..44fb2b5b8 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "1de4e20734d077dfa57b0122619fb030896b42dc" + "dashboardRef": "edaca95fe3d0ce98ac68e2d51f61b3294d6a8cdc" }