diff --git a/lib/default.nix b/lib/default.nix index 29668d5d31..c60504dfcd 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -702,6 +702,8 @@ let queueTransportAlert = pkgs.callPackage ../pkgs/queue-transport-alert/worker/package.nix { }; queueTransportAlertDeploy = pkgs.callPackage ../pkgs/queue-transport-alert/worker/deploy.nix { inherit queueTransportAlert; + cf = pkgs.callPackage ../pkgs/cf { }; + wrangler = pkgs.callPackage ../pkgs/wrangler { }; }; messageBridge = pkgs.callPackage ../pkgs/message-bridge/worker/package.nix { }; messageBridgeDeploy = pkgs.callPackage ../pkgs/message-bridge/worker/deploy.nix { @@ -796,7 +798,7 @@ let cold-store-rehydrator-deploy = mkApp coldStoreRehydratorDeploy "Deploy the cold-store-rehydrator Worker from its flake bundle via the wrangler versions flow (needs Bitwarden and sops access)"; lab-ops-hub-deploy = mkApp labOpsHubDeploy "Deploy the lab-ops-hub Worker and push its crawler container image as one command (needs Bitwarden and sops access)"; cf-container-hello-deploy = mkApp cfContainerHelloDeploy "Deploy the cf-container-hello Worker from its flake package (needs Bitwarden and sops access)"; - queue-transport-alert-deploy = mkApp queueTransportAlertDeploy "Deploy the queue-transport-alert Worker (broker outage alert, code#6369) from its flake package and set its secrets (needs Bitwarden and sops access)"; + queue-transport-alert-deploy = mkApp queueTransportAlertDeploy "Deploy the queue-transport-alert Worker (broker outage alert, code#6369) from its flake package via the cf versions flow (needs Bitwarden and sops access)"; message-bridge-deploy = mkApp messageBridgeDeploy "Deploy the message-bridge Worker (Claude custom connector that sends and receives messages, plus history page) from its flake package and set its access token; --print-urls prints the connector URL, --code-only uploads code only with Cloudflare env vars (CI) (needs Bitwarden and sops access)"; mcpx = { type = "app"; diff --git a/pkgs/queue-transport-alert/worker/README.md b/pkgs/queue-transport-alert/worker/README.md index 4c80d47e84..ca9711eb57 100644 --- a/pkgs/queue-transport-alert/worker/README.md +++ b/pkgs/queue-transport-alert/worker/README.md @@ -69,23 +69,41 @@ issue when both run. State lives in one SQLite-backed Durable Object. From a checkout of this repo, with Bitwarden and sops access: ```bash -nix run .#queue-transport-alert-deploy -- --dry-run # bundle only -nix run .#queue-transport-alert-deploy # deploy + set secrets +nix run .#queue-transport-alert-deploy -- --dry-run # build only +nix run .#queue-transport-alert-deploy # upload + deploy HEAD +nix run .#queue-transport-alert-deploy -- --deploy-version # roll back ``` -The app stages the flake package (`package.nix`), runs -`wrangler deploy`, then `wrangler secret bulk` from stdin with these -values read from Bitwarden by name (override with the env vars): - -| Worker secret | Bitwarden name (env override) | -| ---------------------- | ----------------------------------------------------------------------------------------------------- | -| `ACCESS_CLIENT_ID` | `cloudflare.access.queue-broker-client-id` (`QTA_ACCESS_ID_SECRET`) | -| `ACCESS_CLIENT_SECRET` | `cloudflare.access.queue-broker-client-secret` (`QTA_ACCESS_SECRET_SECRET`) | -| `GITHUB_TOKEN` | `github.developing-today-code-automation` (`QTA_GITHUB_TOKEN_SECRET`) | -| `TELEGRAM_BOT_TOKEN` | `openclaw.telegram-bot-token` (`QTA_TELEGRAM_SECRET`) | -| `BROKER_AGENT_TOKEN` | the file `~/.config/queue-broker/token` (`QTA_BROKER_TOKEN_FILE`); left as is when the file is absent | - -Wrangler itself uses `cloudflare.api-token-day-to-day` +It uses the `cf` CLI's versions flow, the same standard as +`pkarr-deploy`, with `cloudflare.config.ts` as the deploy config +(`wrangler.jsonc` mirrors it for `wrangler dev`; `test/config.test.mjs` +keeps the two in step). The app stages the flake package +(`package.nix`), links `cf/config` and wrangler (cf's build bridge) from +the Nix store, then: + +1. `cf workers versions create --tag git-` uploads a version + with its secrets read from stdin (`--secrets-file /dev/stdin`); + nothing goes live yet. +2. `cf workers deployments create` puts that version at 100%. +3. `cf workers triggers deploy` applies the cron schedule. +4. It checks the latest deployment serves that version and that + `/status.json` answers. + +Every version carries its own secrets, so `--deploy-version ` rolls +back to an older version as it was, without uploading anything +(`cf workers versions list --worker-id queue-transport-alert` lists the +ids). The secrets come from Bitwarden by name (override with the env +vars); one left out of an upload keeps the previous version's value: + +| Worker secret | Bitwarden name (env override) | +| ---------------------- | ------------------------------------------------------------------------------------------------------- | +| `ACCESS_CLIENT_ID` | `cloudflare.access.queue-broker-client-id` (`QTA_ACCESS_ID_SECRET`) | +| `ACCESS_CLIENT_SECRET` | `cloudflare.access.queue-broker-client-secret` (`QTA_ACCESS_SECRET_SECRET`) | +| `GITHUB_TOKEN` | `github.developing-today-code-automation` (`QTA_GITHUB_TOKEN_SECRET`) | +| `TELEGRAM_BOT_TOKEN` | `openclaw.telegram-bot-token` (`QTA_TELEGRAM_SECRET`) | +| `BROKER_AGENT_TOKEN` | the file `~/.config/queue-broker/token` (`QTA_BROKER_TOKEN_FILE`); carried over when the file is absent | + +cf itself uses `cloudflare.api-token-day-to-day` (`QTA_CF_TOKEN_SECRET`). It is also in the deploy registry as `queue-transport-alert` (`deploy list`). diff --git a/pkgs/queue-transport-alert/worker/cloudflare.config.ts b/pkgs/queue-transport-alert/worker/cloudflare.config.ts new file mode 100644 index 0000000000..78ba1767bb --- /dev/null +++ b/pkgs/queue-transport-alert/worker/cloudflare.config.ts @@ -0,0 +1,42 @@ +import { bindings, defineConfig, exports, triggers } from "cf/config"; +import * as entrypoint from "./src/index.js" with { type: "cf-worker" }; + +// queue-transport-alert Worker (code#6369): the deploy source of truth +// for the cf versions flow (deploy.mjs, `nix run +// .#queue-transport-alert-deploy`). wrangler.jsonc mirrors it for local +// `wrangler dev`; test/config.test.mjs keeps the two in step. +export default defineConfig({ + worker: { + name: "queue-transport-alert", + compatibilityDate: "2026-10-25", + entrypoint, + observability: { enabled: true }, + triggers: [triggers.scheduled({ schedule: "*/10 * * * *" })], + exports: { + // Created by the wrangler `new_sqlite_classes` migration (tag v1); + // declared here so the namespace and its state carry over. + TransportState: exports.durableObject({ storage: "sqlite" }), + }, + env: { + TRANSPORT_STATE: bindings.durableObject({ worker: "queue-transport-alert", exportName: "TransportState" }), + BROKER_URL: bindings.text("https://queue-broker.security.cab"), + REPO: bindings.text("developing-today/code"), + THRESHOLD: bindings.text("2"), + PROBE_TIMEOUT_MS: bindings.text("10000"), + QUEUE: bindings.text("repo-health-code-pilot"), + // Drew's Telegram user id (DM with @shed_openclaw_bot); also in home/openclaw. + TELEGRAM_CHAT_ID: bindings.text("8290042325"), + PUBLIC_URL: bindings.text("https://queue-transport-alert.developing-today.workers.dev"), + // "true" files/comments on incidents, pushes and enqueues; anything else only logs. + APPLY: bindings.text("true"), + // Uploaded with each version by deploy.mjs (--secrets-file from + // stdin); a secret missing from that upload inherits the previous + // version's value. + ACCESS_CLIENT_ID: bindings.secret(), + ACCESS_CLIENT_SECRET: bindings.secret(), + GITHUB_TOKEN: bindings.secret(), + TELEGRAM_BOT_TOKEN: bindings.secret(), + BROKER_AGENT_TOKEN: bindings.secret(), + }, + }, +}); diff --git a/pkgs/queue-transport-alert/worker/deploy-lib.mjs b/pkgs/queue-transport-alert/worker/deploy-lib.mjs new file mode 100644 index 0000000000..11d0f54e97 --- /dev/null +++ b/pkgs/queue-transport-alert/worker/deploy-lib.mjs @@ -0,0 +1,90 @@ +// Pure helpers for deploy.mjs (code#6369), kept apart so they are tested +// without running cf or bws. Run directly (`node deploy-lib.mjs ARGS`) it +// only checks the arguments, which deploy.sh does before Bitwarden or +// sops are touched. +import { fileURLToPath } from "node:url"; + +export const USAGE = [ + "usage: deploy.mjs [--dry-run]", + " deploy.mjs --deploy-version [--dry-run]", +].join("\n"); + +// Fail closed: a word we do not understand must never turn into a live +// deploy of HEAD when a preview or a rollback was meant. +export function parseArgs(argv) { + let dryRun = false; + let deployVersion = null; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--dry-run") { + if (dryRun) throw new Error(`duplicate argument --dry-run\n${USAGE}`); + dryRun = true; + } else if (arg === "--deploy-version" || arg.startsWith("--deploy-version=")) { + if (deployVersion !== null) throw new Error(`duplicate argument --deploy-version\n${USAGE}`); + const value = arg === "--deploy-version" ? argv[(i += 1)] : arg.slice("--deploy-version=".length); + if (!value || value.startsWith("-")) throw new Error(`--deploy-version needs a version id\n${USAGE}`); + deployVersion = value; + } else { + throw new Error(`unrecognized argument ${JSON.stringify(arg)}\n${USAGE}`); + } + } + return { dryRun, deployVersion }; +} + +// cf prints JSON by default, but progress lines can come first; take +// the first parseable JSON value that runs to the end of the output. +export function parseJsonOutput(out) { + const text = String(out).trim(); + try { + return JSON.parse(text); + } catch { /* scan below */ } + for (const open of ["{", "["]) { + for (let i = text.indexOf(open); i >= 0; i = text.indexOf(open, i + 1)) { + try { + return JSON.parse(text.slice(i)); + } catch { /* keep scanning */ } + } + } + throw new Error(`could not parse cf JSON output: ${text.slice(0, 200)}`); +} + +export function listItems(parsed, what) { + for (const candidate of [parsed, parsed?.result, parsed?.result?.items, parsed?.items, parsed?.[what]]) { + if (Array.isArray(candidate)) return candidate; + } + throw new Error(`unexpected ${what} list output`); +} + +function createdOn(item) { + const raw = item?.metadata?.created_on ?? item?.created_on ?? item?.createdOn ?? 0; + const parsed = typeof raw === "number" ? raw : Date.parse(raw); + return Number.isFinite(parsed) ? parsed : 0; +} + +// Uploads are not deduplicated, so a redeploy of the same commit adds a +// second version under the same tag: take the newest match. +export function newestWithTag(versions, tag) { + return versions + .filter((v) => (v.annotations?.["workers/tag"] ?? v.metadata?.annotations?.["workers/tag"]) === tag) + .sort((a, b) => createdOn(b) - createdOn(a))[0] ?? null; +} + +// The latest deployment must serve exactly this version at 100%. +export function servingCheck(deployments, versionId) { + const latest = [...deployments].sort((a, b) => createdOn(b) - createdOn(a))[0]; + const active = (latest?.versions ?? []).filter((v) => Number(v.percentage) > 0); + if (active.length === 1 && active[0].version_id === versionId && Number(active[0].percentage) === 100) { + return { ok: true }; + } + const serving = active.length ? active.map((v) => `${v.version_id}@${v.percentage}%`).join(", ") : "no active version"; + return { ok: false, serving }; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + try { + parseArgs(process.argv.slice(2)); + } catch (error) { + console.error(error.message); + process.exit(2); + } +} diff --git a/pkgs/queue-transport-alert/worker/deploy.mjs b/pkgs/queue-transport-alert/worker/deploy.mjs index 380c124027..d29979eb10 100644 --- a/pkgs/queue-transport-alert/worker/deploy.mjs +++ b/pkgs/queue-transport-alert/worker/deploy.mjs @@ -1,46 +1,57 @@ -// Deploys the queue-transport-alert Worker (code#6369) from its flake -// package: stages the package (or, run directly from a checkout, the -// checkout), runs `wrangler deploy` from the staged copy, then sets -// the Worker's three secrets with one `wrangler secret bulk` read from -// stdin, so no secret touches disk. +// Deploys the queue-transport-alert Worker (code#6369) with the `cf` CLI's +// versions flow, the repo's Worker deployment standard (as pkarr-deploy): +// +// cf workers versions create upload a version stamped with the git +// SHA (--tag git-), its secrets +// read from stdin; nothing goes live yet +// cf workers deployments create put that version at 100% +// cf workers triggers deploy apply the cron schedule from the config +// +// then checks the latest deployment serves that version and that +// /status.json answers. Rollback is the same machinery at an older id: +// --deploy-version deploys an existing version (which carries its +// own secrets) without uploading anything. // // Usage: -// deploy.mjs [--dry-run] +// deploy.mjs [--dry-run] build + upload + deploy HEAD +// deploy.mjs --deploy-version deploy or roll back to +// deploy.mjs --deploy-version --dry-run preview; creates nothing // -// Needs CLOUDFLARE_ACCOUNT_ID and BWS_ACCESS_TOKEN; deploy.sh sets -// them. Every value comes from Bitwarden by name: -// QTA_CF_TOKEN_SECRET (cloudflare.api-token-day-to-day) wrangler's API token +// The Worker package comes from the flake (QUEUE_TRANSPORT_ALERT_PKG) and +// cf/config plus wrangler (cf's build bridge) from the Nix store +// (QTA_CF_MODULE, QTA_WRANGLER_MODULE), so a deploy runs no npm install. +// Needs CLOUDFLARE_ACCOUNT_ID and BWS_ACCESS_TOKEN; deploy.sh sets them. +// Every value comes from Bitwarden by name: +// QTA_CF_TOKEN_SECRET (cloudflare.api-token-day-to-day) cf's API token // QTA_ACCESS_ID_SECRET (cloudflare.access.queue-broker-client-id) // QTA_ACCESS_SECRET_SECRET (cloudflare.access.queue-broker-client-secret) // QTA_GITHUB_TOKEN_SECRET (github.developing-today-code-automation) -// QTA_TELEGRAM_SECRET (openclaw.telegram-bot-token) phone push -// and the broker's agent token (for the post-outage queue task) from -// the file the fleet queue CLI reads, QTA_BROKER_TOKEN_FILE (default -// ~/.config/queue-broker/token); it is not in Bitwarden. When that file -// is absent the Worker keeps whatever BROKER_AGENT_TOKEN it already has. -// No secret is ever printed. +// QTA_TELEGRAM_SECRET (openclaw.telegram-bot-token) Telegram push +// and the broker's agent token (for the post-outage queue task) from the +// file the fleet queue CLI reads, QTA_BROKER_TOKEN_FILE (default +// ~/.config/queue-broker/token). A secret left out of an upload inherits +// the previous version's value. No secret is printed or written to disk. import { execFileSync } from "node:child_process"; -import { cpSync, existsSync, mkdtempSync, readFileSync } from "node:fs"; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; +import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck } from "./deploy-lib.mjs"; + const here = dirname(fileURLToPath(import.meta.url)); const WORKER = "queue-transport-alert"; +const WORKER_URL = "https://queue-transport-alert.developing-today.workers.dev"; +const BROWSER_UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"; -function usageError(message) { - console.error(`${message}\nusage: deploy.mjs [--dry-run]`); +let dryRun; +let deployVersion; +try { + ({ dryRun, deployVersion } = parseArgs(process.argv.slice(2))); +} catch (error) { + console.error(`deploy.mjs: ${error.message}`); process.exit(2); } -let dryRun = false; -for (const arg of process.argv.slice(2)) { - if (arg === "--dry-run") { - if (dryRun) usageError("duplicate argument: --dry-run"); - dryRun = true; - } else { - usageError(`unrecognized argument: ${arg}`); - } -} if (!process.env.CLOUDFLARE_ACCOUNT_ID) throw new Error("CLOUDFLARE_ACCOUNT_ID is not set; run deploy.sh"); const names = { @@ -57,6 +68,86 @@ const byName = (name) => { return value.replace(/\r?\n$/, ""); }; const env = { ...process.env, CLOUDFLARE_API_TOKEN: byName(names.cf) }; + +// Stage a writable copy (the store path is read-only and cf writes +// .cloudflare/ build output next to the config) with node_modules +// pointing at the Nix-built cf and wrangler. +const pkgDir = process.env.QUEUE_TRANSPORT_ALERT_PKG ?? here; +const stage = mkdtempSync(join(tmpdir(), "queue-transport-alert-deploy-")); +cpSync(pkgDir, stage, { recursive: true, filter: (src) => !src.includes("node_modules") }); +// Copies of store paths keep their read-only modes; make the stage +// writable so it can be removed afterwards. +execFileSync("chmod", ["-R", "u+w", stage]); +process.on("exit", () => { + try { + rmSync(stage, { recursive: true, force: true }); + } catch (error) { + console.warn(`could not remove ${stage}: ${error.message}`); + } +}); +if (!existsSync(join(stage, "cloudflare.config.ts"))) { + throw new Error(`no cloudflare.config.ts in the Worker package at ${pkgDir}`); +} +mkdirSync(join(stage, "node_modules"), { recursive: true }); +for (const [name, variable] of [["cf", "QTA_CF_MODULE"], ["wrangler", "QTA_WRANGLER_MODULE"]]) { + const target = process.env[variable] ?? join(here, "node_modules", name); + if (!existsSync(target)) throw new Error(`${variable} is not set and ${target} does not exist; run deploy.sh via nix run`); + symlinkSync(target, join(stage, "node_modules", name)); +} + +function runCf(args, { capture = false, input } = {}) { + return execFileSync("cf", ["-q", ...args], { + cwd: stage, + env, + encoding: "utf8", + input, + stdio: [input === undefined ? "inherit" : "pipe", capture ? "pipe" : "inherit", "inherit"], + }); +} + +function createDeployment(versionId) { + console.log(`creating deployment at version ${versionId} (100%)`); + const versions = JSON.stringify([{ version_id: versionId, percentage: 100 }]); + runCf(["workers", "deployments", "create", "--worker", WORKER, "--strategy", "percentage", "--versions", versions]); +} + +async function verify(versionId) { + const deployments = listItems( + parseJsonOutput(runCf(["workers", "deployments", "list", "--worker", WORKER], { capture: true })), + "deployments", + ); + const serving = servingCheck(deployments, versionId); + if (!serving.ok) { + throw new Error(`post-deploy check failed: expected version ${versionId} at 100%, latest deployment serves ${serving.serving}`); + } + const url = `${WORKER_URL}/status.json`; + const response = await fetch(url, { headers: { "user-agent": BROWSER_UA }, signal: AbortSignal.timeout(15_000) }); + if (!response.ok) throw new Error(`post-deploy check failed: ${url} answered HTTP ${response.status}`); + const status = await response.json(); + console.log(`verified: version ${versionId} serves 100%; ${url} reports the broker ${status.status ?? "unknown"}`); +} + +if (deployVersion !== null) { + if (dryRun) { + console.log(`dry run: would deploy ${WORKER} at existing version ${deployVersion} (100%); nothing created`); + process.exit(0); + } + createDeployment(deployVersion); + await verify(deployVersion); + console.log(`live: ${WORKER_URL} at version ${deployVersion}`); + process.exit(0); +} + +const sha = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); +const tag = `git-${sha.slice(0, 12)}`; +const message = `deploy ${sha} via nix run .#queue-transport-alert-deploy`; + +if (dryRun) { + runCf(["workers", "versions", "create", "--worker", WORKER, "--tag", tag, "--message", message, "--dry-run"]); + console.log("dry run: config builds, nothing uploaded"); + process.exit(0); +} + const workerSecrets = { ACCESS_CLIENT_ID: byName(names.accessId), ACCESS_CLIENT_SECRET: byName(names.accessSecret), @@ -64,33 +155,28 @@ const workerSecrets = { TELEGRAM_BOT_TOKEN: byName(names.telegram), }; const brokerTokenFile = process.env.QTA_BROKER_TOKEN_FILE ?? join(homedir(), ".config/queue-broker/token"); -if (existsSync(brokerTokenFile)) { - const token = readFileSync(brokerTokenFile, "utf8").trim(); - if (token) workerSecrets.BROKER_AGENT_TOKEN = token; +const brokerToken = existsSync(brokerTokenFile) ? readFileSync(brokerTokenFile, "utf8").trim() : ""; +if (brokerToken) { + workerSecrets.BROKER_AGENT_TOKEN = brokerToken; } else { - console.warn(`no broker token at ${brokerTokenFile}; leaving the Worker's BROKER_AGENT_TOKEN as it is`); + console.warn(`no broker token at ${brokerTokenFile}; BROKER_AGENT_TOKEN carries over from the previous version`); } -// Stage a writable copy (the store path is read-only; wrangler writes -// .wrangler state next to the config). -const pkgDir = process.env.QUEUE_TRANSPORT_ALERT_PKG ?? here; -const stage = mkdtempSync(join(tmpdir(), "queue-transport-alert-deploy-")); -cpSync(pkgDir, stage, { recursive: true }); -if (!existsSync(join(stage, "wrangler.jsonc"))) { - throw new Error(`no wrangler.jsonc in staged Worker package at ${pkgDir}`); -} +console.log(`uploading version (tag ${tag}; secrets ${Object.keys(workerSecrets).join(", ")})`); +runCf( + ["workers", "versions", "create", "--worker", WORKER, "--tag", tag, "--message", message, "--secrets-file", "/dev/stdin"], + { input: JSON.stringify(workerSecrets) }, +); +const versions = listItems( + parseJsonOutput(runCf(["workers", "versions", "list", "--worker-id", WORKER], { capture: true })), + "versions", +); +const version = newestWithTag(versions, tag); +if (!version) throw new Error(`uploaded version with tag ${tag} not found in the versions list`); +console.log(`uploaded version ${version.id}`); -const wranglerArgs = ["deploy"]; -if (dryRun) wranglerArgs.push("--dry-run"); -execFileSync("wrangler", wranglerArgs, { cwd: stage, env, stdio: "inherit" }); -if (dryRun) { - console.log(`dry run: config builds, nothing uploaded; would set secrets ${Object.keys(workerSecrets).join(", ")}`); - process.exit(0); -} -execFileSync("wrangler", ["secret", "bulk"], { - cwd: stage, - env, - input: JSON.stringify(workerSecrets), - stdio: ["pipe", "inherit", "inherit"], -}); -console.log(`deployed: ${WORKER} (wrangler deploy from the flake package; secrets ${Object.keys(workerSecrets).join(", ")} set)`); +createDeployment(version.id); +console.log("applying cron trigger from cloudflare.config.ts"); +runCf(["workers", "triggers", "deploy", "--worker", WORKER]); +await verify(version.id); +console.log(`live: ${WORKER_URL} at version ${version.id} (${tag}); roll back with --deploy-version `); diff --git a/pkgs/queue-transport-alert/worker/deploy.nix b/pkgs/queue-transport-alert/worker/deploy.nix index eabef01883..b59bb69888 100644 --- a/pkgs/queue-transport-alert/worker/deploy.nix +++ b/pkgs/queue-transport-alert/worker/deploy.nix @@ -1,28 +1,31 @@ { writeShellApplication, bws, + cf, git, - jq, nodejs, sops, wrangler, queueTransportAlert, }: # code#6369: the deploy app carries the Worker package (package.nix) by -# store path; deploy.mjs stages it, runs wrangler deploy from the staged -# copy, then sets the Worker's secrets from Bitwarden by name. +# store path; deploy.mjs stages it and deploys through the cf versions +# flow. cf/config and wrangler (cf's build bridge for a plain-JS Worker) +# are linked into the staged node_modules from the store, so a deploy +# needs no npm install. writeShellApplication { name = "queue-transport-alert-deploy"; runtimeInputs = [ bws + cf git - jq nodejs sops - wrangler ]; text = '' export QUEUE_TRANSPORT_ALERT_PKG="${queueTransportAlert}" + export QTA_CF_MODULE="${cf}/lib/node_modules/cf" + export QTA_WRANGLER_MODULE="${wrangler}/lib/node_modules/wrangler" repo_root=$(git rev-parse --show-toplevel) exec bash "$repo_root/pkgs/queue-transport-alert/worker/deploy.sh" "$@" ''; diff --git a/pkgs/queue-transport-alert/worker/deploy.sh b/pkgs/queue-transport-alert/worker/deploy.sh index 49388d22b3..be736a13da 100755 --- a/pkgs/queue-transport-alert/worker/deploy.sh +++ b/pkgs/queue-transport-alert/worker/deploy.sh @@ -1,20 +1,12 @@ #!/usr/bin/env bash -# Deploys the queue-transport-alert Worker (see deploy.mjs). Pass -# --dry-run to validate without deploying. +# Deploys the queue-transport-alert Worker through the cf versions flow +# (see deploy.mjs). Pass --dry-run to build without uploading, or +# --deploy-version to deploy (roll back to) an existing version. set -euo pipefail -# Check arguments before Bitwarden or sops are touched, so a typo never -# triggers a credential prompt or a decrypt. -for arg in "$@"; do - case "$arg" in - --dry-run) ;; - *) - echo "unrecognized argument: $arg" >&2 - echo "usage: deploy.sh [--dry-run]" >&2 - exit 2 - ;; - esac -done cd "$(dirname "${BASH_SOURCE[0]}")" +# Check arguments before Bitwarden or sops are touched, so a typo never +# triggers a credential prompt, a decrypt or a deploy of HEAD. +node deploy-lib.mjs "$@" repo_root=$(git rev-parse --show-toplevel) if [ -z "${BWS_ACCESS_TOKEN:-}" ]; then # shellcheck source=/dev/null diff --git a/pkgs/queue-transport-alert/worker/package.json b/pkgs/queue-transport-alert/worker/package.json index 58018c9d20..50e7a1f2d6 100644 --- a/pkgs/queue-transport-alert/worker/package.json +++ b/pkgs/queue-transport-alert/worker/package.json @@ -5,6 +5,11 @@ "type": "module", "description": "Cloudflare Worker that alerts on a repo-queue broker outage (code#6369)", "scripts": { - "test": "node --test test/*.test.mjs" + "test": "node --test test/*.test.mjs", + "deploy": "echo 'deploy through the flake instead: nix run .#queue-transport-alert-deploy' >&2; exit 1" + }, + "devDependencies": { + "cf": "1.0.0-beta.20", + "wrangler": "4.147.0" } } diff --git a/pkgs/queue-transport-alert/worker/package.nix b/pkgs/queue-transport-alert/worker/package.nix index bf0f3c3839..7608649288 100644 --- a/pkgs/queue-transport-alert/worker/package.nix +++ b/pkgs/queue-transport-alert/worker/package.nix @@ -6,7 +6,7 @@ # The queue-transport-alert Worker tree as a flake package (code#6369). # Plain ESM with no npm dependencies, so the package is the source tree -# itself; wrangler bundles it at deploy time from a staged copy. The +# itself; cf bundles it at deploy time from a staged copy. The # contract tests run in checkPhase. stdenvNoCC.mkDerivation { pname = "queue-transport-alert-worker"; @@ -18,6 +18,8 @@ stdenvNoCC.mkDerivation { ./test ./package.json ./wrangler.jsonc + ./cloudflare.config.ts + ./deploy-lib.mjs ]; }; nativeCheckInputs = [ nodejs ]; @@ -30,7 +32,7 @@ stdenvNoCC.mkDerivation { installPhase = '' runHook preInstall mkdir -p $out - cp -r src package.json wrangler.jsonc $out/ + cp -r src package.json wrangler.jsonc cloudflare.config.ts $out/ runHook postInstall ''; meta = { diff --git a/pkgs/queue-transport-alert/worker/test/config.test.mjs b/pkgs/queue-transport-alert/worker/test/config.test.mjs new file mode 100644 index 0000000000..9431451ffd --- /dev/null +++ b/pkgs/queue-transport-alert/worker/test/config.test.mjs @@ -0,0 +1,42 @@ +// cloudflare.config.ts (the cf deploy source) and wrangler.jsonc (local +// `wrangler dev`) describe the same Worker; keep them in step. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; + +const dir = new URL("../", import.meta.url); +const cfConfig = readFileSync(new URL("cloudflare.config.ts", dir), "utf8"); +const wrangler = JSON.parse( + readFileSync(new URL("wrangler.jsonc", dir), "utf8") + .split("\n") + .filter((line) => !line.trim().startsWith("//")) + .join("\n"), +); + +test("name, compatibility date and cron schedule match", () => { + assert.match(cfConfig, new RegExp(`name: "${wrangler.name}"`)); + assert.match(cfConfig, new RegExp(`compatibilityDate: "${wrangler.compatibility_date}"`)); + const schedules = [...cfConfig.matchAll(/triggers\.scheduled\(\{ schedule: "([^"]+)" \}\)/g)].map((m) => m[1]); + assert.deepEqual(schedules, wrangler.triggers.crons); +}); + +test("every plain var matches", () => { + const texts = Object.fromEntries([...cfConfig.matchAll(/(\w+): bindings\.text\("([^"]*)"\)/g)].map((m) => [m[1], m[2]])); + assert.deepEqual(texts, wrangler.vars); +}); + +test("the Durable Object keeps its sqlite namespace", () => { + const [binding] = wrangler.durable_objects.bindings; + assert.match(cfConfig, new RegExp(`${binding.class_name}: exports\\.durableObject\\(\\{ storage: "sqlite" \\}\\)`)); + assert.match(cfConfig, new RegExp(`${binding.name}: bindings\\.durableObject\\(\\{ worker: "${wrangler.name}", exportName: "${binding.class_name}" \\}\\)`)); + assert.ok(wrangler.migrations.some((m) => m.new_sqlite_classes?.includes(binding.class_name))); +}); + +test("every secret the Worker reads is declared", () => { + const declared = [...cfConfig.matchAll(/(\w+): bindings\.secret\(\)/g)].map((m) => m[1]).sort(); + assert.deepEqual(declared, ["ACCESS_CLIENT_ID", "ACCESS_CLIENT_SECRET", "BROKER_AGENT_TOKEN", "GITHUB_TOKEN", "TELEGRAM_BOT_TOKEN"]); + const src = ["index.js", "run.js", "notify.js", "queue.js"] + .map((f) => readFileSync(new URL(`src/${f}`, dir), "utf8")) + .join("\n"); + for (const name of declared) assert.match(src, new RegExp(`env\\.${name}\\b`), name); +}); diff --git a/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs b/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs new file mode 100644 index 0000000000..f351da0b07 --- /dev/null +++ b/pkgs/queue-transport-alert/worker/test/deploy-lib.test.mjs @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { listItems, newestWithTag, parseArgs, parseJsonOutput, servingCheck } from "../deploy-lib.mjs"; + +test("parseArgs accepts the three shapes", () => { + assert.deepEqual(parseArgs([]), { dryRun: false, deployVersion: null }); + assert.deepEqual(parseArgs(["--dry-run"]), { dryRun: true, deployVersion: null }); + assert.deepEqual(parseArgs(["--deploy-version", "abc"]), { dryRun: false, deployVersion: "abc" }); + assert.deepEqual(parseArgs(["--deploy-version=abc", "--dry-run"]), { dryRun: true, deployVersion: "abc" }); +}); + +test("parseArgs fails closed on anything else", () => { + for (const argv of [ + ["--dry-rnu"], + ["deploy"], + ["--deploy-version"], + ["--deploy-version", "--dry-run"], + ["--deploy-version="], + ["--dry-run", "--dry-run"], + ["--deploy-version", "a", "--deploy-version", "b"], + ]) { + assert.throws(() => parseArgs(argv), /usage:/, JSON.stringify(argv)); + } +}); + +test("parseJsonOutput skips progress lines before the JSON", () => { + assert.deepEqual(parseJsonOutput('[{"id":"v1"}]'), [{ id: "v1" }]); + assert.deepEqual(parseJsonOutput('Fetching {versions}\n{"result":{"items":[]}}'), { result: { items: [] } }); + assert.throws(() => parseJsonOutput("no json here"), /could not parse/); +}); + +test("listItems finds the array in every shape cf and the API use", () => { + const items = [{ id: "a" }]; + for (const shape of [items, { result: items }, { result: { items } }, { items }, { versions: items }]) { + assert.deepEqual(listItems(shape, "versions"), items); + } + assert.throws(() => listItems({ result: {} }, "versions"), /unexpected versions/); +}); + +test("newestWithTag picks the newest upload of a re-deployed commit", () => { + const versions = [ + { id: "old", annotations: { "workers/tag": "git-abc" }, metadata: { created_on: "2026-11-19T01:00:00Z" } }, + { id: "new", annotations: { "workers/tag": "git-abc" }, metadata: { created_on: "2026-11-19T02:00:00Z" } }, + { id: "other", annotations: { "workers/tag": "git-def" }, metadata: { created_on: "2026-11-19T03:00:00Z" } }, + ]; + assert.equal(newestWithTag(versions, "git-abc").id, "new"); + assert.equal(newestWithTag(versions, "git-zzz"), null); +}); + +test("servingCheck requires the latest deployment to serve the version at 100%", () => { + const deployments = [ + { created_on: "2026-11-19T01:00:00Z", versions: [{ version_id: "v1", percentage: 100 }] }, + { created_on: "2026-11-19T02:00:00Z", versions: [{ version_id: "v2", percentage: 100 }] }, + ]; + assert.deepEqual(servingCheck(deployments, "v2"), { ok: true }); + assert.equal(servingCheck(deployments, "v1").ok, false); + const split = [{ created_on: "2026-11-19T03:00:00Z", versions: [{ version_id: "v2", percentage: 50 }, { version_id: "v3", percentage: 50 }] }]; + assert.match(servingCheck(split, "v2").serving, /v2@50%, v3@50%/); +}); diff --git a/pkgs/queue-transport-alert/worker/wrangler.jsonc b/pkgs/queue-transport-alert/worker/wrangler.jsonc index 269d73cf7b..525f094ad2 100644 --- a/pkgs/queue-transport-alert/worker/wrangler.jsonc +++ b/pkgs/queue-transport-alert/worker/wrangler.jsonc @@ -1,5 +1,6 @@ { - // Queue transport alert Worker (code#6369). Deployed from the flake: + // Queue transport alert Worker (code#6369), for local `wrangler dev`. + // Deploys go through cloudflare.config.ts and the cf versions flow: // nix run .#queue-transport-alert-deploy [-- --dry-run] "name": "queue-transport-alert", "main": "src/index.js", @@ -18,7 +19,7 @@ // "true" files/comments on incidents, pushes and enqueues; anything else only logs. "APPLY": "true" }, - // Secrets (set by deploy.mjs from Bitwarden, never in this file): + // Secrets (uploaded with each version by deploy.mjs from Bitwarden, never in this file): // ACCESS_CLIENT_ID, ACCESS_CLIENT_SECRET Access service token for the broker route // GITHUB_TOKEN token that may write issues in REPO // TELEGRAM_BOT_TOKEN OpenClaw's Telegram bot, for the phone push