diff --git a/.github/workflows/pm-console-edge-deploy.yml b/.github/workflows/pm-console-edge-deploy.yml index 8fb096d5dd..698967d353 100644 --- a/.github/workflows/pm-console-edge-deploy.yml +++ b/.github/workflows/pm-console-edge-deploy.yml @@ -7,10 +7,24 @@ name: pm-console-edge deploy # (pm-stack/console/edge): every push to main that touches the console, # or a manual run, runs the console's tests (which drive the Worker's # routing and state against the host's real handler), bundles the -# Worker, and uploads it with the CLOUDFLARE_API_TOKEN and +# Worker, and releases it with the CLOUDFLARE_API_TOKEN and # CLOUDFLARE_ACCOUNT_ID repository secrets, the ones message-bridge # deploys with. # +# The release (pm-stack/console/edge/release.mjs) starts from whatever +# is there, including nothing: +# 1. no Worker of that name: an empty one is stood up (edge/init); +# 2. this commit is uploaded as a version, which serves nothing yet; +# 3. that version is put at 100%; +# 4. the Worker is asked which version it is, and if it does not +# answer as this commit the version that was serving is put back +# and the run fails. +# So nothing outside this workflow is needed to bring the Worker up in +# an account that has none. That path is run for real, on a scratch +# Worker that is removed first and removed again afterwards, whenever a +# push changes how the Worker is stood up, and on a manual run that asks +# for it (scratch). The real Worker is not touched by that. +# # The Worker has no secrets from this deploy: the keys it uses it makes # itself, or are published by the host. Three secrets are optional, put # there by the host's scripts/expose.py --edge-direct (off by default): @@ -38,6 +52,10 @@ on: description: "Existing Worker version id to put back instead of uploading; empty deploys this commit" required: false default: "" + scratch: + description: "First stand a scratch Worker up from nothing, deploy this commit to it, check it and remove it" + type: boolean + default: false permissions: contents: read @@ -52,7 +70,7 @@ jobs: deploy: name: deploy pm-console-edge runs-on: ubuntu-latest - timeout-minutes: 15 + timeout-minutes: 30 steps: - name: Check deploy secrets id: secrets @@ -77,11 +95,46 @@ jobs: - name: Install the deploy tool working-directory: pm-stack/console/edge run: npm ci --no-audit --no-fund - - name: Bundle the Worker + - name: Bundle the Worker, and the empty one it is stood up from working-directory: pm-stack/console/edge run: | node build.mjs npx wrangler deploy --dry-run --outdir .wrangler/dry + npx wrangler deploy --dry-run --config init/wrangler.jsonc --outdir .wrangler/dry-init + - name: See whether this push changes how the Worker is stood up + id: standup + if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' + env: + GH_TOKEN: ${{ github.token }} + ASKED: ${{ inputs.scratch }} + BEFORE: ${{ github.event.before }} + run: | + # A manual run says whether it wants the scratch stand-up. A + # push gets it when it touches the release itself. If what + # the push changed cannot be read, the stand-up is run: it + # costs a few minutes and risks nothing. + scratch=false + if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ]; then + if [ "$ASKED" = "true" ]; then scratch=true; fi + elif ! printf '%s' "${BEFORE:-}" | grep -Eq '^[0-9a-f]{40}$' || [ "$BEFORE" = "0000000000000000000000000000000000000000" ]; then + scratch=true + elif files="$(gh api "repos/${GITHUB_REPOSITORY}/compare/${BEFORE}...${GITHUB_SHA}" --jq '.files[].filename')"; then + if printf '%s\n' "$files" | grep -Eq '^(pm-stack/console/edge/(release\.mjs|release-plan\.mjs|wrangler\.jsonc|package\.json|package-lock\.json|init/.*)|\.github/workflows/pm-console-edge-deploy\.yml)$'; then + scratch=true + fi + else + scratch=true + fi + echo "scratch=$scratch" >> "$GITHUB_OUTPUT" + - name: Stand a scratch Worker up from nothing, deploy this commit to it, and remove it + if: steps.standup.outputs.scratch == 'true' + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + run: | + node release.mjs --sha "$GITHUB_SHA" --scratch + echo "Stood pm-console-edge-scratch up from nothing, deployed ${GITHUB_SHA::12} to it, heard it answer, and removed it." >> "$GITHUB_STEP_SUMMARY" - name: Deploy if: steps.secrets.outputs.ready == 'true' working-directory: pm-stack/console/edge @@ -100,7 +153,10 @@ jobs: npx wrangler rollback "$ROLLBACK_VERSION" --yes --message "rollback from workflow run ${GITHUB_RUN_ID}" echo "Put pm-console-edge back to version ${ROLLBACK_VERSION}." >> "$GITHUB_STEP_SUMMARY" else - npx wrangler deploy --var "VERSION:${GITHUB_SHA::12}" --message "git ${GITHUB_SHA}" + # Stands the Worker up if there is none, uploads this commit + # as a version, puts it at 100%, and puts the previous + # version back if this one does not answer. + node release.mjs --sha "$GITHUB_SHA" echo "Deployed pm-console-edge from ${GITHUB_SHA}." >> "$GITHUB_STEP_SUMMARY" fi - name: Check the deployed Worker answers @@ -116,7 +172,7 @@ jobs: | python3 -c 'import json,sys; print(json.load(sys.stdin)["result"]["subdomain"])')" url="https://pm-console-edge.${sub}.workers.dev/console/health" want="${GITHUB_SHA::12}" - for attempt in $(seq 1 20); do + for _ in $(seq 1 20); do got="$(curl -fsS --max-time 10 "$url" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("version") if d.get("ok") and d.get("edge") else "")' 2>/dev/null || true)" if [ "$got" = "$want" ]; then echo "pm-console-edge answers as ${want}." >> "$GITHUB_STEP_SUMMARY" diff --git a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md index 25fc12eabd..719f0ff6f1 100644 --- a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md +++ b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md @@ -219,3 +219,41 @@ Still open, and why: staged in #12561 and needs two protected environments with their own tokens before it can run. - The Android project is still on androidbrowserhelper 2.5.0. + +## 2026-11-23T01:25Z Update: the build never holds up a report + +The last three commits of the Android-build change (#12723) merged +before any reviewer read them, so they were read again afterwards. Two +real faults came out of that: one in how the build travels, one in how +the edge keeps it. + +A report that carries the build is megabytes; every other report is +kilobytes. The laptop gives a report twenty seconds. On a connection +too slow to send the build in that time, the report failed, and the +next was built the same way and failed too, for as long as the edge +still lacked the build. In that time no report arrived at all, so the +edge took the laptop for gone while it was there. Nothing of the kind +could happen before the build was put into reports. + +- A report that carried the build and did not get through, whether cut + off or turned away, is followed at once by one without the build. + The build is tried again ten minutes later. At worst one report in + ten minutes is lost to it. +- A build file that cannot be read is left out the same way, where it + used to stop the report. +- Whether the build and the changed sections fit one report is now + measured on the report as sent, in bytes. It was estimated in + characters, and text outside ASCII is up to three bytes a character, + so the estimate could pass a report the edge then refused as too + large. +- When the build goes alone, the sections it displaced follow at once + instead of at the next ordinary report. + +- The edge wrote a new build over the pieces of the old one and only + then recorded the new build. A write that stopped half-way left + pieces of two builds under the old record, and with the laptop away + those were handed out as the old build. The old record is now removed + before its pieces are touched, so a half-written copy is no copy: the + edge says it has none, hands nothing out, and asks for the build + again. Pieces left by a larger build are removed whether or not its + record survived. diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index db9d4475eb..88e246d053 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -18,6 +18,7 @@ runs the fleet's tools can be reached. | Direct actions (reply to or close a prompt, comment, rank an issue, move a task) | edge, once the laptop has been quiet for a minute | run at the edge through the laptop's own classes, and never sent to the laptop, so they are not done twice; a new prompt is filed at the edge and only its queue task is held for the laptop | | Actions not safe to do late (merge, units, unblock, …) | laptop, relayed at once | refused, saying why | | The dashboard's own pages, logs, one pull request's page | laptop | a plain notice with a link to the app | +| The signed Android build (`/console/pm-console.apk`) | laptop, and a copy at the edge | the copy is served, and the app says so when the copy is older than the laptop's newest | The list of actions that may be done late is `HOLDABLE` in `../src/edge-proto.ts`. @@ -50,6 +51,15 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts state that changed, how current each unchanged one is, and what became of anything held for it. The answer says whether anyone is looking, and carries the actions the owner took while it was away. +- **The signed Android build travels in a report**, once per build, when + the edge says it lacks it, and is kept only if it matches its + fingerprint. It never stands in the way of the reports themselves, + which are how the edge knows the laptop is there. Beside sections that + would take the report past its room (counted in bytes as sent) it goes + alone and they follow at once. If a report carrying it does not get + through (a slow connection runs out of time, or it is turned away), or + the file cannot be read, the reports after that go without it, and it + is tried again ten minutes later. - **An action for the laptop is relayed at once** when the laptop is in reach; its answer carries what it read again, so the edge's copy shows the change before the next report. @@ -113,8 +123,39 @@ sign-in issuer's). Pushes to `main` that touch the console deploy it (`.github/workflows/pm-console-edge-deploy.yml`): the console's tests, which drive this Worker's routing and state against the laptop's real -handler; a bundle; `wrangler deploy`; then a check that the deployed -Worker answers its health check as that commit. +handler; a bundle; the release; then a check that the deployed Worker +answers its health check as that commit. + +The release is [`release.mjs`](release.mjs), and it starts from whatever +is there, including nothing: + +1. No Worker of that name: an empty one is stood up + ([`init/`](init/worker.ts): the Durable Object's class and an answer + that says it is empty). A version cannot be uploaded to a Worker that + does not exist, and the storage behind the class is only made by a + deploy. +2. This commit is uploaded as a version. It serves nothing yet. +3. That version is put at 100%. +4. The Worker is asked which version it is. If it does not answer as + this commit, the version that was serving is put back and the run + fails. + +A new Durable Object migration in `wrangler.jsonc` cannot travel in a +version, so then steps 2 and 3 are one `wrangler deploy`. + +So an account with no Worker needs nothing but this workflow to get +one. That is not taken on trust: whenever a push changes the release +itself (`release.mjs`, `release-plan.mjs`, `init/`, `wrangler.jsonc`, +the lockfile or the workflow), and on a manual run with `scratch`, the +same steps are first run on `pm-console-edge-scratch`, which is removed +before (so the start is nothing) and removed after. The real Worker is +not touched by that, and the scratch one is the only Worker the script +will ever delete. + +```bash +gh workflow run pm-console-edge-deploy.yml # deploy main's head +gh workflow run pm-console-edge-deploy.yml -f scratch=true # and show the stand-up from nothing first +``` The Worker has no route in `wrangler.jsonc` on purpose. The laptop's `scripts/expose.py` (on a 15 minute timer) sends the hostname through it diff --git a/pm-stack/console/edge/init/worker.ts b/pm-stack/console/edge/init/worker.ts new file mode 100644 index 0000000000..7c111a8834 --- /dev/null +++ b/pm-stack/console/edge/init/worker.ts @@ -0,0 +1,25 @@ +// The Worker before its first version: the object's class, so that its +// state has somewhere to live, and an answer that says there is nothing +// here yet. +// +// A version cannot be uploaded to a Worker that does not exist, and the +// storage behind a Durable Object class is only created by a deploy. So +// when there is no Worker, release.mjs deploys this one first and then +// uploads the real one over it as a version. +// +// It answers 503 with `ok: false` on purpose: the host's +// scripts/expose.py sends the hostname through the Worker only once its +// health check says `ok`, and an empty Worker must never get the +// hostname. +import { DurableObject } from "cloudflare:workers"; + +export class PmEdge extends DurableObject {} + +export default { + fetch(): Response { + return new Response(JSON.stringify({ ok: false, edge: true, empty: true }), { + status: 503, + headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }, + }); + }, +}; diff --git a/pm-stack/console/edge/init/wrangler.jsonc b/pm-stack/console/edge/init/wrangler.jsonc new file mode 100644 index 0000000000..e482dd9ef4 --- /dev/null +++ b/pm-stack/console/edge/init/wrangler.jsonc @@ -0,0 +1,17 @@ +{ + // The empty Worker release.mjs stands up when there is none: see + // worker.ts. Everything here that is not a version's own (the name, + // the Durable Object class and its migration, the workers.dev + // address, logs) must say what ../wrangler.jsonc says; a test holds + // the two together (test/release.test.ts). + "name": "pm-console-edge", + "main": "worker.ts", + "compatibility_date": "2026-10-01", + "compatibility_flags": ["nodejs_compat"], + "workers_dev": true, + "preview_urls": false, + "observability": { "enabled": true }, + "vars": { "PUBLIC_HOST": "pm.security.cab", "VERSION": "empty" }, + "durable_objects": { "bindings": [{ "name": "PM", "class_name": "PmEdge" }] }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["PmEdge"] }] +} diff --git a/pm-stack/console/edge/release-plan.mjs b/pm-stack/console/edge/release-plan.mjs new file mode 100644 index 0000000000..92ce20bc2c --- /dev/null +++ b/pm-stack/console/edge/release-plan.mjs @@ -0,0 +1,138 @@ +// The decisions release.mjs makes, apart from the doing: nothing here +// talks to Cloudflare or runs a command, so every one of them is tested +// (../test/release.test.ts). + +const VERSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const SHA = /^[0-9a-f]{40}$/; +const WORKER_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/; + +/** What a commit is called once it is a version. */ +export function names(sha) { + if (!SHA.test(sha)) throw new Error("--sha must be a full commit id"); + const short = sha.slice(0, 12); + return { short, tag: `git-${short}`, message: `git ${sha}` }; +} + +/** The name and the newest migration tag a wrangler configuration gives. + * The text is JSON with comments, and is read without a parser for + * them: comments are dropped where they stand outside strings. */ +export function configOf(text) { + let out = ""; + let inString = false; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (inString) { + out += c; + if (c === "\\") out += text[++i] ?? ""; + else if (c === '"') inString = false; + } else if (c === '"') { + inString = true; + out += c; + } else if (c === "/" && text[i + 1] === "/") { + while (i < text.length && text[i] !== "\n") i++; + out += "\n"; + } else if (c === "/" && text[i + 1] === "*") { + i = text.indexOf("*/", i + 2); + if (i < 0) throw new Error("the configuration has a comment that never ends"); + i++; + } else out += c; + } + const config = JSON.parse(out.replace(/,(\s*[}\]])/g, "$1")); + if (typeof config.name !== "string" || !WORKER_NAME.test(config.name)) { + throw new Error("the configuration names no Worker"); + } + const migrations = Array.isArray(config.migrations) ? config.migrations : []; + return { config, name: config.name, migrationTag: migrations.at(-1)?.tag ?? null }; +} + +/** The Worker a stand-up from nothing is tried on. It is never the real + * one: it has a name of its own, made here and nowhere else. */ +export function scratchName(base) { + return `${base}-scratch`; +} + +/** A Worker this script may delete: the scratch one, and no other. */ +export function removable(name, base) { + return name === scratchName(base) && name !== base; +} + +/** What Cloudflare said about a Worker's existence, read strictly: only + * a plain "there is no such Worker" counts as absent, because the answer + * to absence is to deploy an empty Worker under that name. */ +export function existence(status, body) { + if (status === 200 && body?.success === true) { + return { exists: true, migrationTag: body.result?.default_environment?.script?.migration_tag ?? null }; + } + // The two codes Cloudflare gives for "no such Worker" (the ones + // wrangler itself takes to mean that). + const codes = Array.isArray(body?.errors) ? body.errors.map((e) => e?.code) : []; + if (status === 404 && (codes.includes(10007) || codes.includes(10090))) { + return { exists: false, migrationTag: null }; + } + throw new Error(`cannot tell whether the Worker exists: http ${status} ${JSON.stringify(body?.errors ?? null)}`); +} + +/** Whether a list of the account's Workers has one of this name. */ +export function listed(body, name) { + if (body?.success !== true || !Array.isArray(body.result)) { + throw new Error("cannot read the account's list of Workers"); + } + return body.result.some((script) => script?.id === name); +} + +/** The steps to take, given what is there. + * + * - No Worker: stand an empty one up, then upload and promote. + * - A Worker whose Durable Object classes are as the configuration has + * them: upload a version and promote it. + * - A Worker whose classes differ (a new migration, or none applied + * yet): one full deploy, because a version cannot carry a migration. + */ +export function plan({ exists, migrationTag }, wantTag) { + if (!exists) return ["stand-up", "upload", "promote"]; + if (migrationTag === wantTag) return ["upload", "promote"]; + return ["deploy"]; +} + +/** The id of the version wrangler just uploaded for this Worker, from + * the file it writes its results to (one JSON object a line). */ +export function uploadedVersion(text, name) { + let found = null; + for (const line of text.split("\n")) { + if (line.trim() === "") continue; + let entry; + try { + entry = JSON.parse(line); + } catch { + continue; + } + if (entry?.type === "version-upload" && entry.worker_name === name) found = entry.version_id; + } + if (typeof found !== "string" || !VERSION_ID.test(found)) { + throw new Error("wrangler did not say which version it uploaded"); + } + return found; +} + +/** The version serving all traffic now, or null when there is none or + * traffic is split (nothing to put back with one step). */ +export function servingVersion(body) { + const newest = body?.result?.deployments?.[0]; + const versions = Array.isArray(newest?.versions) ? newest.versions : []; + if (versions.length !== 1 || versions[0]?.percentage !== 100) return null; + const id = versions[0].version_id; + return typeof id === "string" && VERSION_ID.test(id) ? id : null; +} + +/** What a health answer means for a release of `short`. */ +export function healthSays(answer, short) { + if (!answer || typeof answer !== "object") return "silent"; + if (answer.empty === true && answer.edge === true) return "empty"; + if (answer.ok === true && answer.edge === true) return answer.version === short ? "this" : "another"; + return "silent"; +} + +/** A version id as a person may give it for a rollback. */ +export function isVersionId(value) { + return typeof value === "string" && VERSION_ID.test(value); +} diff --git a/pm-stack/console/edge/release.mjs b/pm-stack/console/edge/release.mjs new file mode 100644 index 0000000000..f4425a416a --- /dev/null +++ b/pm-stack/console/edge/release.mjs @@ -0,0 +1,241 @@ +#!/usr/bin/env node +// Puts this checkout's Worker into service, starting from whatever is +// there, including nothing. +// +// node release.mjs --sha +// the Worker named in wrangler.jsonc +// node release.mjs --sha --scratch +// the same steps on a Worker made for the purpose: removed first +// if it is there, so the start is nothing; removed again at the +// end. It shows that a stand-up from nothing works without the +// real Worker being touched. +// +// The steps: +// 1. No Worker of that name: stand up an empty one (init/). A version +// cannot be uploaded to a Worker that does not exist, and the +// storage behind the Durable Object class is only made by a deploy. +// 2. Upload this checkout as a version, tagged with the commit. It +// serves nothing yet. +// 3. Put that version at 100%. +// 4. Ask the Worker which version it is. If it does not answer as +// this one, put back the version that was serving, and fail. +// +// When wrangler.jsonc has a Durable Object migration the Worker has not +// had, steps 2 and 3 are one `wrangler deploy`: a version cannot carry a +// migration. +// +// Needs CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID in the +// environment, and `node build.mjs` to have been run. The decisions are +// in release-plan.mjs, where they are tested; this file does the doing. +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + configOf, + existence, + healthSays, + listed, + names, + plan, + removable, + scratchName, + servingVersion, + uploadedVersion, +} from "./release-plan.mjs"; + +const here = dirname(fileURLToPath(import.meta.url)); +// The PM_RELEASE_* settings exist for the tests, which stand in for +// Cloudflare and for the Worker's address (../test/release.test.ts). +const API = process.env.PM_RELEASE_API ?? "https://api.cloudflare.com/client/v4"; +// A Worker's first address can take a while to answer; one already +// there answers a new version within seconds. +const HEALTH_TRIES = Number(process.env.PM_RELEASE_HEALTH_TRIES ?? 40); +const HEALTH_WAIT_MS = Number(process.env.PM_RELEASE_HEALTH_WAIT_MS ?? 6_000); + +/** Stop before anything has been done: a bad argument, a missing setting. */ +function fail(message) { + console.error(`release.mjs: ${message}`); + process.exit(1); +} + +const args = process.argv.slice(2); +const flag = (name) => args.includes(name); +const value = (name) => { + const at = args.indexOf(name); + return at >= 0 ? args[at + 1] : undefined; +}; +for (const arg of args) { + if (arg.startsWith("--") && !["--sha", "--scratch"].includes(arg)) fail(`unknown option ${arg}`); +} + +let commit; +try { + commit = names(value("--sha") ?? ""); +} catch (error) { + fail(error.message); +} +const token = process.env.CLOUDFLARE_API_TOKEN ?? ""; +const account = process.env.CLOUDFLARE_ACCOUNT_ID ?? ""; +if (token === "" || account === "") fail("CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID must be set"); + +const real = configOf(readFileSync(join(here, "wrangler.jsonc"), "utf8")); +const empty = configOf(readFileSync(join(here, "init", "wrangler.jsonc"), "utf8")); +const scratch = flag("--scratch"); +const worker = scratch ? scratchName(real.name) : real.name; +const run = process.env.GITHUB_RUN_ID ? `workflow run ${process.env.GITHUB_RUN_ID}` : "a manual run"; + +const say = (line) => console.log(`release.mjs: ${line}`); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function api(method, path) { + const res = await fetch(`${API}${path}`, { method, headers: { authorization: `Bearer ${token}` } }); + const body = await res.json().catch(() => null); + return { status: res.status, body }; +} + +async function look() { + const { status, body } = await api("GET", `/accounts/${account}/workers/services/${worker}`); + const found = existence(status, body); + if (found.exists) return found; + // Absence is answered by deploying an empty Worker under this name, + // so it is asked a second way before it is believed. + const list = await api("GET", `/accounts/${account}/workers/scripts`); + if (listed(list.body, worker)) { + throw new Error(`Cloudflare says ${worker} does not exist and also lists it; doing nothing`); + } + return found; +} + +function wrangler(argv, outputFile) { + const done = spawnSync("npx", ["wrangler", ...argv], { + cwd: here, + stdio: "inherit", + env: { ...process.env, ...(outputFile ? { WRANGLER_OUTPUT_FILE_PATH: outputFile } : {}) }, + }); + if (done.status !== 0) throw new Error(`wrangler ${argv.slice(0, 2).join(" ")} failed`); +} + +async function serving() { + const { status, body } = await api("GET", `/accounts/${account}/workers/scripts/${worker}/deployments`); + return status === 200 ? servingVersion(body) : null; +} + +let address = null; +async function health() { + if (!address && process.env.PM_RELEASE_HEALTH) address = `${process.env.PM_RELEASE_HEALTH}/${worker}`; + if (!address) { + const { status, body } = await api("GET", `/accounts/${account}/workers/subdomain`); + const sub = body?.result?.subdomain; + if (status !== 200 || typeof sub !== "string") throw new Error("cannot read the account's workers.dev subdomain"); + address = `https://${worker}.${sub}.workers.dev/console/health`; + } + try { + const res = await fetch(address, { signal: AbortSignal.timeout(10_000), headers: { "cache-control": "no-cache" } }); + return await res.json(); + } catch { + return null; + } +} + +/** Wait for the Worker to answer as `want` says it should. */ +async function answers(want) { + let last = "silent"; + for (let attempt = 0; attempt < HEALTH_TRIES; attempt++) { + last = healthSays(await health(), commit.short); + if (last === want) return true; + await sleep(HEALTH_WAIT_MS); + } + say(`${worker} did not answer as ${want === "this" ? commit.short : want} (last answer: ${last})`); + return false; +} + +async function remove() { + if (!removable(worker, real.name)) { + throw new Error(`refusing to remove ${worker}: only the scratch Worker is ever removed`); + } + const { status, body } = await api("DELETE", `/accounts/${account}/workers/scripts/${worker}?force=true`); + if (status !== 200 && status !== 404) { + throw new Error(`could not remove ${worker}: http ${status} ${JSON.stringify(body?.errors ?? null)}`); + } + say(status === 404 ? `${worker} was not there` : `removed ${worker}`); +} + +/** The steps, in order. Says whether the Worker ended up serving this commit. */ +async function release() { + if (scratch) { + say(`starting from nothing on ${worker}`); + await remove(); + } + const found = await look(); + const steps = plan(found, real.migrationTag); + say( + `${worker}: ${found.exists ? `there (migration ${found.migrationTag ?? "none"})` : "not there"}; steps: ${steps.join(", ")}`, + ); + + if (steps.includes("stand-up")) { + wrangler(["deploy", "--config", "init/wrangler.jsonc", "--name", worker, "--message", `empty Worker, stood up by ${run}`]); + say(`stood up ${worker} empty`); + // On the scratch Worker the empty one is waited for: that it answers + // as empty is part of what the run is there to show. + if (scratch && !(await answers("empty"))) return false; + } + + if (steps.includes("deploy")) { + wrangler(["deploy", "--name", worker, "--var", `VERSION:${commit.short}`, "--message", commit.message]); + say(`deployed ${commit.short} to ${worker} in one step (its Durable Object classes changed)`); + return answers("this"); + } + + const before = await serving(); + const dir = mkdtempSync(join(tmpdir(), "pm-edge-release-")); + const out = join(dir, "wrangler.ndjson"); + let version; + try { + wrangler( + ["versions", "upload", "--name", worker, "--tag", commit.tag, "--message", commit.message, "--var", `VERSION:${commit.short}`], + out, + ); + version = uploadedVersion(readFileSync(out, "utf8"), worker); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + say(`uploaded ${commit.short} to ${worker} as version ${version}; it serves nothing yet`); + wrangler(["versions", "deploy", `${version}@100%`, "--name", worker, "--yes", "--message", commit.message]); + say(`put version ${version} at 100%`); + if (await answers("this")) return true; + if (before && before !== version) { + wrangler([ + "versions", + "deploy", + `${before}@100%`, + "--name", + worker, + "--yes", + "--message", + `put back: ${commit.short} did not answer its health check`, + ]); + say(`put version ${before} back at 100%`); + } + return false; +} + +let ok = false; +let trouble = null; +try { + ok = await release(); +} catch (error) { + trouble = error; +} +// The scratch Worker never outlives its run, however the run went. +if (scratch) { + try { + await remove(); + } catch (error) { + trouble ??= error; + } +} +if (trouble) fail(trouble.message); +if (!ok) fail(`${worker} is not serving ${commit.short}`); +say(scratch ? `${worker} stood up from nothing, served ${commit.short}, and is gone again` : `${worker} is serving ${commit.short}`); diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 492394a90e..365b055fbb 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -23,6 +23,7 @@ import { DIRECT_ACTIONS, DIRECT_READ_SECTIONS, directClasses, directRead } from import { Devices, KeyedLimiter, Limiter } from "../../src/devices.ts"; import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts"; import { + APK_LIMIT, type ApkReport, apkReport, type EdgeConfig, @@ -90,6 +91,8 @@ const SIGNATURE = /^[A-Za-z0-9_-]{86}$/; const SYNC_REFUSALS = 20; /** The Android build is kept in pieces of this many bytes. */ const APK_CHUNK = 512 * 1024; +/** The most pieces a build that may be carried can take. */ +const APK_PIECES = Math.ceil(APK_LIMIT / APK_CHUNK); /** A build that could not be kept is asked for again no sooner than this. */ const APK_RETRY_MS = 10 * 60_000; /** With no report for this long, the laptop is not there to ask. */ @@ -270,10 +273,19 @@ export class Edge { const sha256 = [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""); if (bytes.byteLength !== build.size || sha256 !== build.sha256) throw new Error("the build sent is not the build described"); - const before = await this.apkKept(); + // The record of the copy kept so far goes first. Its pieces are about + // to be written over, and a write that stops half-way must not leave + // pieces of two builds under a record that describes one of them. + // With no record there is no copy: nothing is handed out, and the + // build is asked for again. + if (await this.apkKept()) { + this.keptApk = null; + await this.kv.delete("apk"); + } const chunks = Math.ceil(bytes.byteLength / APK_CHUNK); for (let i = 0; i < chunks; i++) await this.kv.put(`apk:${i}`, bytes.slice(i * APK_CHUNK, (i + 1) * APK_CHUNK)); - for (let i = chunks; i < (before?.chunks ?? 0); i++) await this.kv.delete(`apk:${i}`); + // Pieces left by a larger build, whether or not its record survived. + for (let i = chunks; i < APK_PIECES; i++) await this.kv.delete(`apk:${i}`); this.keptApk = { sha256, size: build.size, at: build.at, chunks }; await this.kv.put("apk", this.keptApk); } diff --git a/pm-stack/console/edge/wrangler.jsonc b/pm-stack/console/edge/wrangler.jsonc index adf3a4aa02..6dcab57992 100644 --- a/pm-stack/console/edge/wrangler.jsonc +++ b/pm-stack/console/edge/wrangler.jsonc @@ -2,7 +2,8 @@ // The Worker in front of pm.security.cab: the app, its state, // notifications and the phone widget, served from Cloudflare. // - // Deployed by the pm-console-edge-deploy workflow (wrangler deploy). + // Deployed by the pm-console-edge-deploy workflow (release.mjs: an + // empty Worker from init/ if there is none, then this as a version). // It has no route here on purpose: scripts/expose.py on the host puts // the hostname's route on it once it answers its health check, and can // take the route away again, which is the whole rollback. diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index 7bbca73de9..1459101532 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -35,6 +35,9 @@ const FAST_MS = 5_000; const IDLE_MS = 30_000; const WATCHED_EVERY_MS = 60_000; const SYNC_TIMEOUT_MS = 20_000; +/** After a report that carried the Android build did not get through, + * the build is left out of the reports that follow for this long. */ +const APK_AGAIN_MS = 10 * 60_000; const DONE_KEPT = 300; type Fate = "started" | { ok: boolean; error?: string }; @@ -72,6 +75,12 @@ export class EdgeLink { private watchedAt = 0; private timer: ReturnType | null = null; private busy = false; + /** The Android build is not put in a report before this time. */ + private apkNotBefore = 0; + /** The last report left something out that the next should carry at + * once: the sections, when the build went alone, or everything but + * the build, when a report carrying it did not get through. */ + private more = false; /** Actions being done right now, by the name the edge gave them. */ private running = new Set(); private now: () => number; @@ -180,6 +189,14 @@ export class EdgeLink { this.acks.push({ id: held.id, ...fate }); } + /** The build could not be sent. It is left out of the reports that + * follow for a while: nothing about the build may stand in the way of + * an ordinary report, which is how the edge knows the host is there. */ + private holdBuild(why: string): void { + this.apkNotBefore = this.now() + APK_AGAIN_MS; + this.log(`${why}; reporting without it for ten minutes`); + } + /** One report to the edge. Returns its answer, or null if it could not * be reached or refused the report; nothing is lost either way. */ async once(): Promise { @@ -187,37 +204,63 @@ export class EdgeLink { this.busy = true; try { const pair = await this.keys(); + this.more = false; const snapshot = this.o.docs.snapshot(); let sections = snapshot.filter((s) => this.sent.get(s.name) !== s.hash || this.want.has(s.name)); const acks = [...this.acks]; const at = Math.max(this.now(), this.lastAt + 1); // The Android build: always what it is, and the build itself only - // when the edge has said it lacks this one. + // when the edge has said it lacks this one (and not for a while + // after it could not be sent). const build = (await this.o.apk?.().catch(() => null)) ?? null; const apk: ApkReport | null = build && build.size <= APK_LIMIT ? { sha256: build.sha256, size: build.size, at: build.at } : null; - if (apk && build && this.want.has("apk")) { - apk.data = Buffer.from(await build.read()).toString("base64"); - // The build and large sections together could pass what the edge - // takes in one report, and a report refused as too large would be - // built the same way again and again. So the build goes alone - // then; the sections are not marked sent and follow next time. - const others = sections.reduce((sum, s) => sum + JSON.stringify(s.data).length, 0); - if (apk.data.length + others > REPORT_ROOM) sections = []; + if (apk && build && this.want.has("apk") && this.now() >= this.apkNotBefore) { + try { + apk.data = Buffer.from(await build.read()).toString("base64"); + } catch (error) { + this.holdBuild(`the Android build could not be read (${(error as Error).message})`); + } + } + const config = await this.o.config(); + const have = Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])); + const phones = await this.o.phones.links(); + const acts = this.o.docs.recentActs(); + const encoded = (carried: typeof sections) => { + const message: SyncRequest & { acts: unknown } = { + v: 1, + at, + ...(this.o.version ? { version: this.o.version } : {}), + ...(apk ? { apk } : {}), + config, + sections: carried, + have, + acks, + phones, + acts, + }; + return new TextEncoder().encode(JSON.stringify(message)); + }; + let body = encoded(sections); + // The build and large sections together could pass what the edge + // takes in one report. Measured on the report as it would be sent, + // in bytes: when it is past the room there is, the build goes + // alone; the sections are not marked sent and follow at once. + if (apk?.data && sections.length > 0 && body.byteLength > REPORT_ROOM) { + sections = []; + body = encoded(sections); + this.more = true; } - const message: SyncRequest & { acts: unknown } = { - v: 1, - at, - ...(this.o.version ? { version: this.o.version } : {}), - ...(apk ? { apk } : {}), - config: await this.o.config(), - sections, - have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])), - acks, - phones: await this.o.phones.links(), - acts: this.o.docs.recentActs(), + // A report that carries the build is large and slow to send. If it + // does not get through, the same report again would not either, and + // while that went on the edge would hear nothing at all from this + // host. So the reports after it go without the build, the first of + // them at once. + const lost = () => { + if (!apk?.data) return; + this.holdBuild("a report carrying the Android build did not get through"); + this.more = true; }; - const body = new TextEncoder().encode(JSON.stringify(message)); let res: Response; try { res = await this.fetchImpl(`${this.o.url}/console/edge/sync`, { @@ -233,6 +276,7 @@ export class EdgeLink { }); } catch (error) { if (this.last) this.log(`cannot reach the edge: ${(error as Error).message}`); + lost(); this.last = null; return null; } @@ -243,6 +287,7 @@ export class EdgeLink { // gives (it ran backwards): step past it. if (res.status === 409 && typeof answer?.last === "number") this.lastAt = Math.max(this.lastAt, answer.last); if (this.last) this.log(`the edge refused the report: http ${res.status} ${answer?.error ?? ""}`); + lost(); this.last = null; return null; } @@ -271,10 +316,11 @@ export class EdgeLink { void this.o.docs.current(WATCHED, 0); } const answer = await this.once(); - // Something was done or is wanted: say so at once. + // Something was done, is wanted, or was left out of that report: + // say so at once. // (The Android build is not such a thing: it waits for the next // ordinary report, and half a megabyte is never sent in a hurry.) - if (this.acks.length > 0 || [...this.want].some((name) => name !== "apk")) return 500; + if (this.acks.length > 0 || this.more || [...this.want].some((name) => name !== "apk")) return 500; return answer?.watching || this.o.docs.watched() ? FAST_MS : IDLE_MS; } diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index b3ea25c41e..35555f294b 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -415,9 +415,12 @@ async function setup(options: { direct?: boolean } = {}) { const stored = new Map(); /** Every key written to the edge's storage, in order. */ const puts: string[] = []; + /** Keys the edge's storage refuses to write, as a store in trouble would. */ + const storeFails = new Set(); const kv: KV = { get: async (key) => structuredClone(stored.get(key)), put: async (key, value) => { + if (storeFails.has(key)) throw new Error(`storage: could not write ${key}`); puts.push(key); stored.set(key, structuredClone(value)); }, @@ -550,13 +553,25 @@ async function setup(options: { direct?: boolean } = {}) { audited.push(entry); }, }; - const net = { hostUp: true, edgeUp: true, loseAnswer: false, giveUpEarly: false }; + const net: { + hostUp: boolean; + edgeUp: boolean; + loseAnswer: boolean; + giveUpEarly: boolean; + /** A report of more than this many bytes does not get through: it + * is cut off on the way ("lost", a slow connection running out of + * time) or turned away by something in front of the edge ("refused"). */ + large: { over: number; fate: "lost" | "refused" } | null; + } = { hostUp: true, edgeUp: true, loseAnswer: false, giveUpEarly: false, large: null }; + /** The size of each report the host sent, whether or not it arrived. */ + const reportSizes: number[] = []; /** The signed Android build on the host, if any, and how often it was read to be sent. */ - const build: { bytes: Uint8Array | null; at: number; reads: number; corrupt: boolean } = { + const build: { bytes: Uint8Array | null; at: number; reads: number; corrupt: boolean; unreadable: boolean } = { bytes: null, at: 0, reads: 0, corrupt: false, + unreadable: false, }; /** Requests to the host still running after the edge stopped waiting. */ const stillRunning: Promise[] = []; @@ -623,6 +638,7 @@ async function setup(options: { direct?: boolean } = {}) { at: build.at, read: async () => { build.reads++; + if (build.unreadable) throw new Error("EACCES: permission denied"); return build.corrupt ? bytes.map((b) => b ^ 1) : bytes; }, }; @@ -636,6 +652,12 @@ async function setup(options: { direct?: boolean } = {}) { run: heldRunner(hostDeps), fetchImpl: (async (url: string, init: RequestInit) => { if (!net.edgeUp) throw new Error("no route to the edge"); + const size = (init.body as Uint8Array).byteLength; + reportSizes.push(size); + if (net.large && size > net.large.over) { + if (net.large.fate === "lost") throw new Error("The operation timed out."); + return new Response("bad gateway", { status: 502 }); + } return route( new Request(url, { ...init, headers: { ...(init.headers as Record), "cf-ray": "1" } }), io, @@ -699,6 +721,7 @@ async function setup(options: { direct?: boolean } = {}) { edge, makeEdge, stored, + storeFails, puts, keys, done, @@ -722,6 +745,7 @@ async function setup(options: { direct?: boolean } = {}) { core, hostReads, build, + reportSizes, failing, gate, stillRunning, @@ -1319,6 +1343,13 @@ describe("the Android build", () => { const res = await w.browse("/console/pm-console.apk"); return { res, bytes: new Uint8Array(await res.arrayBuffer()) }; }; + /** The questions as the edge holds them, put back together. */ + const questionsAtEdge = (w: Awaited>) => { + const pieces = (w.stored.get("m:questions") as { chunks: number } | undefined)?.chunks ?? 0; + let text = ""; + for (let i = 0; i < pieces; i++) text += String(w.stored.get(`m:questions:${i}`)); + return text === "" ? null : (JSON.parse(text) as Record); + }; test("a copy is kept at the edge, sent once, and served when the laptop is away", async () => { const w = await setup(); @@ -1421,16 +1452,157 @@ describe("the Android build", () => { w.data.questions = { sets: [{ id: "big", text: "q".repeat(3_000_000) }] }; w.now.t += 11_000; await w.hostReads(); - // Every report from here is accepted: none is refused as too large. - const answers = [await report(w), await report(w), await report(w)]; + // The build goes alone, and the host does not wait to send what it displaced. + w.now.t += 1_000; + expect(await w.link.now.turn()).toBe(500); + expect(w.link.now.last?.ok).toBe(true); + expect((w.stored.get("apk") as { size: number }).size).toBe(4_900_000); + expect(questionsAtEdge(w)).toEqual({ open: [] }); + // The questions arrive whole in the report after it, and then there is no hurry. + w.now.t += 1_000; + expect(await w.link.now.turn()).toBeGreaterThan(500); + expect(w.link.now.last?.ok).toBe(true); + expect((w.stored.get("m:questions") as { chunks: number }).chunks).toBeGreaterThan(1); + expect(questionsAtEdge(w)?.sets[0].text.length).toBe(3_000_000); + // No report was as large as the edge refuses (8 MiB), and the build's kept the room it is given. + expect(Math.max(...w.reportSizes)).toBeLessThanOrEqual(7.5 * 1024 * 1024); + }); + + test("room in a report is counted in bytes, so text outside ASCII cannot push it past the limit", async () => { + const w = await setup(); + await w.hostReads(); + await report(w); + w.build.bytes = apk(5, 4_900_000); + w.build.at = w.now.t; + await report(w); // described; the edge asks for it + // 700,000 characters, each three bytes as sent. Counted as characters + // they fit beside the build; as bytes the two are past what the edge takes. + const text = "\u65e5".repeat(700_000); + expect(new TextEncoder().encode(text).byteLength).toBe(2_100_000); + w.data.questions = { sets: [{ id: "wide", text }] }; + w.now.t += 11_000; + await w.hostReads(); + const answers = [await report(w), await report(w)]; expect(answers.every((answer) => answer?.ok === true)).toBe(true); + expect(Math.max(...w.reportSizes)).toBeLessThanOrEqual(7.5 * 1024 * 1024); expect((w.stored.get("apk") as { size: number }).size).toBe(4_900_000); - // And the questions arrived whole, in the report after the build's. - const pieces = (w.stored.get("m:questions") as { chunks: number } | undefined)?.chunks ?? 0; - expect(pieces).toBeGreaterThan(1); - let text = ""; - for (let i = 0; i < pieces; i++) text += String(w.stored.get(`m:questions:${i}`)); - expect(JSON.parse(text).sets[0].text.length).toBe(3_000_000); + expect(questionsAtEdge(w)?.sets[0].text).toBe(text); + }); + + test("a build that does not get through does not hold up the reports after it", async () => { + for (const fate of ["lost", "refused"] as const) { + const w = await setup(); + await w.hostReads(); + await report(w); + w.build.bytes = apk(1); + w.build.at = w.now.t; + expect((await report(w))?.want).toContain("apk"); // described; the edge asks for it + // A connection too slow for a report that large, or something in + // front of the edge that will not pass one. + w.net.large = { over: 500_000, fate }; + w.data.questions = { sets: [{ id: "new", text: "what next?" }] }; + w.now.t += 11_000; + await w.hostReads(); + // The report with the build in it fails. The host does not wait to + // send the next, and that one goes without the build... + w.now.t += 1_000; + expect(await w.link.now.turn()).toBe(500); + expect(w.link.now.last).toBeNull(); + expect(w.reportSizes.at(-1)).toBeGreaterThan(500_000); + w.now.t += 1_000; + expect(await w.link.now.turn()).toBeGreaterThan(500); + expect(w.link.now.last?.ok).toBe(true); + expect(w.reportSizes.at(-1)).toBeLessThan(500_000); + // ...and brings what had changed. + expect(questionsAtEdge(w)).toEqual({ sets: [{ id: "new", text: "what next?" }] }); + // An edge that cannot be reached at all is another matter: a report + // without the build that fails is not hurried after. + w.net.edgeUp = false; + w.now.t += 1_000; + expect(await w.link.now.turn()).toBeGreaterThan(500); + expect(w.link.now.last).toBeNull(); + w.net.edgeUp = true; + // The edge still asks for the build. For ten minutes it is not sent again. + for (let i = 0; i < 20; i++) expect((await report(w))?.want).toContain("apk"); + expect(w.build.reads).toBe(1); + // Then it is tried once more. If that fails too, again only that one report is lost. + w.now.t += 10 * 60_000; + expect(await report(w)).toBeNull(); + expect(w.build.reads).toBe(2); + expect((await report(w))?.ok).toBe(true); + expect(w.build.reads).toBe(2); + // On a connection that can carry it, it arrives at the next try. + w.net.large = null; + w.now.t += 10 * 60_000; + expect((await report(w))?.want).not.toContain("apk"); + expect(w.build.reads).toBe(3); + expect((w.stored.get("apk") as { size: number }).size).toBe(700_000); + } + }); + + test("a copy whose replacement stops half-way is not handed out as either build", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(1, 1_500_000); + w.build.at = w.now.t; + await report(w); + await report(w); + expect((w.stored.get("apk") as { chunks: number }).chunks).toBe(3); + // A newer build arrives, and the edge's storage fails on its second piece. + w.build.bytes = apk(2, 1_500_000); + w.build.at = w.now.t + 500; + await report(w); // described; the edge asks for it + w.storeFails.add("apk:1"); + expect((await report(w))?.ok).toBe(true); // the report itself is taken + // The first piece is now the new build's and the rest are the old one's. + // There is no record over them: the edge has no copy, and says so. + expect(w.stored.has("apk")).toBe(false); + const health = (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect(health.androidBuild).toBeNull(); + // The laptop goes away. Nothing is handed out from those pieces. + w.net.hostUp = false; + w.now.t += 2 * 60_000; + expect((await download(w)).res.status).not.toBe(200); + // It comes back with a smaller build. That one is kept whole, and the + // pieces of the larger ones before it are gone, record or no record. + w.net.hostUp = true; + w.storeFails.clear(); + w.build.bytes = apk(3, 400_000); + w.build.at = w.now.t + 500; + expect((await report(w))?.want).toContain("apk"); + expect((await report(w))?.want).not.toContain("apk"); + expect([...w.stored.keys()].filter((k) => /^apk:\d+$/.test(k))).toEqual(["apk:0"]); + w.net.hostUp = false; + w.now.t += 2 * 60_000; + const got = await download(w); + expect(got.res.status).toBe(200); + expect(got.bytes).toEqual(apk(3, 400_000)); + }); + + test("a build that cannot be read is left out, and the report goes anyway", async () => { + const w = await setup(); + await w.hostReads(); + await report(w); + w.build.bytes = apk(4); + w.build.at = w.now.t; + expect((await report(w))?.want).toContain("apk"); + w.build.unreadable = true; + w.data.questions = { sets: [{ id: "new", text: "what next?" }] }; + w.now.t += 11_000; + await w.hostReads(); + // The report is not given up for the build's sake. + expect((await report(w))?.ok).toBe(true); + expect(questionsAtEdge(w)).toEqual({ sets: [{ id: "new", text: "what next?" }] }); + expect(w.build.reads).toBe(1); + // Nor is the file tried again with every report. + for (let i = 0; i < 20; i++) expect((await report(w))?.ok).toBe(true); + expect(w.build.reads).toBe(1); + // Ten minutes on it can be read, and is sent. + w.build.unreadable = false; + w.now.t += 10 * 60_000; + expect((await report(w))?.want).not.toContain("apk"); + expect(w.build.reads).toBe(2); + expect((w.stored.get("apk") as { size: number }).size).toBe(700_000); }); test("a build that is not the one described is not kept, and one too large is not sent", async () => { diff --git a/pm-stack/console/test/release.test.ts b/pm-stack/console/test/release.test.ts new file mode 100644 index 0000000000..eadf42fbdf --- /dev/null +++ b/pm-stack/console/test/release.test.ts @@ -0,0 +1,509 @@ +// The Worker's release (edge/release.mjs): what it decides, and what it +// does, run for real against a stand-in for Cloudflare's API and a +// stand-in for wrangler that records what it was asked to do. +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + configOf, + existence, + healthSays, + isVersionId, + listed, + names, + plan, + removable, + scratchName, + servingVersion, + uploadedVersion, +} from "../edge/release-plan.mjs"; + +const EDGE = join(import.meta.dir, "..", "edge"); +const SHA = "0123456789abcdef0123456789abcdef01234567"; +const SHORT = SHA.slice(0, 12); +const V = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`; + +describe("what a release decides", () => { + test("a commit's names", () => { + expect(names(SHA)).toEqual({ short: SHORT, tag: `git-${SHORT}`, message: `git ${SHA}` }); + for (const bad of ["", "abc", SHORT, `${SHA}0`, SHA.toUpperCase(), `${SHA.slice(0, 39)}g`]) { + expect(() => names(bad)).toThrow(); + } + }); + + test("the two configurations agree on everything that is not a version's own", () => { + const real = configOf(readFileSync(join(EDGE, "wrangler.jsonc"), "utf8")); + const empty = configOf(readFileSync(join(EDGE, "init", "wrangler.jsonc"), "utf8")); + expect(real.name).toBe("pm-console-edge"); + expect(real.migrationTag).toBe("v1"); + // The empty Worker is stood up under the same name, with the same + // class behind the same binding and the same migrations: that is + // what lets the real one be uploaded over it as a version. + for (const key of [ + "name", + "compatibility_date", + "compatibility_flags", + "workers_dev", + "preview_urls", + "observability", + "durable_objects", + "migrations", + ]) { + expect(empty.config[key]).toEqual(real.config[key]); + } + expect(empty.migrationTag).toBe(real.migrationTag); + // And it has nothing of the app in it. + expect(empty.config.assets).toBeUndefined(); + expect(empty.config.main).toBe("worker.ts"); + }); + + test("a configuration is read past its comments, and one that names no Worker is refused", () => { + const text = `{ + // a line comment with "quotes" and a // second marker + "name": "pm-x", /* a block + comment */ "vars": { "URL": "https://example.test//path", "S": "a /* not a comment */ b" }, + "migrations": [{ "tag": "v1" }, { "tag": "v2", "new_sqlite_classes": ["A"] },], + }`; + const got = configOf(text); + expect(got.name).toBe("pm-x"); + expect(got.migrationTag).toBe("v2"); + expect(got.config.vars).toEqual({ URL: "https://example.test//path", S: "a /* not a comment */ b" }); + expect(configOf('{"name":"pm-x"}').migrationTag).toBeNull(); + expect(() => configOf("{}")).toThrow(); + expect(() => configOf('{"name":"Not A Worker"}')).toThrow(); + expect(() => configOf('{"name":"x" /* never ends')).toThrow(); + }); + + test("only a plain 'no such Worker' counts as absent", () => { + const there = { success: true, result: { default_environment: { script: { migration_tag: "v1" } } } }; + expect(existence(200, there)).toEqual({ exists: true, migrationTag: "v1" }); + expect(existence(200, { success: true, result: {} })).toEqual({ exists: true, migrationTag: null }); + for (const code of [10007, 10090]) { + expect(existence(404, { success: false, errors: [{ code }] })).toEqual({ exists: false, migrationTag: null }); + } + // Anything else is not an answer, and nothing is deployed on it. + expect(() => existence(404, { success: false, errors: [{ code: 7003 }] })).toThrow(); + expect(() => existence(404, null)).toThrow(); + expect(() => existence(403, { success: false, errors: [{ code: 10000 }] })).toThrow(); + expect(() => existence(500, { success: false, errors: [{ code: 10007 }] })).toThrow(); + expect(() => existence(200, { success: false })).toThrow(); + }); + + test("the list of Workers is read by exact name", () => { + const body = { success: true, result: [{ id: "pm-console-edge-scratch" }, { id: "message-bridge" }] }; + expect(listed(body, "pm-console-edge-scratch")).toBe(true); + expect(listed(body, "pm-console-edge")).toBe(false); + expect(() => listed({ success: false }, "x")).toThrow(); + expect(() => listed(null, "x")).toThrow(); + }); + + test("the steps for what is there", () => { + expect(plan({ exists: false, migrationTag: null }, "v1")).toEqual(["stand-up", "upload", "promote"]); + expect(plan({ exists: true, migrationTag: "v1" }, "v1")).toEqual(["upload", "promote"]); + // A migration the Worker has not had cannot travel in a version. + expect(plan({ exists: true, migrationTag: "v1" }, "v2")).toEqual(["deploy"]); + expect(plan({ exists: true, migrationTag: null }, "v1")).toEqual(["deploy"]); + }); + + test("only the scratch Worker may be removed", () => { + expect(scratchName("pm-console-edge")).toBe("pm-console-edge-scratch"); + expect(removable("pm-console-edge-scratch", "pm-console-edge")).toBe(true); + expect(removable("pm-console-edge", "pm-console-edge")).toBe(false); + expect(removable("message-bridge", "pm-console-edge")).toBe(false); + expect(removable("pm-console-edge-scratch-scratch", "pm-console-edge")).toBe(false); + expect(removable("", "")).toBe(false); + }); + + test("the uploaded version is the one wrangler names for this Worker", () => { + const lines = [ + JSON.stringify({ type: "wrangler-session", version: 1 }), + "not json", + JSON.stringify({ type: "version-upload", worker_name: "another", version_id: V(1) }), + JSON.stringify({ type: "version-upload", worker_name: "pm-console-edge", version_id: V(2) }), + "", + ].join("\n"); + expect(uploadedVersion(lines, "pm-console-edge")).toBe(V(2)); + expect(() => uploadedVersion(lines, "pm-console-edge-scratch")).toThrow(); + expect(() => uploadedVersion("", "pm-console-edge")).toThrow(); + const odd = JSON.stringify({ + type: "version-upload", + worker_name: "pm-console-edge", + version_id: "latest; rm -rf", + }); + expect(() => uploadedVersion(odd, "pm-console-edge")).toThrow(); + }); + + test("the version to put back is the one serving everything, or none", () => { + const one = { result: { deployments: [{ versions: [{ version_id: V(7), percentage: 100 }] }] } }; + expect(servingVersion(one)).toBe(V(7)); + const split = { + result: { + deployments: [ + { + versions: [ + { version_id: V(7), percentage: 90 }, + { version_id: V(8), percentage: 10 }, + ], + }, + ], + }, + }; + expect(servingVersion(split)).toBeNull(); + expect(servingVersion({ result: { deployments: [] } })).toBeNull(); + expect(servingVersion(null)).toBeNull(); + expect( + servingVersion({ result: { deployments: [{ versions: [{ version_id: "x", percentage: 100 }] }] } }), + ).toBeNull(); + expect(isVersionId(V(1))).toBe(true); + expect(isVersionId("latest")).toBe(false); + }); + + test("what a health answer means", () => { + expect(healthSays({ ok: true, edge: true, version: SHORT }, SHORT)).toBe("this"); + expect(healthSays({ ok: true, edge: true, version: "ffffffffffff" }, SHORT)).toBe("another"); + expect(healthSays({ ok: false, edge: true, empty: true }, SHORT)).toBe("empty"); + // Something else answering on that address is not this Worker. + expect(healthSays({ ok: true, version: SHORT }, SHORT)).toBe("silent"); + expect(healthSays(null, SHORT)).toBe("silent"); + expect(healthSays("", SHORT)).toBe("silent"); + }); +}); + +// ---- the release, run ------------------------------------------------------ + +interface FakeWorker { + migrationTag: string | null; + /** Version id to what that version answers on its health address. */ + versions: Map; + serving: string | null; +} + +describe("a release, run against stand-ins", () => { + const account = "acct"; + const state = { + workers: new Map(), + /** What was done, in order: wrangler's commands and the API's changes. */ + did: [] as string[], + next: 100, + /** Knobs for what goes wrong. */ + uploadFails: false, + appNeverAnswers: false, + emptyNeverAnswers: false, + existenceStatus: 0, + hiddenFromServices: false, + removeFails: false, + }; + let server: ReturnType; + let bin: string; + + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + const flagValue = (argv: string[], name: string) => argv[argv.indexOf(name) + 1]; + + /** wrangler's part: change the state the way the real command would. */ + const wrangler = (argv: string[]): { status: number; write?: string } => { + state.did.push(`wrangler ${argv.join(" ")}`); + const name = flagValue(argv, "--name"); + const id = V(state.next++); + if (argv[0] === "deploy") { + const config = flagValue(argv, "--config"); + const made = state.workers.get(name) ?? { migrationTag: null, versions: new Map(), serving: null }; + made.migrationTag = "v1"; + if (config === "init/wrangler.jsonc") made.versions.set(id, { kind: "empty" }); + else made.versions.set(id, { kind: "app", short: flagValue(argv, "--var").replace("VERSION:", "") }); + made.serving = id; + state.workers.set(name, made); + return { status: 0 }; + } + const worker = state.workers.get(name); + if (!worker) return { status: 1 }; + if (argv[0] === "versions" && argv[1] === "upload") { + if (state.uploadFails) return { status: 1 }; + worker.versions.set(id, { kind: "app", short: flagValue(argv, "--var").replace("VERSION:", "") }); + return { + status: 0, + write: JSON.stringify({ type: "version-upload", version: 1, worker_name: name, version_id: id }), + }; + } + if (argv[0] === "versions" && argv[1] === "deploy") { + const version = argv[2].replace("@100%", ""); + if (!worker.versions.has(version) || !argv.includes("--yes")) return { status: 1 }; + worker.serving = version; + return { status: 0 }; + } + return { status: 1 }; + }; + + beforeAll(() => { + server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + async fetch(req) { + const url = new URL(req.url); + const path = url.pathname; + if (path === "/_wrangler") return json(wrangler((await req.json()) as string[])); + const health = path.match(/^\/health\/([^/]+)$/); + if (health) { + const worker = state.workers.get(health[1]); + const serving = worker?.serving ? worker.versions.get(worker.serving) : undefined; + if (!serving) return new Response("no such Worker", { status: 404 }); + if (serving.kind === "empty") { + if (state.emptyNeverAnswers) return new Response("error code: 1042", { status: 404 }); + return json({ ok: false, edge: true, empty: true }, 503); + } + if (state.appNeverAnswers) return new Response("error code: 1101", { status: 500 }); + return json({ ok: true, edge: true, version: serving.short }); + } + if (req.headers.get("authorization") !== "Bearer cf-test") + return json({ success: false, errors: [{ code: 10000 }] }, 403); + const base = `/api/accounts/${account}/workers`; + const service = path.match(new RegExp(`^${base}/services/([^/]+)$`)); + if (service && req.method === "GET") { + if (state.existenceStatus) return json({ success: false, errors: [{ code: 10000 }] }, state.existenceStatus); + const worker = state.workers.get(service[1]); + if (!worker || state.hiddenFromServices) return json({ success: false, errors: [{ code: 10090 }] }, 404); + return json({ + success: true, + result: { default_environment: { script: { migration_tag: worker.migrationTag } } }, + }); + } + if (path === `${base}/scripts` && req.method === "GET") { + return json({ success: true, result: [...state.workers.keys()].map((id) => ({ id })) }); + } + const deployments = path.match(new RegExp(`^${base}/scripts/([^/]+)/deployments$`)); + if (deployments && req.method === "GET") { + const worker = state.workers.get(deployments[1]); + if (!worker) return json({ success: false, errors: [{ code: 10007 }] }, 404); + const versions = worker.serving ? [{ version_id: worker.serving, percentage: 100 }] : []; + return json({ success: true, result: { deployments: [{ versions }] } }); + } + const script = path.match(new RegExp(`^${base}/scripts/([^/]+)$`)); + if (script && req.method === "DELETE") { + state.did.push(`api DELETE ${script[1]} force=${url.searchParams.get("force")}`); + if (state.removeFails) return json({ success: false, errors: [{ code: 10013 }] }, 500); + if (!state.workers.delete(script[1])) return json({ success: false, errors: [{ code: 10007 }] }, 404); + return json({ success: true, result: null }); + } + return json({ success: false, errors: [{ code: 7003 }] }, 404); + }, + }); + // A stand-in for `npx`: it tells the server what wrangler was asked, + // and does what the server says a real run would have done. + bin = mkdtempSync(join(tmpdir(), "pm-release-test-")); + writeFileSync( + join(bin, "npx"), + `#!/usr/bin/env bun +const argv = process.argv.slice(2); +if (argv[0] !== "wrangler") process.exit(64); +const res = await fetch(process.env.FAKE_CONTROL, { method: "POST", body: JSON.stringify(argv.slice(1)) }); +const { status, write } = await res.json(); +if (write) (await import("node:fs")).appendFileSync(process.env.WRANGLER_OUTPUT_FILE_PATH, write + "\\n"); +process.exit(status); +`, + ); + chmodSync(join(bin, "npx"), 0o755); + }); + + afterAll(() => { + server.stop(true); + rmSync(bin, { recursive: true, force: true }); + }); + + const reset = (workers: Record = {}) => { + state.workers = new Map(Object.entries(workers)); + state.did = []; + state.next = 100; + state.uploadFails = false; + state.appNeverAnswers = false; + state.emptyNeverAnswers = false; + state.existenceStatus = 0; + state.hiddenFromServices = false; + state.removeFails = false; + }; + const worker = (short: string, migrationTag: string | null = "v1"): FakeWorker => ({ + migrationTag, + versions: new Map([[V(1), { kind: "app", short }]]), + serving: V(1), + }); + const release = async (...args: string[]) => { + const origin = `http://127.0.0.1:${server.port}`; + const run = Bun.spawn(["bun", join(EDGE, "release.mjs"), "--sha", SHA, ...args], { + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + CLOUDFLARE_API_TOKEN: "cf-test", + CLOUDFLARE_ACCOUNT_ID: account, + PM_RELEASE_API: `${origin}/api`, + PM_RELEASE_HEALTH: `${origin}/health`, + PM_RELEASE_HEALTH_TRIES: "3", + PM_RELEASE_HEALTH_WAIT_MS: "5", + FAKE_CONTROL: `${origin}/_wrangler`, + GITHUB_RUN_ID: "77", + }, + stdout: "pipe", + stderr: "pipe", + }); + const [out, err, code] = await Promise.all([ + new Response(run.stdout).text(), + new Response(run.stderr).text(), + run.exited, + ]); + return { code, out, err }; + }; + const serving = (name: string) => { + const w = state.workers.get(name); + return w?.serving ? w.versions.get(w.serving) : undefined; + }; + const REAL = "pm-console-edge"; + const SCRATCH = "pm-console-edge-scratch"; + + test("a Worker that is there gets a new version, uploaded and then promoted", async () => { + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + const got = await release(); + expect(got.code).toBe(0); + expect(state.did).toEqual([ + `wrangler versions upload --name ${REAL} --tag git-${SHORT} --message git ${SHA} --var VERSION:${SHORT}`, + `wrangler versions deploy ${V(100)}@100% --name ${REAL} --yes --message git ${SHA}`, + ]); + expect(serving(REAL)).toEqual({ kind: "app", short: SHORT }); + expect(got.out).toContain(`${REAL} is serving ${SHORT}`); + }); + + test("with no Worker there, an empty one is stood up first and the version goes over it", async () => { + reset(); + const got = await release(); + expect(got.code).toBe(0); + expect(state.did).toEqual([ + `wrangler deploy --config init/wrangler.jsonc --name ${REAL} --message empty Worker, stood up by workflow run 77`, + `wrangler versions upload --name ${REAL} --tag git-${SHORT} --message git ${SHA} --var VERSION:${SHORT}`, + `wrangler versions deploy ${V(101)}@100% --name ${REAL} --yes --message git ${SHA}`, + ]); + expect(serving(REAL)).toEqual({ kind: "app", short: SHORT }); + }); + + test("a Worker whose classes differ from the configuration gets one full deploy", async () => { + reset({ [REAL]: worker("aaaaaaaaaaaa", "v0") }); + const got = await release(); + expect(got.code).toBe(0); + expect(state.did).toEqual([`wrangler deploy --name ${REAL} --var VERSION:${SHORT} --message git ${SHA}`]); + expect(serving(REAL)).toEqual({ kind: "app", short: SHORT }); + // If what it deployed does not answer, the run fails. There is no + // putting back across a change of classes. + reset({ [REAL]: worker("aaaaaaaaaaaa", "v0") }); + state.appNeverAnswers = true; + const bad = await release(); + expect(bad.code).toBe(1); + expect(state.did.length).toBe(1); + }); + + test("a version that does not answer is taken off again, and the run fails", async () => { + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + state.appNeverAnswers = true; + const got = await release(); + expect(got.code).toBe(1); + expect(state.did).toEqual([ + `wrangler versions upload --name ${REAL} --tag git-${SHORT} --message git ${SHA} --var VERSION:${SHORT}`, + `wrangler versions deploy ${V(100)}@100% --name ${REAL} --yes --message git ${SHA}`, + `wrangler versions deploy ${V(1)}@100% --name ${REAL} --yes --message put back: ${SHORT} did not answer its health check`, + ]); + // What was serving before is serving again. + expect(serving(REAL)).toEqual({ kind: "app", short: "aaaaaaaaaaaa" }); + expect(got.err).toContain(`${REAL} is not serving ${SHORT}`); + }); + + test("an upload that fails changes nothing that is serving", async () => { + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + state.uploadFails = true; + const got = await release(); + expect(got.code).toBe(1); + expect(state.did.length).toBe(1); + expect(serving(REAL)).toEqual({ kind: "app", short: "aaaaaaaaaaaa" }); + }); + + test("nothing is stood up on an answer that is not plainly 'no such Worker'", async () => { + // Refused: the token cannot see Workers. + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + state.existenceStatus = 403; + let got = await release(); + expect(got.code).toBe(1); + expect(state.did).toEqual([]); + // Two answers that disagree: one says it is not there, the list has it. + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + state.hiddenFromServices = true; + got = await release(); + expect(got.code).toBe(1); + expect(state.did).toEqual([]); + expect(got.err).toContain("doing nothing"); + expect(serving(REAL)).toEqual({ kind: "app", short: "aaaaaaaaaaaa" }); + }); + + test("the scratch run starts from nothing, shows each step, and leaves nothing behind", async () => { + // A scratch Worker left by a run that was cut off, and the real one in service. + reset({ [REAL]: worker("aaaaaaaaaaaa"), [SCRATCH]: worker("bbbbbbbbbbbb", "v0") }); + const got = await release("--scratch"); + expect(got.code).toBe(0); + expect(state.did).toEqual([ + `api DELETE ${SCRATCH} force=true`, + `wrangler deploy --config init/wrangler.jsonc --name ${SCRATCH} --message empty Worker, stood up by workflow run 77`, + `wrangler versions upload --name ${SCRATCH} --tag git-${SHORT} --message git ${SHA} --var VERSION:${SHORT}`, + `wrangler versions deploy ${V(101)}@100% --name ${SCRATCH} --yes --message git ${SHA}`, + `api DELETE ${SCRATCH} force=true`, + ]); + expect(state.workers.has(SCRATCH)).toBe(false); + // The real Worker was never named. + expect(serving(REAL)).toEqual({ kind: "app", short: "aaaaaaaaaaaa" }); + expect(got.out).toContain("stood up from nothing"); + }); + + test("the scratch Worker is removed even when its run fails", async () => { + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + state.uploadFails = true; + let got = await release("--scratch"); + expect(got.code).toBe(1); + expect(state.did.at(-1)).toBe(`api DELETE ${SCRATCH} force=true`); + expect(state.workers.has(SCRATCH)).toBe(false); + // And when its version never answers. + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + state.appNeverAnswers = true; + got = await release("--scratch"); + expect(got.code).toBe(1); + expect(state.workers.has(SCRATCH)).toBe(false); + expect(state.workers.has(REAL)).toBe(true); + }); + + test("the scratch run waits to hear the empty Worker before it goes on", async () => { + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + state.emptyNeverAnswers = true; + const got = await release("--scratch"); + expect(got.code).toBe(1); + // It was stood up, never answered as empty, and was removed: no version was uploaded to it. + expect(state.did).toEqual([ + `api DELETE ${SCRATCH} force=true`, + `wrangler deploy --config init/wrangler.jsonc --name ${SCRATCH} --message empty Worker, stood up by workflow run 77`, + `api DELETE ${SCRATCH} force=true`, + ]); + // The real Worker's stand-up does not wait on it: the upload follows at once. + reset(); + state.emptyNeverAnswers = true; + expect((await release()).code).toBe(0); + expect(serving(REAL)).toEqual({ kind: "app", short: SHORT }); + }); + + test("a scratch Worker that cannot be removed fails the run", async () => { + reset({ [SCRATCH]: worker("bbbbbbbbbbbb") }); + state.removeFails = true; + const got = await release("--scratch"); + expect(got.code).toBe(1); + // Nothing was stood up on top of what could not be cleared. + expect(state.did.filter((line) => line.startsWith("wrangler"))).toEqual([]); + }); + + test("bad arguments stop it before anything is asked or done", async () => { + reset({ [REAL]: worker("aaaaaaaaaaaa") }); + const got = await release("--name", "message-bridge"); + expect(got.code).toBe(1); + expect(got.err).toContain("unknown option --name"); + expect(state.did).toEqual([]); + }); +});