diff --git a/docs/deployments.md b/docs/deployments.md index d2f7508..d44b564 100644 --- a/docs/deployments.md +++ b/docs/deployments.md @@ -10,7 +10,7 @@ answers with `hidden: true` and a sentence that does not say whether it exists. | `deployment-history` | One page of the environment's workflow runs and the deployment runs no workflow owns, optionally for one branch | The environment-wide list | | `deployment-run` | One deployment or workflow run with its stages | The run detail | | `deployment-logs` | One page of a run's logs, by cursor | Logs | -| `deployment-releases` | One page of the environment's releases (APIs, agents, static sites), then their runs of the last `days` (default 30) in one more request | The Releases list: the last ten run states, the last run, the active run and stats per release | +| `deployment-releases` | One page of the environment's releases (APIs, agents, static sites), then their runs of the last `days` (default 30) in one more request. Releases without a successful run in that window get their newest successful run from one request with no window (up to ten it leaves out are read one by one), and releases with no runs at all get their repository and branch names from one branches request | The Releases list: the last ten run states, the last run, the active run and stats per release, plus `deployed` (the release has an active revision), `lastDeploy` (its newest successful run, whatever the window) and its repository and branch | | `deployment-release` | One release, its revisions and its runs of the last `days` | A release's history: the serving and wanted revisions, the runs and their stats | | `deployment-active` | Only runs still `queued` or `running` (at most 20), optionally for one branch | The cheap check while something is deploying | | `deployment-wait` | One run, every ten seconds, until it ends or `timeoutSeconds` (at most 120) runs out | Waiting for a deployment the person or the model started | diff --git a/package-lock.json b/package-lock.json index b7bcf9a..2b97cb5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@dev-mainsequence/devtools", - "version": "0.3.20", + "version": "0.3.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@dev-mainsequence/devtools", - "version": "0.3.20", + "version": "0.3.21", "license": "MIT", "bin": { "ms-devtools": "dist/runner.js" diff --git a/package.json b/package.json index 71780e9..63c7ca7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@dev-mainsequence/devtools", - "version": "0.3.20", + "version": "0.3.21", "description": "Shared MainSequence developer actions, project operations, MCP client and command runner", "license": "MIT", "engines": { diff --git a/src/shared/deployments.ts b/src/shared/deployments.ts index 523333a..138d49b 100644 --- a/src/shared/deployments.ts +++ b/src/shared/deployments.ts @@ -304,10 +304,34 @@ export function createDeployments(options: { host: HostServices; signal?: AbortS } const byRelease = new Map(); for (const run of runs) if (run.releaseUid) byRelease.set(run.releaseUid, [...(byRelease.get(run.releaseUid) || []), run]); + // A release is deployed whatever the window: its last deploy, repository and branch come from its own + // history, not only from the window's runs. One more request covers every release without a + // successful run in the window; a few that request leaves out are read one by one. + const lastDeploy = new Map(); + for (const [releaseUid, own] of byRelease) { const deployed = own.find(run => run.state === 'succeeded'); if (deployed) lastDeploy.set(releaseUid, deployed); } + const quiet = rows.filter(row => !lastDeploy.has(row.uid as string)); + const deploys = async (targets: string[], limit: number) => page(await scoped.request(backend, 'GET', `/api/v1/deployment-runs/?${new URLSearchParams({ organization_environment_uid: environmentUid, + target_uid__in: targets.join(','), state: 'succeeded', ordering: '-creation_date', limit: String(limit) })}`), 'The deployment runs').results + .map(row => deploymentRun(row, now)).filter((run): run is Run => !!run); + if (quiet.length) { + for (const run of await deploys(quiet.map(row => row.uid as string), 200)) if (run.releaseUid && !lastDeploy.has(run.releaseUid)) lastDeploy.set(run.releaseUid, run); + const missing = quiet.filter(row => row.activeRevisionUid && !lastDeploy.has(row.uid as string)).slice(0, 10); + for (const run of (await Promise.all(missing.map(row => deploys([row.uid as string], 1)))).flat()) if (run.releaseUid) lastDeploy.set(run.releaseUid, run); + } + const names = new Map(); + const unnamed = [...new Set(rows.filter(row => row.branchUid && !(byRelease.get(row.uid as string)?.[0]?.repositoryName || lastDeploy.get(row.uid as string)?.repositoryName)).map(row => row.branchUid as string))]; + if (unnamed.length) { + // Names only: a reader who may see a release but not its branch still gets the list. + const branches = await scoped.request(backend, 'GET', `/api/v1/code-repository-branches/?${new URLSearchParams({ uid__in: unnamed.join(','), limit: String(unnamed.length) })}`) + .then(body => page(body, 'The repository branches').results, error => { if (error instanceof ToolingError && ['API_ERROR', 'FORBIDDEN'].includes(error.code)) return []; throw error; }); + for (const branch of branches.map(rec)) { const uid = optionalUuid(branch.uid); if (uid) names.set(uid, { repositoryName: text(branch.code_repository_name, 200), branchName: text(branch.repository_branch, 200) }); } + } const results = rows.map(row => { const own = byRelease.get(row.uid as string) || [], last = own[0], active = own.find(run => ACTIVE_RUN_STATES.has(run.state)); - return { ...row, repositoryName: last?.repositoryName || '', branchName: last?.branchName || '', recent: own.slice(0, 10).map(run => ({ uid: run.uid, state: run.state })), - lastRun: last ? runSummary(last) : null, activeRun: active ? runSummary(active) : null, stats: releaseStats(own) }; + const deployed = lastDeploy.get(row.uid as string), named = names.get(row.branchUid as string); + return { ...row, repositoryName: last?.repositoryName || deployed?.repositoryName || named?.repositoryName || '', branchName: last?.branchName || deployed?.branchName || named?.branchName || '', + recent: own.slice(0, 10).map(run => ({ uid: run.uid, state: run.state })), deployed: !!row.activeRevisionUid, + lastRun: last ? runSummary(last) : null, lastDeploy: deployed ? runSummary(deployed) : null, activeRun: active ? runSummary(active) : null, stats: releaseStats(own) }; }); const deploying = results.filter(row => row.activeRun).length; data = { environmentUid, branchUid: branchUid || null, releaseKind: kind || null, search: search || null, days, count: releases.count, limit, offset, now: at, diff --git a/tests/deployment-releases.test.cjs b/tests/deployment-releases.test.cjs index bd7efc3..bdcfb9b 100644 --- a/tests/deployment-releases.test.cjs +++ b/tests/deployment-releases.test.cjs @@ -13,7 +13,7 @@ function run(n, release, state, { minutes = 4, error, type = 'resource_release', pipeline: { current_step_key: state === 'running' ? 'deploy' : '', steps: steps || [step(1, 'Build', 'succeeded', 3, -n * 60), step(2, 'Deploy', state === 'succeeded' ? 'succeeded' : state === 'running' ? 'running' : 'failed', minutes, -n * 60)] }, ...(error ? { error } : {}), billing: { secret: 'never-return' }, cost_summary: { total: 99 } }; } -function fixture({ runs, waitStates } = {}) { +function fixture({ runs, waitStates, batchLimit, siteDeployed = false, branchStatus = 200 } = {}) { const calls = [], state = { username: 'fixture' }; const allRuns = runs || [run(0, API, 'running'), run(1, API, 'succeeded'), run(2, API, 'failed', { error: { code: 'runtime_readiness_timeout', detail: 'not ready' } }), run(3, AGENT, 'failed', { type: 'harness_agent', error: { code: 'image_build_failed' } }), run(4, AGENT, 'superseded', { type: 'harness_agent' }), run(5, SITE, 'succeeded', { type: 'static_site' })]; @@ -24,7 +24,10 @@ function fixture({ runs, waitStates } = {}) { if (u.pathname === '/api/v1/resource-releases/') return Response.json({ count: 3, results: [ { uid: API, name: 'pricing-api', release_kind: 'fastapi', code_repository_branch_uid: BRANCH, active_revision: id(20), desired_revision: id(21), workload_user_uid: 'w' }, { uid: AGENT, name: 'risk-agent', release_kind: 'harness_agent', code_repository_branch_uid: BRANCH }, - { uid: SITE, name: 'docs-site', release_kind: 'static_site', code_repository_branch_uid: BRANCH }] }); + { uid: SITE, name: 'docs-site', release_kind: 'static_site', code_repository_branch_uid: BRANCH, ...(siteDeployed ? { active_revision: id(22) } : {}) }] }); + if (u.pathname === '/api/v1/code-repository-branches/') return branchStatus === 200 + ? Response.json({ count: 1, results: [{ uid: BRANCH, code_repository_name: 'pricing-engine', repository_branch: 'main' }].filter(row => u.searchParams.get('uid__in').split(',').includes(row.uid)) }) + : Response.json({ detail: 'forbidden' }, { status: branchStatus }); if (u.pathname === `/api/v1/resource-releases/${API}/`) return Response.json({ uid: API, name: 'pricing-api', release_kind: 'fastapi', code_repository_branch_uid: BRANCH, active_revision: id(20), desired_revision: id(21) }); if (u.pathname === `/api/v1/resource-releases/${API}/revisions/`) return Response.json({ count: 2, results: [ { uid: id(21), state: 'pending', commit_sha: 'abc0def0123456', configuration_revision: 15, created_at: iso(0) }, @@ -34,7 +37,11 @@ function fixture({ runs, waitStates } = {}) { if (u.searchParams.get('target_uid__in')) rows = rows.filter(row => u.searchParams.get('target_uid__in').split(',').includes(row.target_uid)); if (u.searchParams.get('target_uid')) rows = rows.filter(row => row.target_uid === u.searchParams.get('target_uid')); if (u.searchParams.get('state__in')) rows = rows.filter(row => u.searchParams.get('state__in').split(',').includes(row.state)); - return Response.json({ count: rows.length, results: rows }); + if (u.searchParams.get('state')) rows = rows.filter(row => row.state === u.searchParams.get('state')); + if (u.searchParams.get('created_after')) rows = rows.filter(row => row.created_at >= u.searchParams.get('created_after')); + const count = rows.length, multiple = (u.searchParams.get('target_uid__in') || '').includes(','); + if (batchLimit && multiple && u.searchParams.get('state')) rows = rows.slice(0, batchLimit); + return Response.json({ count, results: rows }); } if (u.pathname === `/api/v1/deployment-runs/${id(100)}/`) { const states = waitStates || ['running']; const now = states[Math.min(reads.wait++, states.length - 1)]; @@ -49,7 +56,8 @@ test('the release list reads one page of releases and their runs in one more req const f = fixture(), result = await f.run('deployment-releases', { environmentUid: ENV, days: 30 }); assert.equal(result.status, 'success', result.summary); const reads = f.calls.filter(call => call.path !== '/api/v1/users/me/'); - assert.deepEqual(reads.map(call => call.path), ['/api/v1/resource-releases/', '/api/v1/deployment-runs/']); + assert.deepEqual(reads.map(call => call.path), ['/api/v1/resource-releases/', '/api/v1/deployment-runs/', '/api/v1/deployment-runs/']); + assert.deepEqual([reads[2].query.target_uid__in, reads[2].query.state, reads[2].query.created_after], [AGENT, 'succeeded', undefined], 'only the release without a successful run in the window is looked up further back'); assert.ok(f.calls.every(call => call.method === 'GET')); assert.equal(reads[0].query.organization_environment_uid, ENV); assert.deepEqual(reads[1].query.target_uid__in.split(','), [API, AGENT, SITE]); @@ -142,3 +150,30 @@ test('a wait stops when its read is cancelled', async () => { const started = Date.now(), result = await api.dispatch({ action: 'deployment-wait', backend, expectedAccount: 'fixture', runUid: id(100), timeoutSeconds: 60 }); assert.equal(result.status, 'cancelled'); assert.ok(Date.now() - started < 3000); }); + +test('a release with no run in the window still says it is deployed, when, and from which repository and branch', async () => { + const f = fixture(), result = await f.run('deployment-releases', { environmentUid: ENV, days: 1 }); + assert.equal(result.status, 'success', result.summary); + const reads = f.calls.filter(call => call.path !== '/api/v1/users/me/'); + assert.deepEqual(reads.map(call => call.path), ['/api/v1/resource-releases/', '/api/v1/deployment-runs/', '/api/v1/deployment-runs/', '/api/v1/code-repository-branches/'], 'at most two more requests'); + assert.ok(reads[1].query.created_after, 'the window read is bounded'); assert.equal(reads[2].query.state, 'succeeded'); assert.equal(reads[2].query.created_after, undefined); + assert.deepEqual(reads[2].query.target_uid__in.split(','), [API, AGENT, SITE]); assert.equal(reads[3].query.uid__in, BRANCH); + const [api, agent, site] = result.data.results; + assert.deepEqual(api.recent, [], 'nothing ran in the last day'); assert.equal(api.lastRun, null); + assert.equal(api.deployed, true); assert.equal(api.lastDeploy.uid, id(101)); assert.equal(api.lastDeploy.finishedAt, iso(-60 + 4)); + assert.deepEqual([api.repositoryName, api.branchName], ['pricing-engine', 'main']); + assert.equal(agent.deployed, false, 'no active revision'); assert.equal(agent.lastDeploy, null); + assert.deepEqual([agent.repositoryName, agent.branchName], ['pricing-engine', 'main'], 'named from its branch when it never deployed'); + assert.equal(site.lastDeploy.uid, id(105)); +}); + +test('a deployed release the batched lookup leaves out is read on its own; a branch it may not read leaves the name blank', async () => { + const f = fixture({ batchLimit: 1, siteDeployed: true, branchStatus: 403 }), result = await f.run('deployment-releases', { environmentUid: ENV, days: 1 }); + assert.equal(result.status, 'success', result.summary); + const lookups = f.calls.filter(call => call.path === '/api/v1/deployment-runs/' && call.query.state === 'succeeded'); + assert.equal(lookups.length, 2); assert.equal(lookups[1].query.target_uid__in, SITE); assert.equal(lookups[1].query.limit, '1'); + const [api, agent, site] = result.data.results; + assert.equal(api.lastDeploy.uid, id(101)); assert.equal(site.lastDeploy.uid, id(105), 'found by its own read'); + assert.equal(agent.lastDeploy, null, 'a release never deployed is not read on its own'); + assert.deepEqual([agent.repositoryName, agent.branchName], ['', ''], 'a refused branch read does not fail the list'); +});