diff --git a/docs/app-map.md b/docs/app-map.md index 53578d396..721399caf 100644 --- a/docs/app-map.md +++ b/docs/app-map.md @@ -10,10 +10,19 @@ The App map shows how a team's app fits together across all its repositories. It - `build`: writes the answers and builds, until the build passes and every file and endpoint is described (the workflow's own limits: 4 and 3 attempts). - After a push to a default branch (a code graph update), a team that has a map gets an update queued two minutes later. Floorplan's refresh keeps every description whose file didn't change, so only new or changed files and endpoints are described again. - The map (`floorplan/graph@1`) is kept in the bucket at `app-map/{team}/graph.json.gz`, Floorplan's own files at `state.tgz`, and the step's job at `job.json`; the build status is in the settings table (`AM#{team}`, `STATUS`). +- With each map the worker also writes the page's copy (`view.json.gz`: read-only, Floorplan's checks labelled, stored as JSON with `Content-Encoding: gzip`) and a small index (`index.json.gz`, `common::app_map::MapIndex`: the repositories' folders, every file path on the map, each repository's main part and Floorplan's checks with their places). A map written before these existed gets them from the gateway on its first read. + +## How the page reads it + +- `GET /api/app-map` never reads or sends the whole map. It answers with the build status, a signed GET for the page's copy (`graph_url`, 15 minutes; the browser reads it from the bucket and unzips it), the same bytes through the API for a browser that can't reach the bucket (`graph_fallback`, `GET /api/app-map/graph`, passed on unread), when the map was written (`graph_at`), and CoderHelm's overlays (`overlays`) placed with the index: Recent work (`recent`), and Health (`health.add`, the Floorplan checks to `drop` by id, and the `summary`). The page lays them over its copy (`dashboard/src/lib/app-map-load.ts`, the same as `common::app_map::apply_overlays`) and reads the map again only when `graph_at` changes. +- Recent work reads the plans' "why" eight at a time, for runs that are on the map only; Health reads its four sources at once. +- The data bucket's CORS allows `GET` and `HEAD` from the dashboard's origins (`infra/lib/storage-stack.ts`), next to the uploads' `PUT`. +- `cargo test -p common a_page_view` measures a page view on a made-up 4,000-file map (`APP_MAP_BENCH_GRAPH=` measures a map on disk); `cargo test -p gateway a_page_view_of_a_large_map` does it through the handler. +- Chat and `/mcp` still read the whole map at their first lookup (`load_graph`): one read per question, and their lookups need the files, links and descriptions the index doesn't keep. ## What CoderHelm adds (`common/src/app_map.rs`) -- Recent work and Health, put into the map's own `recent` and `health.issues` fields when the gateway serves it, so Floorplan's viewer shows them natively. CoderHelm's findings are marked `source: "coderhelm"` and link to their pages; Floorplan's own checks are marked `Floorplan check`, and one at the same file and line as a CoderHelm finding is dropped. +- Recent work and Health in the map's own `recent` and `health.issues` fields, laid over the page's copy on the page, so Floorplan's viewer shows them natively. CoderHelm's findings are marked `source: "coderhelm"` and link to their pages; Floorplan's own checks are marked `Floorplan check`, and one at the same file and line as a CoderHelm finding is dropped. - The page's copy: read-only (Floorplan's exported mode), with the sandbox's folder left out. - Lookups for the read API (`/api/app-map/part`, `file`, `screen`, `search`). - The map lookups Chat and `/mcp` share (`common::app_map::Lookups`: `map_overview`, `map_find`, `map_part`, `map_screen`, `map_file`). Chat offers them when the team has a built map and reads the map at the first lookup; a question about how the app fits together gets them first (`chat_understand`). Each lookup is a citable source linking to the App map page focused on its parts, and an answer that used them carries a mini map of those parts (`map` on the answer and its saved message). The App map page's Ask box asks Chat (origin `app_map`), so its questions are kept in the person's chats. On `/mcp` the same lookups are read-only tools under `code:read`. diff --git a/infra/lib/storage-stack.ts b/infra/lib/storage-stack.ts index e15166b02..d0b08bb38 100644 --- a/infra/lib/storage-stack.ts +++ b/infra/lib/storage-stack.ts @@ -108,12 +108,14 @@ export class StorageStack extends cdk.Stack { autoDeleteObjects: !props.cfg.retainData, // Knowledge base files and brain chat attachments are uploaded from // the browser with short-lived signed PUT URLs (bound to the object's - // key, size and type by the gateway); nothing else is allowed. The - // dashboard's origins when known at synth; otherwise any origin, since - // the signed URL itself is the credential. + // key, size and type by the gateway), and the App map page reads the + // team's map with a short-lived signed GET URL (the gateway never + // passes the map itself); nothing else is allowed. The dashboard's + // origins when known at synth; otherwise any origin, since the signed + // URL itself is the credential. cors: [ { - allowedMethods: [s3.HttpMethods.PUT], + allowedMethods: [s3.HttpMethods.PUT, s3.HttpMethods.GET, s3.HttpMethods.HEAD], allowedOrigins: props.cfg.split?.corsOrigins ?? (props.cfg.appUrl ? [props.cfg.appUrl] : ["*"]), diff --git a/infra/test/hybrid.test.ts b/infra/test/hybrid.test.ts index 4f9d02126..36fd0f373 100644 --- a/infra/test/hybrid.test.ts +++ b/infra/test/hybrid.test.ts @@ -170,6 +170,19 @@ test("relay bodies held for retries are gone after two days", () => { assert.equal(rule.ExpirationInDays, 2); }); +test("the dashboard may read signed GETs from the data bucket (the App map), and still only its own origins", () => { + const cors = (t: any) => { + const bucket = Object.values(t.findResources("AWS::S3::Bucket")).find((b: any) => JSON.stringify(b.Properties.BucketName).includes("-data")) as any; + return bucket.Properties.CorsConfiguration.CorsRules; + }; + const hostedRules = cors(hosted()["coderhelm-prod-storage"]); + assert.equal(hostedRules.length, 1); + assert.deepEqual([...hostedRules[0].AllowedMethods].sort(), ["GET", "HEAD", "PUT"]); + assert.ok(!hostedRules[0].AllowedOrigins.includes("*"), "the hosted dashboard's own origins"); + const self = synth(resolveConfig({ account: "111122223333", region: "us-west-2", stage: "prod", email: { from: "coderhelm@example.org" }, admins: ["owner@example.org"] })); + assert.deepEqual([...cors(self["coderhelm-prod-storage"])[0].AllowedMethods].sort(), ["GET", "HEAD", "PUT"]); +}); + test("a self-hosted install: relay intake, its own 404, no hosted-side parts", () => { const cfg = resolveConfig({ account: "111122223333", region: "us-west-2", stage: "prod", email: { from: "coderhelm@example.org" }, admins: ["owner@example.org"] }); const t = synth(cfg); diff --git a/selfhost/versions.json b/selfhost/versions.json index 429e5a7e9..030eae04f 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": "3a39e0c8f6b66e3cf734a70292c6e7211afaa47d" + "dashboardRef": "e136e62e4ff4e7ab922c819a3714de2fdfab8936" } 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..3d774e956 100644 --- a/services/common/src/app_map.rs +++ b/services/common/src/app_map.rs @@ -70,6 +70,20 @@ pub fn graph_key(team_id: &str) -> String { format!("{}/graph.json.gz", s3_prefix(team_id)) } +/// The page's copy of the map ([`viewer_copy`]), written with the map: gzipped +/// JSON stored with `Content-Encoding: gzip`, so the browser reads it +/// straight from the bucket (a short-lived signed URL) and unzips it itself. +pub fn view_key(team_id: &str) -> String { + format!("{}/view.json.gz", s3_prefix(team_id)) +} + +/// The map's small index ([`MapIndex`], gzipped JSON), written with the map: +/// what the read API needs to place Recent work and Health on it without +/// reading the map itself. +pub fn index_key(team_id: &str) -> String { + format!("{}/index.json.gz", s3_prefix(team_id)) +} + /// Floorplan's own files from the last run (a gzipped tar of `floorplan/`). pub fn state_key(team_id: &str) -> String { format!("{}/state.tgz", s3_prefix(team_id)) @@ -83,104 +97,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 } -/// 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( +/// 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), +} + +/// 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 +412,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 +428,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 @@ -292,37 +532,14 @@ fn arr<'a>(v: &'a Value, k: &str) -> impl Iterator { v[k].as_array().into_iter().flatten() } -fn files_set(graph: &Value) -> BTreeSet { - arr(graph, "files") - .filter_map(|f| f["p"].as_str().map(str::to_string)) +/// The parent of each part, read once. +fn parents(graph: &Value) -> HashMap<&str, &str> { + arr(graph, "nodes") + .filter_map(|n| Some((n["id"].as_str()?, n["parent"].as_str()?))) .collect() } -/// A repository path on the map (`folder/path`), when the map has that file. -/// `path` may already start with `owner/name/` (a run across several -/// repositories keeps paths that way). -pub fn map_path(graph: &Value, repo: &str, path: &str) -> Option { - let folders = repo_of_folder(graph); - let files = files_set(graph); - let path = path.trim_start_matches("./"); - for (folder, r) in &folders { - if let Some(rest) = path.strip_prefix(&format!("{r}/")) { - let p = format!("{folder}/{rest}"); - return files.contains(&p).then_some(p); - } - } - let folder = folders - .iter() - .find(|(_, r)| r.eq_ignore_ascii_case(repo)) - .map(|(f, _)| f.clone())?; - let p = format!("{folder}/{path}"); - files.contains(&p).then_some(p) -} - -fn top_node(graph: &Value, id: &str) -> String { - let parents: HashMap<&str, &str> = arr(graph, "nodes") - .filter_map(|n| Some((n["id"].as_str()?, n["parent"].as_str()?))) - .collect(); +fn top_of(parents: &HashMap<&str, &str>, id: &str) -> String { let mut cur = id; for _ in 0..20 { match parents.get(cur) { @@ -333,21 +550,115 @@ fn top_node(graph: &Value, id: &str) -> String { cur.to_string() } -/// The top-level part holding most of a repository's files. -fn repo_node(graph: &Value, repo: &str) -> Option { - let folder = repo_of_folder(graph) - .into_iter() - .find(|(_, r)| r.eq_ignore_ascii_case(repo)) - .map(|(f, _)| f)?; - let mut count: BTreeMap = BTreeMap::new(); - for f in arr(graph, "files") { - if f["r"].as_str() == Some(folder.as_str()) { - if let Some(n) = f["n"].as_str() { - *count.entry(top_node(graph, n)).or_default() += 1; +fn top_node(graph: &Value, id: &str) -> String { + top_of(&parents(graph), id) +} + +/// A repository path on the map (`folder/path`), when the map has that file. +/// `path` may already start with `owner/name/` (a run across several +/// repositories keeps paths that way). +pub fn map_path(graph: &Value, repo: &str, path: &str) -> Option { + MapIndex::of(graph).map_path(repo, path) +} + +/// One of Floorplan's own checks, as the index keeps it: enough to tell +/// whether a CoderHelm finding stands at the same place, and to count it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct IndexIssue { + pub id: String, + pub severity: String, + /// (file on the map, line or 0). + #[serde(default)] + pub locations: Vec<(String, u64)>, +} + +/// What the read API needs to place CoderHelm's Recent work and Health on a +/// map, without the map: written at build time with the map +/// ([`index_key`]), a few hundred bytes per file on the map instead of the +/// whole map, and every placement a lookup. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MapIndex { + /// Folder on the map to `owner/name`. + pub repos: BTreeMap, + /// Every file on the map (`folder/path`). + pub files: BTreeSet, + /// `owner/name` (lower case) to the top-level part holding most of its + /// files: where a finding with no file on the map sits. + pub repo_parts: BTreeMap, + /// Floorplan's own checks, in the map's order. + pub issues: Vec, + /// Whether the map has a Health section at all. + pub has_health: bool, +} + +impl MapIndex { + pub fn of(graph: &Value) -> Self { + let repos: BTreeMap = repo_of_folder(graph).into_iter().collect(); + let files = arr(graph, "files") + .filter_map(|f| f["p"].as_str().map(str::to_string)) + .collect(); + let parents = parents(graph); + let mut count: BTreeMap<&str, BTreeMap> = BTreeMap::new(); + for f in arr(graph, "files") { + if let (Some(r), Some(n)) = (f["r"].as_str(), f["n"].as_str()) { + *count + .entry(r) + .or_default() + .entry(top_of(&parents, n)) + .or_default() += 1; + } + } + let repo_parts = repos + .iter() + .filter_map(|(folder, repo)| { + let part = count + .get(folder.as_str())? + .iter() + .max_by_key(|(_, c)| **c) + .map(|(n, _)| n.clone())?; + Some((repo.to_ascii_lowercase(), part)) + }) + .collect(); + let issues = arr(&graph["health"], "issues") + .filter(|i| i["source"].is_null() || i["source"] == "floorplan") + .map(|i| IndexIssue { + id: i["id"].as_str().unwrap_or("").to_string(), + severity: i["severity"].as_str().unwrap_or("low").to_string(), + locations: locations(i).into_iter().collect(), + }) + .collect(); + Self { + repos, + files, + repo_parts, + issues, + has_health: graph.get("health").is_some(), + } + } + + /// A repository path on the map (`folder/path`), when the map has that + /// file. `path` may already start with `owner/name/`. + pub fn map_path(&self, repo: &str, path: &str) -> Option { + let path = path.trim_start_matches("./"); + for (folder, r) in &self.repos { + if let Some(rest) = path.strip_prefix(&format!("{r}/")) { + let p = format!("{folder}/{rest}"); + return self.files.contains(&p).then_some(p); } } + let folder = self + .repos + .iter() + .find(|(_, r)| r.eq_ignore_ascii_case(repo)) + .map(|(f, _)| f)?; + let p = format!("{folder}/{path}"); + self.files.contains(&p).then_some(p) + } + + /// The top-level part holding most of a repository's files. + pub fn repo_node(&self, repo: &str) -> Option { + self.repo_parts.get(&repo.to_ascii_lowercase()).cloned() } - count.into_iter().max_by_key(|(_, c)| *c).map(|(n, _)| n) } // ── Overlays ─────────────────────────────────────────────────────────────── @@ -395,14 +706,14 @@ pub fn severity_level(s: &str) -> &'static str { /// The map's `recent` from CoderHelm's runs: one task per run, one item per /// file it changed that is on the map. A run with no file on the map is left /// out. -pub fn recent_from_runs(graph: &Value, runs: &[WorkItem]) -> Option { +pub fn recent_from_runs(idx: &MapIndex, runs: &[WorkItem]) -> Option { let mut tasks = Vec::new(); let mut items = Vec::new(); for w in runs { let mut ids: Vec = w .files .iter() - .filter_map(|f| map_path(graph, &w.repo, f)) + .filter_map(|f| idx.map_path(&w.repo, f)) .map(|p| format!("f:{p}")) .collect(); ids.dedup(); @@ -442,7 +753,7 @@ pub fn recent_from_runs(graph: &Value, runs: &[WorkItem]) -> Option { /// CoderHelm's findings as Floorplan health issues. A finding in a /// repository the map doesn't have is left out. -pub fn issues_from_findings(graph: &Value, found: &[HealthItem]) -> Vec { +pub fn issues_from_findings(idx: &MapIndex, found: &[HealthItem]) -> Vec { let label = |k: &str| match k { "security" => "security", "infrastructure" => "infrastructure", @@ -455,12 +766,12 @@ pub fn issues_from_findings(graph: &Value, found: &[HealthItem]) -> Vec { let placed: Vec<(String, u32)> = h .files .iter() - .filter_map(|(f, line)| Some((map_path(graph, &h.repo, f)?, *line))) + .filter_map(|(f, line)| Some((idx.map_path(&h.repo, f)?, *line))) .collect(); let mut items: Vec = placed.iter().map(|(p, _)| format!("f:{p}")).collect(); items.dedup(); if items.is_empty() { - items.push(format!("n:{}", repo_node(graph, &h.repo)?)); + items.push(format!("n:{}", idx.repo_node(&h.repo)?)); } Some(json!({ "id": format!("coderhelm:{}:{}", h.kind, h.id), @@ -490,26 +801,9 @@ fn locations(issue: &Value) -> BTreeSet<(String, u64)> { .collect() } -/// The map with CoderHelm's overlays in Floorplan's own fields. With -/// `runs`, they replace the map's recent work; with `found`, CoderHelm's -/// findings join Floorplan's checks (each marked with its `source`; a -/// Floorplan issue at the same file and line as a CoderHelm one is dropped). -/// Floorplan's own checks are always labelled as Floorplan's. -pub fn with_overlays( - mut graph: Value, - runs: Option<&[WorkItem]>, - found: Option<&[HealthItem]>, -) -> Value { - if let Some(runs) = runs { - match recent_from_runs(&graph, runs) { - Some(r) => graph["recent"] = r, - None => { - if let Some(o) = graph.as_object_mut() { - o.remove("recent"); - } - } - } - } +/// Floorplan's checks labelled as Floorplan's, with Health's counts: the +/// map as the page's copy holds it before any of CoderHelm's overlays. +fn labelled(mut graph: Value) -> Value { let mut issues: Vec = graph["health"]["issues"] .as_array() .cloned() @@ -522,25 +816,102 @@ pub fn with_overlays( } } } - if let Some(found) = found { - let ours = issues_from_findings(&graph, found); - let taken: BTreeSet<(String, u64)> = ours.iter().flat_map(locations).collect(); - issues.retain(|i| i["source"] != "floorplan" || locations(i).is_disjoint(&taken)); - issues.extend(ours); + if graph.get("health").is_some() || !issues.is_empty() { + graph["health"]["summary"] = json!(summary_of( + issues + .iter() + .map(|i| i["severity"].as_str().unwrap_or("low")) + )); + graph["health"]["issues"] = json!(issues); } + graph +} + +fn summary_of<'a>(severities: impl Iterator) -> Value { let (mut high, mut medium, mut low) = (0, 0, 0); - for i in &issues { - match i["severity"].as_str().unwrap_or("low") { + for s in severities { + match s { "high" => high += 1, "medium" => medium += 1, _ => low += 1, } } - if graph.get("health").is_some() || !issues.is_empty() { - graph["health"]["issues"] = json!(issues); - graph["health"]["summary"] = json!({"high": high, "medium": medium, "low": low}); + json!({"high": high, "medium": medium, "low": low}) +} + +/// CoderHelm's overlays for a map, from its index alone: a small payload the +/// page lays over its copy of the map ([`apply_overlays`]). +/// +/// - `recent` (with `runs`): the map's Recent work, `null` for none; +/// - `health` (with `found`): CoderHelm's findings to `add`, the ids of +/// Floorplan's checks to `drop` (one at the same file and line as a +/// CoderHelm finding is not shown twice), and Health's `summary`. +pub fn overlays(idx: &MapIndex, runs: Option<&[WorkItem]>, found: Option<&[HealthItem]>) -> Value { + let mut out = json!({}); + if let Some(runs) = runs { + out["recent"] = recent_from_runs(idx, runs).unwrap_or(Value::Null); } - graph + if let Some(found) = found { + let ours = issues_from_findings(idx, found); + let taken: BTreeSet<(String, u64)> = ours.iter().flat_map(locations).collect(); + let (dropped, kept): (Vec<&IndexIssue>, Vec<&IndexIssue>) = idx + .issues + .iter() + .partition(|i| i.locations.iter().any(|l| taken.contains(l))); + if idx.has_health || !idx.issues.is_empty() || !ours.is_empty() { + let summary = summary_of( + kept.iter() + .map(|i| i.severity.as_str()) + .chain(ours.iter().map(|i| i["severity"].as_str().unwrap_or("low"))), + ); + out["health"] = json!({ + "add": ours, + "drop": dropped.iter().map(|i| i.id.as_str()).collect::>(), + "summary": summary, + }); + } + } + out +} + +/// Lays [`overlays`] over the page's copy of the map, as the page does. +pub fn apply_overlays(mut view: Value, o: &Value) -> Value { + if let Some(r) = o.get("recent") { + if r.is_null() { + if let Some(m) = view.as_object_mut() { + m.remove("recent"); + } + } else { + view["recent"] = r.clone(); + } + } + if let Some(h) = o.get("health").filter(|h| h.is_object()) { + let drop: BTreeSet<&str> = arr(h, "drop").filter_map(Value::as_str).collect(); + let mut issues: Vec = arr(&view["health"], "issues") + .filter(|i| { + i["source"] != "floorplan" || !i["id"].as_str().is_some_and(|id| drop.contains(id)) + }) + .cloned() + .collect(); + issues.extend(arr(h, "add").cloned()); + view["health"]["issues"] = json!(issues); + view["health"]["summary"] = h["summary"].clone(); + } + view +} + +/// The map with CoderHelm's overlays in Floorplan's own fields. With +/// `runs`, they replace the map's recent work; with `found`, CoderHelm's +/// findings join Floorplan's checks (each marked with its `source`; a +/// Floorplan issue at the same file and line as a CoderHelm one is dropped). +/// Floorplan's own checks are always labelled as Floorplan's. +pub fn with_overlays( + graph: Value, + runs: Option<&[WorkItem]>, + found: Option<&[HealthItem]>, +) -> Value { + let idx = MapIndex::of(&graph); + apply_overlays(labelled(graph), &overlays(&idx, runs, found)) } /// The copy the page gets: read-only (Floorplan's exported mode, so the @@ -553,6 +924,72 @@ pub fn for_viewer(mut graph: Value, now: &str) -> Value { graph } +/// The page's copy of a freshly built map ([`view_key`]): Floorplan's checks +/// labelled, read-only, without the sandbox's folder. CoderHelm's overlays +/// are laid over it on the page. +pub fn viewer_copy(graph: &Value, now: &str) -> Value { + for_viewer(labelled(graph.clone()), now) +} + +/// The page's copy and the index of a map, gzipped, as they are stored. +pub fn derived(graph: &Value, now: &str) -> (Vec, Vec) { + let view = gzip(viewer_copy(graph, now).to_string().as_bytes()); + let index = gzip(&serde_json::to_vec(&MapIndex::of(graph)).unwrap_or_default()); + (view, index) +} + +/// Writes the page's copy and the index of `graph` next to it (the worker +/// after each build; the read API once for a map built before they +/// existed). The copy is stored as JSON with `Content-Encoding: gzip`, so the +/// browser unzips it itself. +pub async fn store_derived( + s3: &aws_sdk_s3::Client, + bucket: &str, + team_id: &str, + graph: &Value, +) -> Result { + let (view, index) = derived(graph, &chrono::Utc::now().to_rfc3339()); + s3.put_object() + .bucket(bucket) + .key(view_key(team_id)) + .content_type("application/json") + .content_encoding("gzip") + .cache_control("private, no-cache") + .body(aws_sdk_s3::primitives::ByteStream::from(view)) + .send() + .await + .map_err(|e| format!("app map: could not keep the page's copy: {e}"))?; + // The index last: a reader that finds it current finds the copy current. + s3.put_object() + .bucket(bucket) + .key(index_key(team_id)) + .content_type("application/gzip") + .body(aws_sdk_s3::primitives::ByteStream::from(index)) + .send() + .await + .map_err(|e| format!("app map: could not keep the map's index: {e}"))?; + Ok(MapIndex::of(graph)) +} + +/// The team's map index and when it was written (unix seconds), if any. +pub async fn load_index( + s3: &aws_sdk_s3::Client, + bucket: &str, + team_id: &str, +) -> Option<(MapIndex, i64)> { + let obj = s3 + .get_object() + .bucket(bucket) + .key(index_key(team_id)) + .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)?; + Some((serde_json::from_slice(&json).ok()?, at)) +} + // ── Lookups (read API and Ask) ───────────────────────────────────────────── fn node(graph: &Value, id: &str) -> Option { @@ -1046,6 +1483,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 @@ -1173,6 +1694,220 @@ mod tests { assert_eq!(g["health"]["summary"]["high"], 1); } + /// The page's copy and the index are written together from a built map; + /// overlays placed with the stored index and laid over the stored copy + /// are what the map with its overlays always was. + #[test] + fn overlays_from_the_index_match_the_map_with_its_overlays() { + let runs = [WorkItem { + repo: "harbor/harbor-api".into(), + ticket: "DOCK-42".into(), + title: "Stop double bookings".into(), + files: vec!["src/bookings.js".into()], + ..Default::default() + }]; + let found = [ + HealthItem { + kind: "security".into(), + id: "f1".into(), + title: "Prototype pollution".into(), + severity: "P1".into(), + repo: "harbor/harbor-api".into(), + files: vec![("src/bookings.js".into(), 5)], + link: "/security/detail?id=f1".into(), + }, + HealthItem { + kind: "logs".into(), + id: "l1".into(), + title: "Bookings time out".into(), + severity: "warning".into(), + repo: "harbor/harbor-web".into(), + files: vec![], + link: "/logs?finding=l1".into(), + }, + ]; + let now = "2026-11-21T00:00:00Z"; + let (view, index) = derived(&harbor(), now); + let view: Value = serde_json::from_slice(&gunzip(&view, MAX_GRAPH_BYTES).unwrap()).unwrap(); + let idx: MapIndex = + serde_json::from_slice(&gunzip(&index, MAX_GRAPH_BYTES).unwrap()).unwrap(); + assert_eq!(idx, MapIndex::of(&harbor())); + assert_eq!(view["meta"]["exported"]["by"], "Coderhelm"); + assert!(view["meta"]["root"].is_null()); + for (r, f) in [ + (Some(&runs[..]), Some(&found[..])), + (Some(&runs[..]), None), + (None, Some(&found[..])), + (Some(&[][..]), Some(&[][..])), + ] { + let o = overlays(&idx, r, f); + let mut want = for_viewer(with_overlays(harbor(), r, f), now); + let mut got = apply_overlays(view.clone(), &o); + // Recent work is stamped when it is made. + for g in [&mut want, &mut got] { + if let Some(r) = g.get_mut("recent") { + r["updatedAt"] = json!(""); + } + } + assert_eq!(got, want); + } + // The Floorplan check at the same file and line is dropped by id. + let o = overlays(&idx, None, Some(&found)); + assert_eq!(o["health"]["drop"], json!(["no-auth:harbor-api"])); + assert_eq!(idx.repo_node("HARBOR/harbor-web").as_deref(), Some("web")); + } + + /// A made-up map the size of a large team's: `files` files in 12 parts + /// across 9 repositories, three lines per file, 20 Floorplan checks. + fn synthetic(files: usize) -> Value { + let repos: Vec = (0..9).map(|i| format!("dockyard/yard{i}")).collect(); + let folders = folders(&repos); + let nodes: Vec = (0..12) + .map(|i| json!({"id": format!("part{i}"), "parent": null, "label": format!("Dock area {i}"), "kind": "service", "summary": "Looks after berths.", "stats": {"files": files / 12}})) + .collect(); + let fs: Vec = (0..files) + .map(|i| { + let r = &repos[i % 9]; + json!({"p": format!("{}/src/area{}/berth_{i}_keeper.ts", folders[r], i % 40), "n": format!("part{}", i % 12), "r": folders[r], "l": "typescript", "loc": 120, "name": format!("Berth keeper {i}"), "d": "Keeps one berth's bookings, its gate code and the boats that may use it, and tells the office when it changes.", "h": "0123456789abcdef", "s": [], "sig": ""}) + }) + .collect(); + let links: Vec = (0..files * 3) + .map(|i| json!({"a": format!("f:{}", fs[i % files]["p"].as_str().unwrap()), "b": format!("f:{}", fs[(i * 7 + 13) % files]["p"].as_str().unwrap()), "k": "import", "w": 1})) + .collect(); + let issues: Vec = (0..20) + .map(|i| json!({"id": format!("open-endpoints:{}", fs[i * 17]["p"].as_str().unwrap()), "kind": "open-endpoints", "severity": if i % 3 == 0 { "high" } else { "medium" }, "title": "An endpoint anyone can call", "detail": "", "items": [format!("f:{}", fs[i * 17]["p"].as_str().unwrap())], "notes": {}, "locations": [{"file": fs[i * 17]["p"], "line": 10}], "fix": ""})) + .collect(); + let mut g = json!({ + "schema": GRAPH_SCHEMA, "project": {"name": "Dockyard", "summary": "Berths and bookings."}, + "meta": {"root": "/tmp/x", "agent": "claude", "repos": repos}, + "nodes": nodes, "files": fs, "links": links, "routes": [], "flows": [], "tour": [], "screens": [], + "health": {"issues": issues, "checked": [], "appWide": []}, + }); + stamp_repos(&mut g, &folders); + g + } + + /// What a page view costs at a large team's map size: before, the read API + /// read and parsed the whole map, placed each run's and finding's files + /// by scanning the map's files for each one, and sent the whole map back; + /// now it reads the small index, places them by lookup and sends a + /// signed address with the overlays. `APP_MAP_BENCH_GRAPH=` + /// measures a map on disk instead of the made-up one. + #[test] + fn a_page_view_reads_the_small_index_never_the_whole_map() { + use std::time::Instant; + let graph = match std::env::var("APP_MAP_BENCH_GRAPH") { + Ok(p) => serde_json::from_slice( + &gunzip(&std::fs::read(p).unwrap(), MAX_GRAPH_BYTES).unwrap(), + ) + .unwrap(), + Err(_) => synthetic(4_000), + }; + let paths: Vec<(String, String)> = arr(&graph, "files") + .filter_map(|f| { + let folder = f["r"].as_str()?; + let repo = graph["coderhelm"]["repos"][folder].as_str()?; + let p = f["p"].as_str()?.strip_prefix(&format!("{folder}/"))?; + Some((repo.to_string(), p.to_string())) + }) + .collect(); + // The most the page asks for: 60 runs of 20 files, 200 findings of 2. + let runs: Vec = (0..60) + .map(|i| WorkItem { + repo: paths[i % paths.len()].0.clone(), + ticket: format!("DOCK-{i}"), + title: "Tidy the berths".into(), + files: (0..20) + .map(|j| paths[(i * 31 + j * 7) % paths.len()].1.clone()) + .collect(), + ..Default::default() + }) + .collect(); + let found: Vec = (0..200) + .map(|i| HealthItem { + kind: "security".into(), + id: format!("f{i}"), + title: "An advisory".into(), + severity: "P2".into(), + repo: paths[i % paths.len()].0.clone(), + files: if i % 4 == 0 { + vec![] + } else { + vec![ + (paths[(i * 13) % paths.len()].1.clone(), 3), + ("package.json".into(), 0), + ] + }, + link: format!("/security/detail?id=f{i}"), + }) + .collect(); + let stored = gzip(graph.to_string().as_bytes()); + let (view, index) = derived(&graph, "2026-11-21T00:00:00Z"); + + // Before: the whole map read, the overlays placed on it, all of it sent. + let t = Instant::now(); + let g: Value = serde_json::from_slice(&gunzip(&stored, MAX_GRAPH_BYTES).unwrap()).unwrap(); + let mut placed = 0; + for w in &runs { + placed += w + .files + .iter() + .filter(|f| map_path(&g, &w.repo, f).is_some()) + .count(); + } + for h in &found { + placed += h + .files + .iter() + .filter(|(f, _)| map_path(&g, &h.repo, f).is_some()) + .count(); + } + let before_body = json!({"status": {}, "graph": for_viewer(with_overlays(g, Some(&runs), Some(&found)), "now")}).to_string(); + let before = t.elapsed(); + + // Now: the index read, the overlays placed with it, an address sent. + let t = Instant::now(); + let idx: MapIndex = + serde_json::from_slice(&gunzip(&index, MAX_GRAPH_BYTES).unwrap()).unwrap(); + let o = overlays(&idx, Some(&runs), Some(&found)); + let after_body = json!({"status": {}, "graph": null, "graph_url": "https://bucket.s3.us-east-1.amazonaws.com/app-map/t/view.json.gz?X-Amz-Signature=0", "overlays": o}).to_string(); + let after = t.elapsed(); + + eprintln!( + "app map page view: {} files, {} placed; before {:?} and {} bytes sent; now {:?} and {} bytes sent; the map read by the browser: {} bytes gzipped, index {} bytes gzipped", + arr(&graph, "files").count(), + placed, + before, + before_body.len(), + after, + after_body.len(), + view.len(), + index.len(), + ); + assert!(placed > 0); + assert!(after_body.len() < 1_000_000, "{} bytes", after_body.len()); + assert!( + index.len() * 4 < stored.len(), + "the index is a fraction of the map" + ); + // Generous for a debug build on a shared runner; a release build is + // a few milliseconds. + assert!(after.as_millis() < 1_000, "{after:?}"); + assert!(after < before); + // The page lays the overlays over the copy and gets the same map. + let view: Value = serde_json::from_slice(&gunzip(&view, MAX_GRAPH_BYTES).unwrap()).unwrap(); + let mut got = apply_overlays(view, &o); + let mut want = for_viewer( + with_overlays(graph, Some(&runs), Some(&found)), + "2026-11-21T00:00:00Z", + ); + for g in [&mut want, &mut got] { + g["recent"]["updatedAt"] = json!(""); + } + assert_eq!(got["health"], want["health"]); + assert_eq!(got["recent"], want["recent"]); + } + #[test] fn the_page_gets_a_read_only_copy_without_the_sandbox_folder() { let g = for_viewer(harbor(), "2026-11-21T00:00:00Z"); 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..18a42a127 100644 --- a/services/gateway/src/fake_aws.rs +++ b/services/gateway/src/fake_aws.rs @@ -1,5 +1,7 @@ //! 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 +//! objects kept in memory: put, get and head by key, with their content type, +//! encoding and time), 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 +19,7 @@ use axum::{ body::Bytes, extract::State, - http::{HeaderMap, StatusCode}, + http::{HeaderMap, Method, StatusCode, Uri}, response::{IntoResponse, Response}, Router, }; @@ -49,9 +51,54 @@ 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>, + /// S3 objects by path (`/bucket/key`). + objects: Mutex>, +} + +/// An object kept by the S3 stand-in. +#[derive(Clone, Debug, Default)] +pub struct S3Object { + pub body: Vec, + pub content_type: String, + pub content_encoding: String, + /// When it was written (unix seconds). + pub at: i64, } impl Store { + /// Keeps an object in the S3 stand-in, as a put would. + pub fn put_object(&self, bucket: &str, key: &str, body: Vec) { + self.objects.lock().unwrap().insert( + format!("/{bucket}/{key}"), + S3Object { + body, + at: chrono::Utc::now().timestamp(), + ..Default::default() + }, + ); + } + + /// An object in the S3 stand-in. + pub fn object(&self, bucket: &str, key: &str) -> Option { + self.objects + .lock() + .unwrap() + .get(&format!("/{bucket}/{key}")) + .cloned() + } + + /// 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 +291,88 @@ 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: objects by path, kept in memory; a read of one not there is not found. + if target.is_empty() && method == Method::PUT { + let h = |k: &str| { + headers + .get(k) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_string() + }; + store.objects.lock().unwrap().insert( + uri.path().to_string(), + S3Object { + body: body.to_vec(), + content_type: h("content-type"), + content_encoding: h("content-encoding"), + at: chrono::Utc::now().timestamp(), + }, + ); + return (StatusCode::OK, [("etag", "\"stand-in\"")], "").into_response(); + } + if target.is_empty() && matches!(method, Method::GET | Method::HEAD) { + let Some(o) = store.objects.lock().unwrap().get(uri.path()).cloned() else { + return ( + StatusCode::NOT_FOUND, + [("content-type", "application/xml")], + format!( + "NoSuchKeyno {}", + uri.path() + ), + ) + .into_response(); + }; + let modified = chrono::DateTime::from_timestamp(o.at, 0) + .unwrap_or_default() + .format("%a, %d %b %Y %H:%M:%S GMT") + .to_string(); + let mut r = if method == Method::HEAD { + StatusCode::OK.into_response() + } else { + (StatusCode::OK, o.body.clone()).into_response() + }; + let hs = r.headers_mut(); + hs.insert("last-modified", modified.parse().unwrap()); + hs.insert("content-length", o.body.len().to_string().parse().unwrap()); + if !o.content_type.is_empty() { + hs.insert("content-type", o.content_type.parse().unwrap()); + } + if !o.content_encoding.is_empty() { + hs.insert("content-encoding", o.content_encoding.parse().unwrap()); + } + return r; + } 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 +1009,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/main.rs b/services/gateway/src/main.rs index cf5866799..e41d32ff5 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -731,6 +731,7 @@ fn build_app(state: Arc) -> Router { // App map: the team's app across its repositories, made with Floorplan // (vendor/floorplan) and read through common::app_map. .route("/app-map", get(routes::app_map::get_map)) + .route("/app-map/graph", get(routes::app_map::graph)) .route("/app-map/part", get(routes::app_map::part)) .route("/app-map/file", get(routes::app_map::file)) .route("/app-map/screen", get(routes::app_map::screen)) diff --git a/services/gateway/src/routes/app_map.rs b/services/gateway/src/routes/app_map.rs index 4407d0e14..71142472c 100644 --- a/services/gateway/src/routes/app_map.rs +++ b/services/gateway/src/routes/app_map.rs @@ -5,8 +5,13 @@ //! signed-in team's own map: another team's part, file or screen is simply //! not found. //! -//! - `GET /api/app-map?recent=1&health=1`: the build status and the map -//! (the first visit starts the first build); +//! - `GET /api/app-map?recent=1&health=1`: the build status, a short-lived +//! signed address of the page's copy of the map (the browser reads it from +//! the bucket), and Recent work and Health as a small payload the page lays +//! over it (the first visit starts the first build); `graph=0`: the status +//! only; +//! - `GET /api/app-map/graph`: the page's copy through the API, as stored, +//! for a browser that can't reach the bucket; //! - `GET /api/app-map/part?id=`, `/file?path=`, `/screen?id=`, `/search?q=`: //! lookups; //! - questions about the map are Chat's: Chat offers the map lookups @@ -26,24 +31,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 +69,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 +87,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 +97,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,61 +162,210 @@ 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. +/// How long the signed address of the page's copy of the map stays good. +pub const VIEW_URL_SECS: u64 = 15 * 60; + +/// Where the page reads the map when the bucket can't be reached from the +/// browser (`GET /api/app-map/graph`, the same bytes through the API). +pub const VIEW_FALLBACK: &str = "/api/app-map/graph"; + +/// GET /api/app-map — the build status, where to read the map, and +/// CoderHelm's overlays for it. +/// +/// The map itself never passes through here: the worker writes the page's +/// copy at build time (`common::app_map::view_key`, gzipped JSON the browser +/// unzips), and the answer carries a short-lived signed address for it +/// (`graph_url`). Recent work and Health come as a small payload +/// (`overlays`) placed with the map's index (`common::app_map::MapIndex`), +/// which the page lays over the map. A map built before the copy and the +/// index existed gets them written here once. pub async fn get_map( State(state): State>, Extension(claims): Extension, 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), - am::status(&state.dynamo, table, &claims.team_id), + let bucket = &state.config.bucket_name; + let team = claims.team_id.as_str(); + let status_only = q.graph == Some(0); + let (written, index, mut st) = tokio::join!( + am::graph_written_at(&state.s3, bucket, team), + async { + if status_only { + None + } else { + am::load_index(&state.s3, bucket, team).await + } + }, + am::status(&state.dynamo, table, team), ); 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; + // The index is written after the map (and the page's copy before the + // index): one older than the map belongs to an earlier map. + let index = match (index, written) { + (Some((idx, at)), Some(map_at)) if at + 1 >= map_at => Some(idx), + (_, Some(_)) if !status_only => backfill(&state, team).await, + _ => None, + }; + let facts = match written { + Some(at) => MapFacts { + has_map: true, + written_at: at, + repos: index + .as_ref() + .map(|i| i.repos.len() as u32) + .or(st.as_ref().map(|s| s.built_repos)) + .unwrap_or(0), + }, + 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, team).await { + Ok(new) => st = Some(new), + Err(Some(running)) => st = Some(running), + Err(None) => st = am::status(&state.dynamo, table, team).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, team).await + } else { + 0 + }; + let status = status_view(st.as_ref(), facts, team_repos, now); + let (Some(idx), false) = (index, status_only) else { return Ok(Json(json!({ "status": status, "graph": Value::Null }))); }; + let url = view_url(&state, team).await.map_err(|e| { + error!("app map: could not sign the map's address: {e}"); + StatusCode::BAD_GATEWAY + })?; + let overlays = overlays_for(&state, team, &idx, &q).await; + Ok(Json(json!({ + "status": status, + "graph": Value::Null, + "graph_url": url, + "graph_fallback": VIEW_FALLBACK, + "graph_at": facts.written_at, + "overlays": overlays, + }))) +} + +/// Writes the page's copy and the index of a map built before they existed +/// (or by a worker that didn't write them), once; `None` when the map can't +/// be read. +async fn backfill(state: &AppState, team: &str) -> Option { + let bucket = &state.config.bucket_name; + let graph = am::load_graph(&state.s3, bucket, team).await?; + match am::store_derived(&state.s3, bucket, team, &graph).await { + Ok(idx) => { + info!(team_id = team, "App map: wrote the page's copy and index"); + Some(idx) + } + Err(e) => { + error!("{e}"); + None + } + } +} + +/// A signed GET for the page's copy of the team's map. +async fn view_url(state: &AppState, team: &str) -> Result { + let cfg = aws_sdk_s3::presigning::PresigningConfig::expires_in(std::time::Duration::from_secs( + VIEW_URL_SECS, + )) + .map_err(|e| e.to_string())?; + let req = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(am::view_key(team)) + .presigned(cfg) + .await + .map_err(|e| e.to_string())?; + Ok(req.uri().to_string()) +} + +/// Plans read at once for Recent work's "why". +const WHY_AT_ONCE: usize = 8; + +/// CoderHelm's Recent work and Health for the map (each when asked for), +/// placed with the map's index. +async fn overlays_for(state: &AppState, team: &str, idx: &am::MapIndex, q: &MapQuery) -> Value { + use futures::StreamExt; let days = 14; let (runs, found) = tokio::join!( async { - if q.recent == Some(1) { - Some(recent_runs(&state, &claims.team_id, days).await) - } else { - None + if q.recent != Some(1) { + return None; } + let mut runs = recent_runs(state, team, days).await; + // Only runs that are on the map are shown: read the plans of + // those, a few at a time. + runs.retain(|w| w.files.iter().any(|f| idx.map_path(&w.repo, f).is_some())); + let asks: Vec<(String, String)> = runs + .iter() + .take(25) + .map(|w| (w.ticket.clone(), w.repo.clone())) + .collect(); + let whys: Vec = futures::stream::iter(asks) + .map(|(ticket, repo)| async move { plan_why(state, team, &ticket, &repo).await }) + .buffered(WHY_AT_ONCE) + .collect() + .await; + for (w, why) in runs.iter_mut().zip(whys) { + w.why = why; + } + Some(runs) }, async { if q.health == Some(1) { - Some(health(&state, &claims.team_id, days).await) + Some(health(state, team, days).await) } else { None } }, ); - let mut runs = runs; - if let Some(runs) = runs.as_mut() { - for w in runs.iter_mut().take(25) { - w.why = plan_why(&state, &claims.team_id, &w.ticket, &w.repo).await; - } - } - let graph = am::with_overlays(graph, runs.as_deref(), found.as_deref()); - let graph = am::for_viewer(graph, &chrono::Utc::now().to_rfc3339()); - Ok(Json(json!({ "status": status, "graph": graph }))) + am::overlays(idx, runs.as_deref(), found.as_deref()) +} + +/// GET /api/app-map/graph — the page's copy of the map through the API, as +/// stored (gzipped JSON the browser unzips), for a browser that can't reach +/// the bucket. The bytes are passed on, never read. +pub async fn graph( + State(state): State>, + Extension(claims): Extension, +) -> Result { + use axum::response::IntoResponse; + let obj = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(am::view_key(&claims.team_id)) + .send() + .await + .map_err(|_| StatusCode::NOT_FOUND)?; + let bytes = obj + .body + .collect() + .await + .map_err(|_| StatusCode::BAD_GATEWAY)? + .into_bytes(); + Ok(( + [ + (axum::http::header::CONTENT_TYPE, "application/json"), + (axum::http::header::CONTENT_ENCODING, "gzip"), + (axum::http::header::CACHE_CONTROL, "private, no-store"), + ], + bytes, + ) + .into_response()) } fn bounded(s: &str, max: usize) -> Result<(), StatusCode> { @@ -232,16 +442,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), } } @@ -443,9 +680,32 @@ pub fn infra_item(r: &Value) -> Option { const OPEN_SECURITY: &[&str] = &["open", "fixing", "pr_open", "no_fix"]; +/// CoderHelm's open findings that name a repository, its four sources read +/// at once. async fn health(state: &AppState, team_id: &str, days: u32) -> Vec { + let cutoff = (chrono::Utc::now() - chrono::Duration::days(days as i64)).to_rfc3339(); + let (security, infra, logs, alerts) = tokio::join!( + super::security::load_findings(state, team_id), + super::infra_security::load_records(state, team_id), + common::log_findings::list_findings( + &state.dynamo, + &state.config.aws_insights_table_name, + team_id, + 200, + ), + state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :p AND begins_with(sk, :s)") + .expression_attribute_values(":p", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":s", AttributeValue::S("ALERT_EVENT#".into())) + .scan_index_forward(false) + .limit(200) + .send(), + ); let mut out = Vec::new(); - if let Ok(found) = super::security::load_findings(state, team_id).await { + if let Ok(found) = security { for (f, _) in found { let v = serde_json::to_value(&f).unwrap_or_default(); if OPEN_SECURITY.contains(&str_at(&v, &["status"])) { @@ -453,7 +713,7 @@ async fn health(state: &AppState, team_id: &str, days: u32) -> Vec { } } } - if let Ok(records) = super::infra_security::load_records(state, team_id).await { + if let Ok(records) = infra { for r in records { let v = serde_json::to_value(&r).unwrap_or_default(); if !matches!(str_at(&v, &["status"]), "fixed" | "dismissed" | "resolved") { @@ -461,14 +721,7 @@ async fn health(state: &AppState, team_id: &str, days: u32) -> Vec { } } } - if let Ok(found) = common::log_findings::list_findings( - &state.dynamo, - &state.config.aws_insights_table_name, - team_id, - 200, - ) - .await - { + if let Ok(found) = logs { for f in found { if f.fix_repo.is_empty() || matches!(f.status.as_str(), "dismissed" | "resolved") { continue; @@ -485,19 +738,7 @@ async fn health(state: &AppState, team_id: &str, days: u32) -> Vec { } } // Alerts of the last `days` days that named a repository. - let cutoff = (chrono::Utc::now() - chrono::Duration::days(days as i64)).to_rfc3339(); - if let Ok(page) = state - .dynamo - .query() - .table_name(&state.config.settings_table_name) - .key_condition_expression("pk = :p AND begins_with(sk, :s)") - .expression_attribute_values(":p", AttributeValue::S(team_id.to_string())) - .expression_attribute_values(":s", AttributeValue::S("ALERT_EVENT#".into())) - .scan_index_forward(false) - .limit(200) - .send() - .await - { + if let Ok(page) = alerts { for it in page.items() { let s = |k: &str| { it.get(k) @@ -594,6 +835,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", @@ -623,4 +1052,142 @@ mod tests { .any(|i| i["source"] == "coderhelm" && i["items"] == json!(["f:harbor-api/src/bookings.js"]))); } + + /// A made-up map the size of a large team's: `files` files in 12 parts + /// across 9 repositories, three lines per file. + fn big_map(files: usize) -> Value { + let repos: Vec = (0..9).map(|i| format!("dockyard/yard{i}")).collect(); + let folders = am::folders(&repos); + let fs: Vec = (0..files) + .map(|i| { + let r = &repos[i % 9]; + json!({"p": format!("{}/src/area{}/berth_{i}_keeper.ts", folders[r], i % 40), "n": format!("part{}", i % 12), "r": folders[r], "l": "typescript", "loc": 120, "name": format!("Berth keeper {i}"), "d": "Keeps one berth's bookings, its gate code and the boats that may use it, and tells the office when it changes."}) + }) + .collect(); + let links: Vec = (0..files * 3) + .map(|i| json!({"a": format!("f:{}", fs[i % files]["p"].as_str().unwrap()), "b": format!("f:{}", fs[(i * 7 + 13) % files]["p"].as_str().unwrap()), "k": "import", "w": 1})) + .collect(); + let mut g = json!({ + "schema": am::GRAPH_SCHEMA, "project": {"name": "Dockyard", "summary": "Berths and bookings."}, + "meta": {"root": "/tmp/x", "agent": "claude"}, + "nodes": (0..12).map(|i| json!({"id": format!("part{i}"), "parent": null, "label": format!("Dock area {i}"), "kind": "service"})).collect::>(), + "files": fs, "links": links, "routes": [], "flows": [], "tour": [], "screens": [], + "health": {"issues": [{"id": "open-endpoints:x", "severity": "high", "title": "Open", "items": [], "locations": [{"file": "yard0/src/area0/berth_0_keeper.ts", "line": 3}]}]}, + }); + am::stamp_repos(&mut g, &folders); + g + } + + async fn read_map(state: &Arc, team: &str) -> Value { + let q = MapQuery { + recent: Some(1), + health: Some(1), + ..Default::default() + }; + let Json(body) = get_map(State(state.clone()), Extension(admin(team)), Query(q)) + .await + .unwrap(); + body + } + + /// The page gets where to read the map and a small payload of overlays, + /// never the map: the copy and the index are read from the bucket (and + /// written once for a map built before they existed), and the copy + /// itself comes from the bucket, or through the API as stored. + #[tokio::test] + async fn the_page_gets_an_address_for_the_map_and_small_overlays() { + let f = crate::fake_aws::start().await; + let state = crate::fake_aws::state(&f.url); + let team = "TEAM#harbor"; + // No map yet: no address. + let first = read_map(&state, "TEAM#marina").await; + assert!(first["graph_url"].is_null() && first["graph"].is_null()); + + // A map built before the page's copy and its index existed. + f.store.put_object( + "bucket", + &am::graph_key(team), + am::gzip(harbor().to_string().as_bytes()), + ); + let body = read_map(&state, team).await; + assert_eq!(body["status"]["state"], "ready"); + assert!(body["graph"].is_null(), "the map itself is never sent"); + let url = body["graph_url"].as_str().unwrap(); + assert!( + url.contains("/bucket/app-map/TEAM_harbor/view.json.gz?") + && url.contains("X-Amz-Signature=") + && url.contains(&format!("X-Amz-Expires={VIEW_URL_SECS}")), + "{url}" + ); + assert_eq!(body["graph_fallback"], VIEW_FALLBACK); + assert!(body["graph_at"].as_i64().unwrap() > 0); + // Written once, as the browser reads it. + let view = f.store.object("bucket", &am::view_key(team)).unwrap(); + assert_eq!(view.content_type, "application/json"); + assert_eq!(view.content_encoding, "gzip"); + let copy: Value = + serde_json::from_slice(&am::gunzip(&view.body, am::MAX_GRAPH_BYTES).unwrap()).unwrap(); + assert!(copy["meta"]["root"].is_null()); + assert_eq!(copy["meta"]["agent"], "none"); + assert!(f.store.object("bucket", &am::index_key(team)).is_some()); + // Overlays: no runs, Floorplan's own checks counted. + assert!(body["overlays"]["recent"].is_null()); + let summary = &body["overlays"]["health"]["summary"]; + assert_eq!(summary, ©["health"]["summary"]); + // Read again: the copy is not written again. + let at = view.at; + read_map(&state, team).await; + assert_eq!( + f.store.object("bucket", &am::view_key(team)).unwrap().at, + at + ); + + // Through the API: the stored bytes, for the browser to unzip. + let r = graph(State(state.clone()), Extension(admin(team))) + .await + .unwrap(); + assert_eq!(r.headers()["content-encoding"], "gzip"); + assert_eq!(r.headers()["content-type"], "application/json"); + let bytes = axum::body::to_bytes(r.into_body(), usize::MAX) + .await + .unwrap(); + assert_eq!(bytes.to_vec(), view.body); + // Another team's copy is not this team's. + assert!(graph(State(state.clone()), Extension(admin("TEAM#marina"))) + .await + .is_err()); + } + + /// A page view at a large team's map size, through the real handler: the + /// answer is small and quick, however large the map. + #[tokio::test] + async fn a_page_view_of_a_large_map_is_small_and_quick() { + let f = crate::fake_aws::start().await; + let state = crate::fake_aws::state(&f.url); + let team = "TEAM#dockyard"; + let map = am::gzip(big_map(4_000).to_string().as_bytes()); + let map_len = map.len(); + f.store.put_object("bucket", &am::graph_key(team), map); + let am::MapIndex { .. } = am::store_derived( + &state.s3, + "bucket", + team, + &am::load_graph(&state.s3, "bucket", team).await.unwrap(), + ) + .await + .unwrap(); + let t = std::time::Instant::now(); + let body = read_map(&state, team).await; + let took = t.elapsed(); + let size = body.to_string().len(); + let view = f.store.object("bucket", &am::view_key(team)).unwrap(); + eprintln!( + "app map page view, 4,000 files: {took:?}, {size} bytes answered; the map is {map_len} bytes gzipped, the page's copy {} bytes gzipped", + view.body.len() + ); + assert!(body["graph_url"].is_string()); + assert!(size < 1_000_000, "{size} bytes"); + // Debug build, every call through the local stand-in. + assert!(took.as_millis() < 1_000, "{took:?}"); + } } diff --git a/services/worker/src/passes/app_map.rs b/services/worker/src/passes/app_map.rs index 7f7332dcb..7f41e9c26 100644 --- a/services/worker/src/passes/app_map.rs +++ b/services/worker/src/passes/app_map.rs @@ -22,8 +22,11 @@ //! runs the scan or the refresh; `build` writes the model jobs' answers and //! builds. The map is kept in the bucket (`common::app_map::graph_key`), with //! Floorplan's own files for the next refresh (`state_key`) and the step's -//! job (`job_key`). Recent work and Health are added when the page reads the -//! map (`common::app_map::with_overlays`), so they are always current. +//! job (`job_key`). Next to the map go the page's copy (`view_key`, which +//! the browser reads from the bucket itself) and the map's small index +//! (`index_key`), so reading the page never reads the whole map. Recent work +//! and Health are placed with the index when the page is read +//! (`common::app_map::overlays`), so they are always current. use std::collections::BTreeMap; use std::io::Read; @@ -575,27 +578,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 +657,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 +754,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 +768,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 +895,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 +965,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 +1029,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( @@ -981,6 +1060,9 @@ async fn step(state: &WorkerState, msg: AppMapMessage) -> Result<(), String> { am::gzip(g.to_string().as_bytes()), ) .await?; + // The page's copy and the index the read API places overlays + // with, so a page view never reads the whole map. + am::store_derived(&state.s3, &state.config.bucket_name, team_id, &g).await?; job.built = job.heads.clone(); job.arch_attempts = 0; job.desc_attempts = 0; @@ -990,7 +1072,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 +1087,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 +1111,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();