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
10 changes: 9 additions & 1 deletion pm-stack/decision-events-worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,19 @@ land in three places, all idempotent on `eventId`:
| Route | Auth | Purpose |
| ---------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /events` (alias `/webhook`) | shared secret | Accept an event batch: `{events: [...]}` (or a bare array / single event). Stores new events in D1, fans them out to each set's Durable Object, returns `{accepted, inserted, duplicates, errors, fanout}`. |
| `GET /sets/<setId>/events?limit=&after=` | shared secret | Read a set's events back from D1, in `ts` order. |
| `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. |

Read-back pagination: pass the previous page's `nextAfter` value as
`after` to get the next page. The cursor is composite — `<ts>|<eventId>`,
the (ts, event_id) pair of the page's last event — so paging returns
every event exactly once, including groups of events that share one
timestamp (#9614). `nextAfter` is null on an empty page. A bare ISO
timestamp is still accepted as `after` with its legacy meaning
(strictly after that ts, skipping any remaining same-ts events).

Auth is the shared secret as `Authorization: Bearer <secret>` or the
`X-Webhook-Secret` header, compared in constant time. With no secret
configured the Worker fails closed (503 on every data route).
Expand Down
37 changes: 37 additions & 0 deletions pm-stack/decision-events-worker/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,40 @@ export function groupBySet(events: DecisionSetEvent[]): Map<string, DecisionSetE
}
return map;
}

/** Composite read-back cursor for GET /sets/<setId>/events (#9614).
*
* Pagination orders by (ts, event_id), so the cursor must carry BOTH
* components: a bare-ts cursor (`ts > after`) makes every event after
* the first page boundary inside a same-ts group unreachable. The
* wire form is `<ts>|<eventId>` — ts never contains `|`, so splitting
* at the first `|` is unambiguous even if an eventId contains one.
* A bare ISO timestamp is still accepted as a legacy cursor and keeps
* its original meaning (strictly after that ts). */
export interface EventsCursor {
ts: string;
eventId: string | null;
}

export function encodeEventsCursor(cursor: { ts: string; eventId: string }): string {
return `${cursor.ts}|${cursor.eventId}`;
}

export function parseEventsCursor(raw: string): { ok: true; value: EventsCursor } | { ok: false; error: string } {
const sep = raw.indexOf("|");
if (sep === -1) {
if (!isIsoTimestamp(raw)) {
return { ok: false, error: "after must be an ISO timestamp or a <ts>|<eventId> cursor" };
}
return { ok: true, value: { ts: raw, eventId: null } };
}
const ts = raw.slice(0, sep);
const eventId = raw.slice(sep + 1);
if (!isIsoTimestamp(ts)) {
return { ok: false, error: "after cursor ts must be an ISO timestamp" };
}
if (!ID_RE.test(eventId)) {
return { ok: false, error: "after cursor eventId is invalid" };
}
return { ok: true, value: { ts, eventId } };
}
48 changes: 38 additions & 10 deletions pm-stack/decision-events-worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@
// event), stores them in D1 (INSERT OR IGNORE on event_id —
// redelivery is a no-op), then hands each set's NEW events to that
// set's Durable Object for per-set fan-out.
// GET /sets/<setId>/events?limit=<n>&after=<ts>
// Authenticated read-back of a set's events from D1, in ts order.
// GET /sets/<setId>/events?limit=<n>&after=<cursor>
// Authenticated read-back of a set's events from D1, in
// (ts, event_id) order. `after` is the composite cursor the
// previous page returned as `nextAfter` (<ts>|<eventId>); a bare
// <ts> is still accepted with its legacy meaning (ts > after).
// The response's `nextAfter` is the cursor for the following
// page, or null when the page is empty.
// GET /sets/<setId>/state
// Authenticated: the set's Durable Object state (events fanned
// out, last event, live subscriber count) merged with D1's count.
Expand All @@ -27,7 +32,14 @@
// batches to the set's WebSocket subscribers (hibernatable sockets,
// so idle sets cost nothing). D1 stays the durable store; the object
// holds coordination state only.
import { groupBySet, isAuthorized, parseEventBatch, type DecisionSetEvent } from "./events.ts";
import {
encodeEventsCursor,
groupBySet,
isAuthorized,
parseEventBatch,
parseEventsCursor,
type DecisionSetEvent,
} from "./events.ts";

export interface Env {
DB: D1Database;
Expand Down Expand Up @@ -189,12 +201,26 @@ async function handlePostEvents(request: Request, env: Env): Promise<Response> {
async function handleGetEvents(url: URL, env: Env, setId: string): Promise<Response> {
const limitRaw = Number(url.searchParams.get("limit") ?? "200");
const limit = Number.isFinite(limitRaw) ? Math.min(Math.max(Math.trunc(limitRaw), 1), 1000) : 200;
const after = url.searchParams.get("after");
const query = after
? "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? AND ts > ? ORDER BY ts, event_id LIMIT ?"
: "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ? ORDER BY ts, event_id LIMIT ?";
const stmt = env.DB.prepare(query);
const bound = after ? stmt.bind(setId, after, limit) : stmt.bind(setId, limit);
const afterRaw = url.searchParams.get("after");
const select = "SELECT event_id, set_id, question_ref, type, payload, ts FROM decision_set_events WHERE set_id = ?";
let query = `${select} ORDER BY ts, event_id LIMIT ?`;
let bound = env.DB.prepare(query).bind(setId, limit);
if (afterRaw) {
const parsed = parseEventsCursor(afterRaw);
if (!parsed.ok) return jsonError(400, parsed.error);
const { ts, eventId } = parsed.value;
if (eventId !== null) {
// Composite cursor (#9614): resume strictly after the (ts,
// event_id) pair, so events sharing the page-boundary ts are
// not skipped.
query = `${select} AND (ts > ? OR (ts = ? AND event_id > ?)) ORDER BY ts, event_id LIMIT ?`;
bound = env.DB.prepare(query).bind(setId, ts, ts, eventId, limit);
} else {
// Legacy bare-ts cursor: original meaning, ts strictly after.
query = `${select} AND ts > ? ORDER BY ts, event_id LIMIT ?`;
bound = env.DB.prepare(query).bind(setId, ts, limit);
}
}
const { results } = await bound.all<Record<string, unknown>>();
const events = (results ?? []).map((row) => ({
eventId: row.event_id,
Expand All @@ -204,7 +230,9 @@ async function handleGetEvents(url: URL, env: Env, setId: string): Promise<Respo
payload: typeof row.payload === "string" ? JSON.parse(row.payload) : row.payload,
ts: row.ts,
}));
return Response.json({ setId, count: events.length, events });
const last = events[events.length - 1];
const nextAfter = last ? encodeEventsCursor({ ts: last.ts as string, eventId: last.eventId as string }) : null;
return Response.json({ setId, count: events.length, events, nextAfter });
}

export default {
Expand Down
36 changes: 35 additions & 1 deletion pm-stack/decision-events-worker/test/events.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { describe, expect, test } from "bun:test";
import { groupBySet, isAuthorized, parseEventBatch, timingSafeEqual, validateDecisionEvent } from "../src/events.ts";
import {
encodeEventsCursor,
groupBySet,
isAuthorized,
parseEventBatch,
parseEventsCursor,
timingSafeEqual,
validateDecisionEvent,
} from "../src/events.ts";

const ev = (eventId: string, setId = "set-1") => ({
eventId,
Expand Down Expand Up @@ -68,3 +76,29 @@ describe("groupBySet", () => {
expect(groups.get("set-1")?.map((e) => e.eventId)).toEqual(["e1", "e3"]);
});
});

describe("events cursor (#9614)", () => {
test("round-trips a composite (ts, event_id) cursor", () => {
const cursor = encodeEventsCursor({ ts: "2026-11-12T10:00:00.000Z", eventId: "e2" });
expect(cursor).toBe("2026-11-12T10:00:00.000Z|e2");
const parsed = parseEventsCursor(cursor);
expect(parsed.ok).toBe(true);
if (parsed.ok) expect(parsed.value).toEqual({ ts: "2026-11-12T10:00:00.000Z", eventId: "e2" });
});
test("eventIds containing the separator still parse (split at the first |)", () => {
const parsed = parseEventsCursor("2026-11-12T10:00:00.000Z|e|2");
expect(parsed.ok).toBe(true);
if (parsed.ok) expect(parsed.value.eventId).toBe("e|2");
});
test("a bare timestamp is a legacy cursor with no eventId", () => {
const parsed = parseEventsCursor("2026-11-12T10:00:00.000Z");
expect(parsed.ok).toBe(true);
if (parsed.ok) expect(parsed.value).toEqual({ ts: "2026-11-12T10:00:00.000Z", eventId: null });
});
test("rejects malformed cursors", () => {
expect(parseEventsCursor("not-a-date").ok).toBe(false);
expect(parseEventsCursor("2026-11-12T10:00:00.000Z|").ok).toBe(false);
expect(parseEventsCursor("not-a-date|e1").ok).toBe(false);
expect(parseEventsCursor("2026-11-12T10:00:00.000Z|has space").ok).toBe(false);
});
});
117 changes: 117 additions & 0 deletions pm-stack/decision-events-worker/test/pagination.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Read-back pagination regression (#9614): paging through a group of
// events that share one timestamp must return every event exactly
// once. Exercises the real Worker fetch handler and its real SQL
// against an in-memory SQLite database standing in for D1 (D1 is
// SQLite-backed; the fake runs the handler's actual query strings).
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import worker from "../src/index.ts";

const SECRET = "test-secret";
const TS = "2026-11-12T10:00:00.000Z";

class FakeStatement {
constructor(
private db: Database,
private sql: string,
private args: unknown[] = [],
) {}
bind(...args: unknown[]): FakeStatement {
return new FakeStatement(this.db, this.sql, args);
}
async all<T>(): Promise<{ results: T[] }> {
return { results: this.db.query(this.sql).all(...(this.args as never[])) as T[] };
}
async first<T>(): Promise<T | null> {
return (this.db.query(this.sql).get(...(this.args as never[])) as T) ?? null;
}
}

class FakeD1 {
constructor(private db: Database) {}
prepare(sql: string): FakeStatement {
return new FakeStatement(this.db, sql);
}
}

function makeEnv(rows: [string, string, string][]): unknown {
const db = new Database(":memory:");
const schema = readFileSync(join(import.meta.dir, "..", "schema.sql"), "utf8");
db.exec(schema);
const insert = db.query(
"INSERT INTO decision_set_events (event_id, set_id, question_ref, type, payload, ts) VALUES (?, ?, ?, ?, ?, ?)",
);
// Inserted out of order on purpose: ordering is the query's job.
for (const [eventId, setId, ts] of rows) {
insert.run(eventId, setId, "ledger-1#1", "question-answered", JSON.stringify({ optionId: "a" }), ts);
}
return { DB: new FakeD1(db), SET_EVENTS: {}, WEBHOOK_SECRET: SECRET };
}

async function getEvents(
env: unknown,
query: string,
): Promise<{
status: number;
body: { count?: number; events?: { eventId: string }[]; nextAfter?: string | null; error?: string };
}> {
const res = await worker.fetch(
new Request(`http://worker.test/sets/set-1/events?${query}`, {
headers: { Authorization: `Bearer ${SECRET}` },
}),
env as never,
);
return { status: res.status, body: await res.json() };
}

const ROWS: [string, string, string][] = [
["e3", "set-1", TS],
["e1", "set-1", TS],
["e5", "set-1", "2026-11-12T11:00:00.000Z"],
["e2", "set-1", TS],
["e4", "set-1", "2026-11-12T11:00:00.000Z"],
["other-set-event", "set-2", TS],
];

describe("GET /sets/<setId>/events pagination (#9614)", () => {
test("pages through a same-timestamp group: every event exactly once, in (ts, event_id) order", async () => {
const env = makeEnv(ROWS);
const seen: string[] = [];
let after: string | null = null;
for (let page = 0; page < 10; page++) {
const q = after === null ? "limit=2" : `limit=2&after=${encodeURIComponent(after)}`;
const { status, body } = await getEvents(env, q);
expect(status).toBe(200);
const ids = (body.events ?? []).map((e) => e.eventId);
if (ids.length === 0) {
expect(body.nextAfter).toBeNull();
break;
}
seen.push(...ids);
after = body.nextAfter ?? null;
expect(after).not.toBeNull();
// A page that ends inside the same-ts group must hand back the
// composite cursor, not the bare timestamp.
if (page === 0) expect(after).toBe(`${TS}|e2`);
}
expect(seen).toEqual(["e1", "e2", "e3", "e4", "e5"]);
expect(new Set(seen).size).toBe(seen.length);
});

test("legacy bare-ts after keeps its original meaning (strictly after that ts)", async () => {
const env = makeEnv(ROWS);
const { status, body } = await getEvents(env, `limit=10&after=${encodeURIComponent(TS)}`);
expect(status).toBe(200);
expect((body.events ?? []).map((e) => e.eventId)).toEqual(["e4", "e5"]);
});

test("a malformed after cursor is a 400, not a silent first page", async () => {
const env = makeEnv(ROWS);
for (const bad of ["not-a-date", `${TS}|`, `not-a-date|e1`, `${TS}|has space`]) {
const { status } = await getEvents(env, `after=${encodeURIComponent(bad)}`);
expect(status).toBe(400);
}
});
});