Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* Shared helpers for the `outbox` CLI subtree.
|
||||
*
|
||||
* Both `requeue --event-id` and `requeue --type --since` flow through
|
||||
* the runners defined here so the citty command stays a thin wrapper
|
||||
* with full unit-test coverage on the business logic.
|
||||
*
|
||||
* The terminology mirrors the Prisma OutboxStatus enum (PENDING,
|
||||
* PROCESSING, DONE, FAILED, CANCELLED).
|
||||
*/
|
||||
|
||||
export type OutboxRequeueStatus = "PENDING" | "PROCESSING" | "DONE" | "FAILED" | "CANCELLED";
|
||||
|
||||
/**
|
||||
* Refusable statuses — we never reset an event that's currently being
|
||||
* worked on by the dispatcher (PROCESSING) or that's still waiting in
|
||||
* the queue (PENDING). Doing so would double-deliver the work.
|
||||
*/
|
||||
export const OUTBOX_REQUEUE_REFUSED_STATUSES: ReadonlySet<OutboxRequeueStatus> = new Set(["PENDING", "PROCESSING"]);
|
||||
|
||||
/**
|
||||
* Acceptable statuses for re-queue. DONE is included because the
|
||||
* operator may want to replay a side-effect (e.g. resend a billing
|
||||
* notification email that was lost in the receiver). The CLI emits a
|
||||
* warning for DONE so it's never an accident.
|
||||
*/
|
||||
export const OUTBOX_REQUEUE_ALLOWED_STATUSES: ReadonlySet<OutboxRequeueStatus> = new Set(["FAILED", "DONE", "CANCELLED"]);
|
||||
|
||||
export interface OutboxRequeueEventRow {
|
||||
id: string;
|
||||
eventType: string;
|
||||
status: OutboxRequeueStatus;
|
||||
tenantId: string | null;
|
||||
retries: number;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow interface against `@toolctrl/db` — just the methods the
|
||||
* runner uses. Tests inject an in-memory fake.
|
||||
*/
|
||||
export interface OutboxRequeueClient {
|
||||
outboxEvent: {
|
||||
findUnique(args: { where: { id: string } }): Promise<OutboxRequeueEventRow | null>;
|
||||
update(args: {
|
||||
where: { id: string };
|
||||
data: {
|
||||
status: OutboxRequeueStatus;
|
||||
retries: number;
|
||||
lastError: string | null;
|
||||
scheduledAt: Date;
|
||||
lockedUntil: null;
|
||||
processedAt: null;
|
||||
};
|
||||
}): Promise<OutboxRequeueEventRow>;
|
||||
findMany(args: {
|
||||
where: {
|
||||
eventType: string;
|
||||
createdAt: { gte: Date };
|
||||
status: { in: OutboxRequeueStatus[] };
|
||||
};
|
||||
select: { id: true; eventType: true; status: true; tenantId: true; retries: true; createdAt: true };
|
||||
orderBy: { createdAt: "asc" };
|
||||
take: number;
|
||||
}): Promise<OutboxRequeueEventRow[]>;
|
||||
updateMany(args: {
|
||||
where: { id: { in: string[] } };
|
||||
data: {
|
||||
status: OutboxRequeueStatus;
|
||||
retries: number;
|
||||
lastError: string | null;
|
||||
scheduledAt: Date;
|
||||
lockedUntil: null;
|
||||
processedAt: null;
|
||||
};
|
||||
}): Promise<{ count: number }>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OutboxRequeueOutput {
|
||||
log(message: string): void;
|
||||
warn(message: string): void;
|
||||
error(message: string): void;
|
||||
json(payload: unknown): void;
|
||||
}
|
||||
|
||||
export interface OutboxRequeueByIdArgs {
|
||||
eventId: string;
|
||||
json?: boolean;
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
export type OutboxRequeueByIdOutcome =
|
||||
| { exitCode: 0; status: "requeued"; eventId: string; previousStatus: OutboxRequeueStatus }
|
||||
| { exitCode: 1; status: "not_found" | "refused"; eventId: string; previousStatus?: OutboxRequeueStatus; message?: string };
|
||||
|
||||
function isStatus(value: unknown): value is OutboxRequeueStatus {
|
||||
return typeof value === "string" && ["PENDING", "PROCESSING", "DONE", "FAILED", "CANCELLED"].includes(value);
|
||||
}
|
||||
|
||||
export function normalizeStatus(value: unknown): OutboxRequeueStatus {
|
||||
if (isStatus(value)) return value;
|
||||
throw new Error(`Unrecognised OutboxStatus value ${JSON.stringify(value)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-queue a single event by id. Refuses to act on events that are
|
||||
* currently PENDING or PROCESSING — re-queueing them would double-
|
||||
* deliver the work because the dispatcher still has the original copy
|
||||
* in its pipeline.
|
||||
*/
|
||||
export async function runOutboxRequeueById(
|
||||
args: OutboxRequeueByIdArgs,
|
||||
deps: { client: OutboxRequeueClient; output: OutboxRequeueOutput }
|
||||
): Promise<OutboxRequeueByIdOutcome> {
|
||||
const now = args.now ?? new Date();
|
||||
const existing = await deps.client.outboxEvent.findUnique({ where: { id: args.eventId } });
|
||||
if (!existing) {
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: false, reason: "not_found", eventId: args.eventId });
|
||||
} else {
|
||||
deps.output.error(`outbox event ${args.eventId} not found`);
|
||||
}
|
||||
return { exitCode: 1, status: "not_found", eventId: args.eventId };
|
||||
}
|
||||
const status = normalizeStatus(existing.status);
|
||||
if (OUTBOX_REQUEUE_REFUSED_STATUSES.has(status)) {
|
||||
const message = `outbox event ${args.eventId} is currently ${status}; refuse to re-queue (would double-deliver)`;
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: false, reason: "refused", eventId: args.eventId, status });
|
||||
} else {
|
||||
deps.output.error(message);
|
||||
}
|
||||
return { exitCode: 1, status: "refused", eventId: args.eventId, previousStatus: status, message };
|
||||
}
|
||||
if (!OUTBOX_REQUEUE_ALLOWED_STATUSES.has(status)) {
|
||||
const message = `outbox event ${args.eventId} has unsupported status ${status}`;
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: false, reason: "refused", eventId: args.eventId, status });
|
||||
} else {
|
||||
deps.output.error(message);
|
||||
}
|
||||
return { exitCode: 1, status: "refused", eventId: args.eventId, previousStatus: status, message };
|
||||
}
|
||||
|
||||
if (status === "DONE") {
|
||||
deps.output.warn(`outbox event ${args.eventId} is DONE; re-queueing will replay the side effect`);
|
||||
}
|
||||
|
||||
await deps.client.outboxEvent.update({
|
||||
where: { id: args.eventId },
|
||||
data: {
|
||||
status: "PENDING",
|
||||
retries: 0,
|
||||
lastError: null,
|
||||
scheduledAt: now,
|
||||
lockedUntil: null,
|
||||
processedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: true, eventId: args.eventId, previousStatus: status });
|
||||
} else {
|
||||
deps.output.log(`outbox event ${args.eventId} re-queued (was ${status})`);
|
||||
}
|
||||
return { exitCode: 0, status: "requeued", eventId: args.eventId, previousStatus: status };
|
||||
}
|
||||
|
||||
export interface OutboxRequeueBulkArgs {
|
||||
type: string;
|
||||
since: string;
|
||||
/** Optional cap to avoid runaway re-queues. Default 10_000. */
|
||||
limit?: number;
|
||||
/** `true` ⇒ confirm, perform the writes; `false` ⇒ dry-run summary only. */
|
||||
apply?: boolean;
|
||||
/** Include DONE events too. Off by default for safety. */
|
||||
includeDone?: boolean;
|
||||
json?: boolean;
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
export type OutboxRequeueBulkOutcome = {
|
||||
exitCode: 0 | 1;
|
||||
status: "previewed" | "requeued" | "invalid_args";
|
||||
matched: number;
|
||||
applied: number;
|
||||
eventType: string;
|
||||
since: Date | null;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const OUTBOX_REQUEUE_BULK_DEFAULT_LIMIT = 10_000;
|
||||
const OUTBOX_EVENT_TYPE_PATTERN = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*){2,}$/u;
|
||||
|
||||
export async function runOutboxRequeueBulk(
|
||||
args: OutboxRequeueBulkArgs,
|
||||
deps: { client: OutboxRequeueClient; output: OutboxRequeueOutput }
|
||||
): Promise<OutboxRequeueBulkOutcome> {
|
||||
const limit = Math.max(1, Math.min(args.limit ?? OUTBOX_REQUEUE_BULK_DEFAULT_LIMIT, 100_000));
|
||||
if (!OUTBOX_EVENT_TYPE_PATTERN.test(args.type)) {
|
||||
const message = `--type must match <domain>.<entity>.<verb> (got ${JSON.stringify(args.type)})`;
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: false, reason: "invalid_args", message });
|
||||
} else {
|
||||
deps.output.error(message);
|
||||
}
|
||||
return { exitCode: 1, status: "invalid_args", matched: 0, applied: 0, eventType: args.type, since: null, message };
|
||||
}
|
||||
const since = new Date(args.since);
|
||||
if (Number.isNaN(since.getTime())) {
|
||||
const message = `--since must be a valid ISO-8601 timestamp (got ${JSON.stringify(args.since)})`;
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: false, reason: "invalid_args", message });
|
||||
} else {
|
||||
deps.output.error(message);
|
||||
}
|
||||
return { exitCode: 1, status: "invalid_args", matched: 0, applied: 0, eventType: args.type, since: null, message };
|
||||
}
|
||||
|
||||
const statusFilter: OutboxRequeueStatus[] = args.includeDone ? ["FAILED", "DONE", "CANCELLED"] : ["FAILED", "CANCELLED"];
|
||||
const candidates = await deps.client.outboxEvent.findMany({
|
||||
where: {
|
||||
eventType: args.type,
|
||||
createdAt: { gte: since },
|
||||
status: { in: statusFilter },
|
||||
},
|
||||
select: { id: true, eventType: true, status: true, tenantId: true, retries: true, createdAt: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: limit,
|
||||
});
|
||||
|
||||
if (!args.apply) {
|
||||
if (args.json) {
|
||||
deps.output.json({
|
||||
ok: true,
|
||||
applied: 0,
|
||||
matched: candidates.length,
|
||||
eventType: args.type,
|
||||
since: since.toISOString(),
|
||||
preview: candidates.slice(0, 10).map((c) => ({ id: c.id, status: c.status, tenantId: c.tenantId })),
|
||||
});
|
||||
} else {
|
||||
deps.output.log(
|
||||
`outbox requeue (dry-run): ${candidates.length} event(s) matched type=${args.type} since=${since.toISOString()}; pass --apply to perform the re-queue`
|
||||
);
|
||||
}
|
||||
return { exitCode: 0, status: "previewed", matched: candidates.length, applied: 0, eventType: args.type, since };
|
||||
}
|
||||
|
||||
if (candidates.length === 0) {
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: true, applied: 0, matched: 0, eventType: args.type, since: since.toISOString() });
|
||||
} else {
|
||||
deps.output.log(`outbox requeue: no events matched type=${args.type} since=${since.toISOString()}`);
|
||||
}
|
||||
return { exitCode: 0, status: "requeued", matched: 0, applied: 0, eventType: args.type, since };
|
||||
}
|
||||
|
||||
const now = args.now ?? new Date();
|
||||
const result = await deps.client.outboxEvent.updateMany({
|
||||
where: { id: { in: candidates.map((c) => c.id) } },
|
||||
data: {
|
||||
status: "PENDING",
|
||||
retries: 0,
|
||||
lastError: null,
|
||||
scheduledAt: now,
|
||||
lockedUntil: null,
|
||||
processedAt: null,
|
||||
},
|
||||
});
|
||||
if (args.json) {
|
||||
deps.output.json({ ok: true, applied: result.count, matched: candidates.length, eventType: args.type, since: since.toISOString() });
|
||||
} else {
|
||||
deps.output.log(`outbox requeue: ${result.count} event(s) re-queued (type=${args.type} since=${since.toISOString()})`);
|
||||
}
|
||||
return { exitCode: 0, status: "requeued", matched: candidates.length, applied: result.count, eventType: args.type, since };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { defineCommand } from "citty";
|
||||
|
||||
import { outboxRequeueCommand } from "./requeue.js";
|
||||
|
||||
export const outboxCommand = defineCommand({
|
||||
meta: {
|
||||
name: "outbox",
|
||||
description: "Operator commands for the transactional outbox (re-queue failed events, bulk replay).",
|
||||
},
|
||||
subCommands: {
|
||||
requeue: outboxRequeueCommand,
|
||||
},
|
||||
});
|
||||
|
||||
export { outboxRequeueCommand };
|
||||
+336
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* `toolctrl-cli outbox requeue` — re-queue failed (or dead-letter) outbox
|
||||
* events back into the dispatcher's pending pool.
|
||||
*
|
||||
* Two modes:
|
||||
* - `--event-id <id>`: single-event re-queue. Refuses to act on
|
||||
* events whose current status is PENDING or PROCESSING (those are
|
||||
* still in flight; resetting them double-delivers).
|
||||
* - `--type <eventType> --since <ISO-timestamp>`: bulk re-queue. By
|
||||
* default this is a dry-run (count + small preview); pass `--apply`
|
||||
* to perform the writes.
|
||||
*
|
||||
* Output: human summary by default, JSON when `--json` is set. The CLI
|
||||
* uses `@toolctrl/db` directly so the worker process does not need to
|
||||
* be reachable.
|
||||
*/
|
||||
import { defineCommand } from "citty";
|
||||
import consola from "consola";
|
||||
|
||||
import {
|
||||
runOutboxRequeueById,
|
||||
runOutboxRequeueBulk,
|
||||
type OutboxRequeueClient,
|
||||
type OutboxRequeueOutput,
|
||||
} from "./_lib.js";
|
||||
|
||||
function makeOutput(json: boolean): OutboxRequeueOutput {
|
||||
return {
|
||||
log: (msg) => (json ? undefined : consola.success(msg)),
|
||||
warn: (msg) => consola.warn(msg),
|
||||
error: (msg) => (json ? undefined : consola.error(msg)),
|
||||
json: (payload) => consola.log(JSON.stringify(payload)),
|
||||
};
|
||||
}
|
||||
|
||||
export const outboxRequeueCommand = defineCommand({
|
||||
meta: {
|
||||
name: "requeue",
|
||||
description: "Re-queue a single FAILED/DONE outbox event by id, or bulk-re-queue by eventType + since timestamp.",
|
||||
},
|
||||
args: {
|
||||
"event-id": {
|
||||
type: "string",
|
||||
required: false,
|
||||
description: "Single-event mode: outbox event id to re-queue.",
|
||||
},
|
||||
type: {
|
||||
type: "string",
|
||||
required: false,
|
||||
description: "Bulk mode: event type to re-queue (must include all three segments, e.g. 'billing.subscription.ended').",
|
||||
},
|
||||
since: {
|
||||
type: "string",
|
||||
required: false,
|
||||
description: "Bulk mode: ISO-8601 lower bound on createdAt.",
|
||||
},
|
||||
apply: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
default: false,
|
||||
description: "Bulk mode only: perform the write (default is a dry-run preview).",
|
||||
},
|
||||
"include-done": {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
default: false,
|
||||
description: "Bulk mode: include DONE events too (default is FAILED + CANCELLED only).",
|
||||
},
|
||||
limit: {
|
||||
type: "string",
|
||||
required: false,
|
||||
description: "Bulk mode: cap on rows considered (default 10000).",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
default: false,
|
||||
description: "Emit JSON instead of human-readable output.",
|
||||
},
|
||||
},
|
||||
async run({ args }) {
|
||||
const json = Boolean(args.json);
|
||||
const eventId = typeof args["event-id"] === "string" && args["event-id"].length > 0 ? args["event-id"] : null;
|
||||
const typeArg = typeof args.type === "string" && args.type.length > 0 ? args.type : null;
|
||||
const sinceArg = typeof args.since === "string" && args.since.length > 0 ? args.since : null;
|
||||
|
||||
if (eventId && (typeArg || sinceArg)) {
|
||||
consola.error("Pass --event-id OR (--type + --since), not both.");
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
if (!eventId && (!typeArg || !sinceArg)) {
|
||||
consola.error("Either --event-id or (--type + --since) is required.");
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const { getDbClient } = await import("@toolctrl/db/client.server");
|
||||
const prisma = getDbClient() as unknown as OutboxRequeueClient;
|
||||
const output = makeOutput(json);
|
||||
|
||||
try {
|
||||
if (eventId) {
|
||||
const outcome = await runOutboxRequeueById(
|
||||
{ eventId, json },
|
||||
{ client: prisma, output }
|
||||
);
|
||||
process.exitCode = outcome.exitCode;
|
||||
return;
|
||||
}
|
||||
|
||||
const limit = typeof args.limit === "string" && args.limit.length > 0 ? Number.parseInt(args.limit, 10) : undefined;
|
||||
const outcome = await runOutboxRequeueBulk(
|
||||
{
|
||||
type: typeArg!,
|
||||
since: sinceArg!,
|
||||
apply: Boolean(args.apply),
|
||||
includeDone: Boolean(args["include-done"]),
|
||||
...(typeof limit === "number" && Number.isFinite(limit) ? { limit } : {}),
|
||||
json,
|
||||
},
|
||||
{ client: prisma, output }
|
||||
);
|
||||
process.exitCode = outcome.exitCode;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (json) {
|
||||
output.json({ ok: false, reason: "exception", message });
|
||||
} else {
|
||||
consola.error(`outbox requeue failed: ${message}`);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
}
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user