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
54 changes: 54 additions & 0 deletions .github/workflows/decision-events-worker-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
name: decision-events Worker deploy

on:
push:
branches: [main]
paths:
- "pm-stack/decision-events-worker/**"
- "pm-stack/platform/workers.json"
- ".github/workflows/decision-events-worker-deploy.yml"
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}
cancel-in-progress: false

jobs:
deploy:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v7
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
- uses: actions/setup-node@v7.1.0
with:
node-version: 24
- name: Install dependencies
working-directory: pm-stack/decision-events-worker
run: bun install --frozen-lockfile
- name: Test and type-check the Worker
working-directory: pm-stack/decision-events-worker
run: |
bun test
bun run typecheck
- name: Deploy this commit
working-directory: pm-stack/decision-events-worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
run: |
if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ]; then
echo "CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are required to deploy decision-events." >&2
exit 1
fi
bunx wrangler deploy --var "VERSION:${GITHUB_SHA}"
- name: Require the deployed health version to match this commit
working-directory: pm-stack/decision-events-worker
run: >-
node scripts/check-health.mjs
--url https://decision-events.developing-today.workers.dev/health
--version "$GITHUB_SHA"
19 changes: 17 additions & 2 deletions pm-stack/decision-events-worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ land in three places, all idempotent on `eventId`:
| `GET /sets/<setId>/events?limit=&after=` | shared secret | Read a set's events back from D1, in `(ts, event_id)` order; the response's `nextAfter` is the composite cursor for the next page (see below). |
| `GET /sets/<setId>/state` | shared secret | The set's Durable Object state merged with D1's stored count. |
| `GET /sets/<setId>/stream` | shared secret | WebSocket upgrade routed to the set's Durable Object; subscribers get `{type:"decision-events", setId, events}` per new batch, plus the current state on connect. Send `ping` → `pong`, `state` → current state. |
| `GET /health` | none | Liveness + whether the webhook secret is configured. |
| `GET /health` | none | Liveness, whether the webhook secret is configured, and the deployed `VERSION` (or `unknown` until deployment supplies it). |

Read-back pagination: pass the previous page's `nextAfter` value as
`after` to get the next page. The cursor is composite — `<ts>|<eventId>`,
Expand All @@ -47,7 +47,9 @@ Turso. Credentials are resolved **by name** only:

## GitHub Actions release (#9335 Track B)

The manual Wrangler deploy path has been retired. Use
Production code deploys run from `.github/workflows/decision-events-worker-deploy.yml` on changes to this Worker on `main`, or by manually dispatching that workflow on `main`. The workflow tests and type-checks the Worker, deploys with `VERSION` set to the full `GITHUB_SHA`, and fails unless `/health` reports that exact SHA. Cloudflare Actions secrets are `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID`.

Alongside the automatic deploy, a manual versioned release path exists:
`.github/workflows/decision-events-worker-release.yml` from `main`. It
builds and checks the Worker offline, uploads a version with
`cf workers versions create`, and optionally promotes the selected
Expand Down Expand Up @@ -95,6 +97,19 @@ the exact `workers.dev` URL and credentials, then explicitly approve
the first real sync. With the webhook URL set, the aggregator defaults
to writing to both Turso and this Worker.

Initial database provisioning and the webhook secret remain operator setup:

```sh
# Token by name, piped — never on disk/argv (fleet wrangler pattern):
fleet secrets get cloudflare.api-token-day-to-day | \
python3 ~/tools/cloudflare/wrangler-authed.py d1 create decision-events
# put the returned database_id in wrangler.toml, then:
fleet secrets get cloudflare.api-token-day-to-day | \
python3 ~/tools/cloudflare/wrangler-authed.py d1 execute decision-events --remote --file schema.sql
fleet secrets get cloudflare.decision-events.webhook-secret | \
python3 ~/tools/cloudflare/wrangler-secret.py # or: wrangler secret put WEBHOOK_SECRET
```

## Tests

```sh
Expand Down
65 changes: 65 additions & 0 deletions pm-stack/decision-events-worker/scripts/check-health.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Usage: node scripts/check-health.mjs --url HTTPS_URL --version FULL_SHA
// Strictly accepts those two flags once each; rejects any other argument.
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";

export function matchesHealth(payload, expectedVersion) {
return payload?.ok === true && payload?.version === expectedVersion;
}

function parseArgs(args) {
const values = new Map();
for (let i = 0; i < args.length; i += 1) {
const key = args[i];
if (key !== "--url" && key !== "--version") {
throw new Error(`unexpected argument: ${key}`);
}
if (values.has(key) || !args[i + 1] || args[i + 1].startsWith("--")) {
throw new Error(`expected one value after ${key}`);
}
values.set(key, args[++i]);
}

const url = values.get("--url");
const version = values.get("--version");
if (values.size !== 2 || !url || !version) {
throw new Error("usage: node scripts/check-health.mjs --url HTTPS_URL --version FULL_SHA");
}
const parsedUrl = new URL(url);
if (parsedUrl.protocol !== "https:") {
throw new Error("--url must use HTTPS");
}
if (!/^[0-9a-f]{40}$/.test(version)) {
throw new Error("--version must be a full 40-character lowercase commit SHA");
}
return { url: parsedUrl, version };
}

async function waitForHealthyVersion(url, expectedVersion) {
let lastAnswer = "no response";
for (let attempt = 1; attempt <= 20; attempt += 1) {
try {
const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
const payload = await response.json();
lastAnswer = `HTTP ${response.status}: ${JSON.stringify(payload)}`;
if (response.ok && matchesHealth(payload, expectedVersion)) {
console.log(`decision-events answers with version ${expectedVersion}`);
return;
}
} catch (error) {
lastAnswer = error instanceof Error ? error.message : String(error);
}
if (attempt < 20) await new Promise((resolveSleep) => setTimeout(resolveSleep, 6_000));
}
throw new Error(`health check did not report ${expectedVersion}; last answer: ${lastAnswer}`);
}

if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
try {
const { url, version } = parseArgs(process.argv.slice(2));
await waitForHealthyVersion(url, version);
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
}
}
8 changes: 7 additions & 1 deletion pm-stack/decision-events-worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
export interface Env {
DB: D1Database;
SET_EVENTS: DurableObjectNamespace;
VERSION?: string;
WEBHOOK_SECRET?: string;
}

Expand Down Expand Up @@ -270,7 +271,12 @@ export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/health") {
return Response.json({ ok: true, service: "decision-events", webhookConfigured: Boolean(env.WEBHOOK_SECRET) });
return Response.json({
ok: true,
service: "decision-events",
webhookConfigured: Boolean(env.WEBHOOK_SECRET),
version: env.VERSION ?? "unknown",
});
}
if ((url.pathname === "/events" || url.pathname === "/webhook") && request.method === "POST") {
return handlePostEvents(request, env);
Expand Down
17 changes: 17 additions & 0 deletions pm-stack/decision-events-worker/test/deploy-health.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { describe, expect, test } from "bun:test";
import { matchesHealth } from "../scripts/check-health.mjs";

describe("deployment health gate", () => {
const deployedSha = "0123456789abcdef0123456789abcdef01234567";

test("accepts only a healthy response reporting the exact deployed SHA", () => {
expect(matchesHealth({ ok: true, version: deployedSha }, deployedSha)).toBe(true);
});

test("rejects a stale, missing, or unhealthy version", () => {
expect(matchesHealth({ ok: true, version: "abcdef012345" }, deployedSha)).toBe(false);
expect(matchesHealth({ ok: true, version: "unknown" }, deployedSha)).toBe(false);
expect(matchesHealth({ ok: false, version: deployedSha }, deployedSha)).toBe(false);
expect(matchesHealth({}, deployedSha)).toBe(false);
});
});
39 changes: 39 additions & 0 deletions pm-stack/decision-events-worker/test/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,45 @@ describe("auth helpers", () => {
});
});

describe("health", () => {
test("reports the exact build version supplied by the deployment", async () => {
const deployedCommit = "0123456789abcdef0123456789abcdef01234567";
const env = {
VERSION: deployedCommit,
WEBHOOK_SECRET: "s3cr3t",
DB: {} as D1Database,
SET_EVENTS: {} as DurableObjectNamespace,
} as unknown as Env;

const response = await worker.fetch(new Request("https://worker/health"), env);

expect(response.status).toBe(200);
expect(await response.json()).toEqual({
ok: true,
service: "decision-events",
webhookConfigured: true,
version: deployedCommit,
});
});

test("does not claim a commit when the deployment has not supplied one", async () => {
const env = {
WEBHOOK_SECRET: "s3cr3t",
DB: {} as D1Database,
SET_EVENTS: {} as DurableObjectNamespace,
} satisfies Env;

const response = await worker.fetch(new Request("https://worker/health"), env);

expect(await response.json()).toEqual({
ok: true,
service: "decision-events",
webhookConfigured: true,
version: "unknown",
});
});
});

describe("groupBySet", () => {
test("groups preserving order", () => {
const parsed = parseEventBatch([ev("e1"), ev("e2", "set-2"), ev("e3")]);
Expand Down
6 changes: 3 additions & 3 deletions pm-stack/platform/workers.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@
"path": "pm-stack/decision-events-worker",
"does": "The Cloudflare half of the decision-set event pipeline: takes each event once and keeps it for the dashboard's questions.",
"state": "in service",
"deploy": "by hand",
"workflow": null,
"deploy": "actions",
"workflow": "decision-events-worker-deploy.yml",
"address": "https://decision-events.developing-today.workers.dev",
"next": "Deployed from Actions, stood up, checked and rolled back the way the PM console is; listed here with its last deploy. Then the questions it feeds can be read at the edge with no machine."
"next": "Deployed from Actions with VERSION set to the full commit SHA and /health required to report that exact SHA. The broader PM migration will add the console's staged route-flip and rollback flow."
},
{
"name": "pm-notify",
Expand Down