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
90 changes: 60 additions & 30 deletions pm-stack/decision-events-worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,25 +100,41 @@ export class DecisionSetEvents {
this.setId = body.setId;
const state = await this.loadState();
state.setId = body.setId;
const seenList = (await this.state.storage.get<string[]>("seenEventIds")) ?? [];
const seen = new Set(seenList);
const newEvents: DecisionSetEvent[] = [];
for (const e of body.events) {
if (seen.has(e.eventId)) continue;
seen.add(e.eventId);
seenList.push(e.eventId);
newEvents.push(e);
state.fannedOut += 1;
state.lastEventId = e.eventId;
state.lastType = e.type;
state.lastTs = e.ts;
}
state.updatedAt = new Date().toISOString();
await this.state.storage.put("state", state);
const message = JSON.stringify({ type: "decision-events", setId: body.setId, events: body.events });
let delivered = 0;
for (const ws of this.state.getWebSockets()) {
try {
ws.send(message);
delivered += 1;
} catch {
// A dead socket drops out of getWebSockets on its own.
if (newEvents.length > 0) {
state.updatedAt = new Date().toISOString();
const trimmedSeen = seenList.length > 1000 ? seenList.slice(-1000) : seenList;
await this.state.storage.put("seenEventIds", trimmedSeen);
await this.state.storage.put("state", state);
const message = JSON.stringify({ type: "decision-events", setId: body.setId, events: newEvents });
for (const ws of this.state.getWebSockets()) {
try {
ws.send(message);
delivered += 1;
} catch {
// A dead socket drops out of getWebSockets on its own.
}
}
}
return Response.json({ ...state, subscribers: this.state.getWebSockets().length, delivered });
return Response.json({
...state,
subscribers: this.state.getWebSockets().length,
delivered,
deduplicated: body.events.length - newEvents.length,
});
}
if (url.pathname === "/state") {
const state = await this.loadState();
Expand Down Expand Up @@ -163,39 +179,53 @@ async function handlePostEvents(request: Request, env: Env): Promise<Response> {
return Response.json({ accepted: 0, inserted: 0, duplicates: 0, errors });
}

// Store first (D1, idempotent), fan out only what was actually new.
// Store first (D1, idempotent), then fan out to each set's Durable Object.
// Fan out all valid events (not just insertedEvents) because DO /ingest
// deduplicates by eventId; if DO ingest failed on an earlier attempt, a retry
// will report 0 D1 changes but still needs to reach the DO.
const statements = events.map((e) =>
env.DB.prepare(
"INSERT OR IGNORE INTO decision_set_events (event_id, set_id, question_ref, type, payload, ts) VALUES (?, ?, ?, ?, ?, ?)",
).bind(e.eventId, e.setId, e.questionRef, e.type, JSON.stringify(e.payload), e.ts),
);
const results = await env.DB.batch(statements);
const insertedEvents: DecisionSetEvent[] = [];
let inserted = 0;
results.forEach((r, i) => {
const changes = r.meta?.changes ?? 0;
inserted += changes;
if (changes > 0) insertedEvents.push(events[i] as DecisionSetEvent);
results.forEach((r) => {
inserted += r.meta?.changes ?? 0;
});

const fanout: Record<string, unknown> = {};
for (const [setId, setEvents] of groupBySet(insertedEvents)) {
let fanoutFailed = false;
for (const [setId, setEvents] of groupBySet(events)) {
const stub = env.SET_EVENTS.get(env.SET_EVENTS.idFromName(setId));
const res = await stub.fetch("https://do/ingest", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ setId, events: setEvents }),
});
fanout[setId] = res.ok ? await res.json().catch(() => null) : { error: `do ingest HTTP ${res.status}` };
try {
const res = await stub.fetch("https://do/ingest", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ setId, events: setEvents }),
});
if (!res.ok) {
fanoutFailed = true;
fanout[setId] = { error: `do ingest HTTP ${res.status}` };
} else {
fanout[setId] = await res.json().catch(() => null);
}
} catch (err) {
fanoutFailed = true;
fanout[setId] = { error: err instanceof Error ? err.message : String(err) };
}
}

return Response.json({
accepted: events.length,
inserted,
duplicates: events.length - inserted,
errors,
fanout,
});
return Response.json(
{
accepted: events.length,
inserted,
duplicates: events.length - inserted,
errors,
fanout,
},
{ status: fanoutFailed ? 502 : 200 },
);
}

async function handleGetEvents(url: URL, env: Env, setId: string): Promise<Response> {
Expand Down
94 changes: 94 additions & 0 deletions pm-stack/decision-events-worker/test/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
timingSafeEqual,
validateDecisionEvent,
} from "../src/events.ts";
import worker, { DecisionSetEvents, type Env } from "../src/index.ts";

const ev = (eventId: string, setId = "set-1") => ({
eventId,
Expand Down Expand Up @@ -77,6 +78,99 @@ describe("groupBySet", () => {
});
});

describe("DecisionSetEvents & POST /events fan-out retry", () => {
function makeMockEnv() {
const d1Events = new Set<string>();
const doStorage = new Map<string, unknown>();
const doInstance = new DecisionSetEvents({
storage: {
get: async <T>(k: string) => doStorage.get(k) as T | undefined,
put: async (k: string, v: unknown) => {
doStorage.set(k, v);
},
},
getWebSockets: () => [],
} as unknown as DurableObjectState);

let failNextIngest = false;
const env = {
WEBHOOK_SECRET: "s3cr3t",
DB: {
prepare: () => ({
bind: (eventId: string) => ({ eventId }),
}),
batch: async (stmts: Array<{ eventId: string }>) =>
stmts.map((s) => {
if (d1Events.has(s.eventId)) return { meta: { changes: 0 } };
d1Events.add(s.eventId);
return { meta: { changes: 1 } };
}),
} as unknown as D1Database,
SET_EVENTS: {
idFromName: (name: string) => name as unknown as DurableObjectId,
get: () => ({
fetch: async (url: string, init?: RequestInit) => {
if (failNextIngest) {
failNextIngest = false;
return new Response("boom", { status: 500 });
}
return doInstance.fetch(new Request(url, init));
},
}),
} as unknown as DurableObjectNamespace,
} satisfies Env;

return {
env,
setFailNextIngest: (v: boolean) => {
failNextIngest = v;
},
};
}

test("returns 502 on DO ingest failure and fans out exactly once on retry", async () => {
const { env, setFailNextIngest } = makeMockEnv();
const post = () =>
worker.fetch(
new Request("https://worker/events", {
method: "POST",
headers: { Authorization: "Bearer s3cr3t", "Content-Type": "application/json" },
body: JSON.stringify({ events: [ev("e1")] }),
}),
env,
);

setFailNextIngest(true);
const first = await post();
expect(first.status).toBe(502);
const firstBody = (await first.json()) as { inserted: number; fanout: Record<string, { error?: string }> };
expect(firstBody.inserted).toBe(1);
expect(firstBody.fanout["set-1"]?.error).toContain("500");

// Retry: D1 reports 0 changes, DO ingest succeeds and fans out e1 once.
const retry = await post();
expect(retry.status).toBe(200);
const retryBody = (await retry.json()) as {
inserted: number;
duplicates: number;
fanout: Record<string, { fannedOut: number; deduplicated: number }>;
};
expect(retryBody.inserted).toBe(0);
expect(retryBody.duplicates).toBe(1);
expect(retryBody.fanout["set-1"]?.fannedOut).toBe(1);
expect(retryBody.fanout["set-1"]?.deduplicated).toBe(0);

// Second retry: DO deduplicates e1, fannedOut remains 1.
const secondRetry = await post();
expect(secondRetry.status).toBe(200);
const secondBody = (await secondRetry.json()) as {
fanout: Record<string, { fannedOut: number; deduplicated: number }>;
};
expect(secondBody.fanout["set-1"]?.fannedOut).toBe(1);
expect(secondBody.fanout["set-1"]?.deduplicated).toBe(1);
});
});

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" });
Expand Down