Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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";
Expand Down
48 changes: 33 additions & 15 deletions pkgs/queue-transport-alert/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <id> # 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-<sha12>` 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 <id>` 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`).

Expand Down
42 changes: 42 additions & 0 deletions pkgs/queue-transport-alert/worker/cloudflare.config.ts
Original file line number Diff line number Diff line change
@@ -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(),
},
},
});
90 changes: 90 additions & 0 deletions pkgs/queue-transport-alert/worker/deploy-lib.mjs
Original file line number Diff line number Diff line change
@@ -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 <id> [--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);
}
}
Loading