Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,336 @@
import { describe, it, expect, vi } from "vitest";
import {
normalizeStatus,
runOutboxRequeueById,
runOutboxRequeueBulk,
type OutboxRequeueClient,
type OutboxRequeueEventRow,
type OutboxRequeueOutput,
type OutboxRequeueStatus,
} from "./_lib.js";
describe("normalizeStatus", () => {
it("throws on unknown database enum values", () => {
expect(() => normalizeStatus("ARCHIVED")).toThrow(/Unrecognised OutboxStatus/);
});
});
interface FakeState {
byId: Map<string, OutboxRequeueEventRow>;
updates: Array<{ id: string; data: Record<string, unknown> }>;
updateMany: Array<{ ids: string[]; data: Record<string, unknown> }>;
}
function fakeClient(state: FakeState): OutboxRequeueClient {
return {
outboxEvent: {
async findUnique({ where }) {
return state.byId.get(where.id) ?? null;
},
async update({ where, data }) {
const row = state.byId.get(where.id);
if (!row) throw new Error(`no row ${where.id}`);
const next: OutboxRequeueEventRow = { ...row, status: data.status, retries: data.retries };
state.byId.set(where.id, next);
state.updates.push({ id: where.id, data: data as unknown as Record<string, unknown> });
return next;
},
async findMany({ where, take }) {
const all = Array.from(state.byId.values())
.filter((r) => r.eventType === where.eventType && r.createdAt >= where.createdAt.gte && where.status.in.includes(r.status))
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
.slice(0, take);
return all;
},
async updateMany({ where, data }) {
let count = 0;
for (const id of where.id.in) {
const row = state.byId.get(id);
if (row) {
state.byId.set(id, { ...row, status: data.status, retries: data.retries });
count += 1;
}
}
state.updateMany.push({ ids: where.id.in, data: data as unknown as Record<string, unknown> });
return { count };
},
},
};
}
function makeOutput(): OutboxRequeueOutput & { logs: string[]; warns: string[]; errors: string[]; jsons: unknown[] } {
const out = {
logs: [] as string[],
warns: [] as string[],
errors: [] as string[],
jsons: [] as unknown[],
log(msg: string) {
out.logs.push(msg);
},
warn(msg: string) {
out.warns.push(msg);
},
error(msg: string) {
out.errors.push(msg);
},
json(payload: unknown) {
out.jsons.push(payload);
},
};
return out;
}
function row(id: string, overrides: Partial<OutboxRequeueEventRow> = {}): OutboxRequeueEventRow {
return {
id,
eventType: "billing.subscription.ended",
status: "FAILED",
tenantId: "tenant-1",
retries: 3,
createdAt: new Date("2026-05-20T08:00:00Z"),
...overrides,
};
}
describe("runOutboxRequeueById", () => {
it("re-queues a FAILED event and resets retry counters", async () => {
const state: FakeState = {
byId: new Map([["evt-1", row("evt-1", { status: "FAILED", retries: 5 })]]),
updates: [],
updateMany: [],
};
const output = makeOutput();
const outcome = await runOutboxRequeueById({ eventId: "evt-1", now: new Date("2026-05-25T00:00:00Z") }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(0);
expect(outcome.status).toBe("requeued");
expect(state.updates).toHaveLength(1);
const update = state.updates[0]!.data as { status: OutboxRequeueStatus; retries: number; lastError: string | null };
expect(update.status).toBe("PENDING");
expect(update.retries).toBe(0);
expect(update.lastError).toBeNull();
expect(output.logs.some((m) => m.includes("re-queued"))).toBe(true);
});
it("emits JSON when --json is set", async () => {
const state: FakeState = {
byId: new Map([["evt-2", row("evt-2", { status: "FAILED" })]]),
updates: [],
updateMany: [],
};
const output = makeOutput();
await runOutboxRequeueById({ eventId: "evt-2", json: true }, { client: fakeClient(state), output });
expect(output.jsons[0]).toEqual({ ok: true, eventId: "evt-2", previousStatus: "FAILED" });
expect(output.logs).toEqual([]);
});
it("refuses to re-queue events still in PENDING", async () => {
const state: FakeState = {
byId: new Map([["evt-3", row("evt-3", { status: "PENDING" })]]),
updates: [],
updateMany: [],
};
const output = makeOutput();
const outcome = await runOutboxRequeueById({ eventId: "evt-3" }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(1);
expect(outcome.status).toBe("refused");
expect(state.updates).toEqual([]);
expect(output.errors[0]).toMatch(/refuse to re-queue/);
});
it("refuses to re-queue events currently PROCESSING", async () => {
const state: FakeState = {
byId: new Map([["evt-4", row("evt-4", { status: "PROCESSING" })]]),
updates: [],
updateMany: [],
};
const output = makeOutput();
const outcome = await runOutboxRequeueById({ eventId: "evt-4" }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(1);
expect(state.updates).toEqual([]);
});
it("re-queues DONE events but warns the operator", async () => {
const state: FakeState = {
byId: new Map([["evt-5", row("evt-5", { status: "DONE", retries: 0 })]]),
updates: [],
updateMany: [],
};
const output = makeOutput();
const outcome = await runOutboxRequeueById({ eventId: "evt-5" }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(0);
expect(state.updates).toHaveLength(1);
expect(output.warns[0]).toMatch(/will replay/);
});
it("returns not_found when the event does not exist", async () => {
const state: FakeState = { byId: new Map(), updates: [], updateMany: [] };
const output = makeOutput();
const outcome = await runOutboxRequeueById({ eventId: "ghost" }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(1);
expect(outcome.status).toBe("not_found");
expect(output.errors[0]).toMatch(/not found/);
});
it("emits JSON for not_found lookups when --json is set", async () => {
const state: FakeState = { byId: new Map(), updates: [], updateMany: [] };
const output = makeOutput();
const outcome = await runOutboxRequeueById({ eventId: "ghost", json: true }, { client: fakeClient(state), output });
expect(outcome.status).toBe("not_found");
expect(output.jsons[0]).toEqual({ ok: false, reason: "not_found", eventId: "ghost" });
expect(output.errors).toEqual([]);
});
});
describe("runOutboxRequeueBulk", () => {
function bulkState(): FakeState {
return {
byId: new Map([
["a", row("a", { status: "FAILED", createdAt: new Date("2026-05-21T00:00:00Z") })],
["b", row("b", { status: "FAILED", createdAt: new Date("2026-05-22T00:00:00Z") })],
["c", row("c", { status: "DONE", createdAt: new Date("2026-05-22T00:00:00Z") })],
["d", row("d", { status: "PENDING", createdAt: new Date("2026-05-22T00:00:00Z") })],
["e", row("e", { status: "FAILED", createdAt: new Date("2026-05-19T00:00:00Z") })],
["f", row("f", { eventType: "billing.subscription.cancelled", status: "FAILED", createdAt: new Date("2026-05-22T00:00:00Z") })],
]),
updates: [],
updateMany: [],
};
}
it("previews matched count without writing when --apply is omitted", async () => {
const state = bulkState();
const output = makeOutput();
const outcome = await runOutboxRequeueBulk({ type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z" }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(0);
expect(outcome.status).toBe("previewed");
expect(outcome.matched).toBe(2);
expect(outcome.applied).toBe(0);
expect(state.updateMany).toEqual([]);
expect(output.logs[0]).toMatch(/dry-run/);
});
it("re-queues matching events when --apply is set", async () => {
const state = bulkState();
const output = makeOutput();
const outcome = await runOutboxRequeueBulk(
{ type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z", apply: true, now: new Date("2026-05-25T00:00:00Z") },
{ client: fakeClient(state), output }
);
expect(outcome.exitCode).toBe(0);
expect(outcome.status).toBe("requeued");
expect(outcome.applied).toBe(2);
expect(state.updateMany).toHaveLength(1);
// FAILED rows a + b should have flipped to PENDING.
expect(state.byId.get("a")?.status).toBe("PENDING");
expect(state.byId.get("b")?.status).toBe("PENDING");
expect(state.byId.get("c")?.status).toBe("DONE");
expect(state.byId.get("d")?.status).toBe("PENDING"); // already pending, untouched
});
it("includes DONE events when --include-done is set", async () => {
const state = bulkState();
const output = makeOutput();
const outcome = await runOutboxRequeueBulk(
{ type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z", apply: true, includeDone: true },
{ client: fakeClient(state), output }
);
expect(outcome.applied).toBe(3);
expect(state.byId.get("c")?.status).toBe("PENDING");
});
it("rejects malformed event type", async () => {
const state = bulkState();
const output = makeOutput();
const outcome = await runOutboxRequeueBulk({ type: "notavalidtype", since: "2026-05-20T00:00:00Z" }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(1);
expect(outcome.status).toBe("invalid_args");
expect(output.errors[0]).toMatch(/must match/);
});
it("rejects malformed --since", async () => {
const state = bulkState();
const output = makeOutput();
const outcome = await runOutboxRequeueBulk({ type: "billing.subscription.ended", since: "not-a-date" }, { client: fakeClient(state), output });
expect(outcome.exitCode).toBe(1);
expect(outcome.status).toBe("invalid_args");
expect(output.errors[0]).toMatch(/ISO-8601/);
});
it("emits JSON when --json is set", async () => {
const state = bulkState();
const output = makeOutput();
await runOutboxRequeueBulk(
{ type: "billing.subscription.ended", since: "2026-05-20T00:00:00Z", apply: true, json: true },
{ client: fakeClient(state), output }
);
expect(output.jsons[0]).toMatchObject({ ok: true, applied: 2, matched: 2, eventType: "billing.subscription.ended" });
});
it("caps dry-run JSON previews at 10 rows", async () => {
const state: FakeState = {
byId: new Map(
Array.from({ length: 12 }, (_, index) => {
const id = `evt-${index + 1}`;
return [id, row(id, { createdAt: new Date(`2026-05-${String(index + 1).padStart(2, "0")}T00:00:00Z`) })];
})
),
updates: [],
updateMany: [],
};
const output = makeOutput();
await runOutboxRequeueBulk({ type: "billing.subscription.ended", since: "2026-05-01T00:00:00Z", json: true }, { client: fakeClient(state), output });
expect(output.jsons[0]).toMatchObject({ ok: true, applied: 0, matched: 12 });
expect((output.jsons[0] as { preview: unknown[] }).preview).toHaveLength(10);
expect(state.updateMany).toEqual([]);
});
it("returns matched=0 cleanly when no events match", async () => {
const state = bulkState();
const output = makeOutput();
const outcome = await runOutboxRequeueBulk(
{ type: "billing.subscription.ended", since: "2030-01-01T00:00:00Z", apply: true },
{ client: fakeClient(state), output }
);
expect(outcome.exitCode).toBe(0);
expect(outcome.matched).toBe(0);
expect(outcome.applied).toBe(0);
});
});
describe("outboxRequeueCommand argument handling", () => {
it("is wired into the CLI subtree", async () => {
const mod = await import("./index.js");
expect(mod.outboxCommand).toBeDefined();
expect(typeof mod.outboxRequeueCommand.run).toBe("function");
});
});
describe("OutboxRequeueClient narrowness", () => {
it("only requires the four methods the runner consumes", () => {
// This is a structural-typing sanity check: a client with extra
// fields is still acceptable, but missing one of the four methods
// must be a type error. The test is intentionally compile-time
// adjacent; we keep one runtime assertion to keep vitest happy.
const minimal: OutboxRequeueClient = {
outboxEvent: {
findUnique: vi.fn(async () => null),
update: vi.fn(
async (): Promise<OutboxRequeueEventRow> => ({
id: "x",
eventType: "y.y.y",
status: "PENDING" as OutboxRequeueStatus,
tenantId: null,
retries: 0,
createdAt: new Date(),
})
),
findMany: vi.fn(async () => []),
updateMany: vi.fn(async () => ({ count: 0 })),
},
};
expect(Object.keys(minimal.outboxEvent)).toHaveLength(4);
});
});