348 lines
11 KiB
TypeScript
348 lines
11 KiB
TypeScript
import { describe, expect, test } from "vitest";
|
|
import {
|
|
PLUGIN_CAPABILITY_USE_EVENT_TYPE,
|
|
PLUGIN_CAPABILITY_USE_OUTBOX_QUEUE,
|
|
createPrismaPluginCapabilityUseStore,
|
|
handlePluginCapabilityUseJob,
|
|
parsePluginCapabilityUseJob,
|
|
PluginCapabilityUseJobError,
|
|
type PluginCapabilityUseRow,
|
|
type PluginCapabilityUseStorePrisma,
|
|
type PluginCapabilityUseStore,
|
|
} from "./plugin-capability-use.js";
|
|
|
|
function makeStore(): {
|
|
store: PluginCapabilityUseStore;
|
|
inserts: ReadonlyArray<PluginCapabilityUseRow>[];
|
|
} {
|
|
const inserts: ReadonlyArray<PluginCapabilityUseRow>[] = [];
|
|
return {
|
|
inserts,
|
|
store: {
|
|
async insertMany(rows) {
|
|
inserts.push(rows);
|
|
return { inserted: rows.length };
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
function validBatch(overrides?: Partial<Record<string, unknown>>) {
|
|
return {
|
|
outboxEventId: "evt-1",
|
|
tenantId: "t1",
|
|
eventType: PLUGIN_CAPABILITY_USE_EVENT_TYPE,
|
|
payload: {
|
|
pluginInvocationId: "inv-1",
|
|
tenantId: "t1",
|
|
pluginId: "de.acme.slack",
|
|
entries: [
|
|
{
|
|
id: "row-1",
|
|
pluginInvocationId: "inv-1",
|
|
tenantId: "t1",
|
|
pluginId: "de.acme.slack",
|
|
capability: "http.outbound",
|
|
outcome: "success",
|
|
payloadHash: "a".repeat(64),
|
|
durationMs: 12,
|
|
timestamp: "2026-05-17T20:00:00.000Z",
|
|
},
|
|
{
|
|
id: "row-2",
|
|
pluginInvocationId: "inv-1",
|
|
tenantId: "t1",
|
|
pluginId: "de.acme.slack",
|
|
capability: "log",
|
|
outcome: "success",
|
|
durationMs: 1,
|
|
timestamp: "2026-05-17T20:00:00.100Z",
|
|
},
|
|
],
|
|
...overrides,
|
|
},
|
|
};
|
|
}
|
|
|
|
describe("queue / event-type constants", () => {
|
|
test("exports stable queue + event-type names", () => {
|
|
expect(PLUGIN_CAPABILITY_USE_OUTBOX_QUEUE).toBe("outbox.plugin-capability-use");
|
|
expect(PLUGIN_CAPABILITY_USE_EVENT_TYPE).toBe("plugin.capability-use.batch");
|
|
});
|
|
});
|
|
|
|
describe("parsePluginCapabilityUseJob", () => {
|
|
test("parses a well-formed batch", () => {
|
|
const parsed = parsePluginCapabilityUseJob(validBatch());
|
|
expect(parsed.payload.entries).toHaveLength(2);
|
|
expect(parsed.payload.pluginId).toBe("de.acme.slack");
|
|
});
|
|
|
|
test("rejects missing payload", () => {
|
|
expect(() => parsePluginCapabilityUseJob({})).toThrow(PluginCapabilityUseJobError);
|
|
});
|
|
|
|
test("rejects empty entries array", () => {
|
|
expect(() => parsePluginCapabilityUseJob(validBatch({ entries: [] }))).toThrow(/EMPTY_BATCH|no entries/);
|
|
});
|
|
|
|
test("rejects entry missing required fields", () => {
|
|
expect(() =>
|
|
parsePluginCapabilityUseJob(
|
|
validBatch({ entries: [{ capability: "log", outcome: "success" }] })
|
|
)
|
|
).toThrow(PluginCapabilityUseJobError);
|
|
});
|
|
|
|
test.each([
|
|
["tenantId", "other-tenant"],
|
|
["pluginId", "de.acme.other"],
|
|
["pluginInvocationId", "inv-other"],
|
|
])("rejects entries whose %s differs from the batch envelope", (field, value) => {
|
|
expect(() =>
|
|
parsePluginCapabilityUseJob(
|
|
validBatch({
|
|
entries: [
|
|
{
|
|
id: "row-x",
|
|
pluginInvocationId: "inv-1",
|
|
tenantId: "t1",
|
|
pluginId: "de.acme.slack",
|
|
capability: "log",
|
|
outcome: "success",
|
|
timestamp: "2026-05-17T20:00:00.000Z",
|
|
[field]: value,
|
|
},
|
|
],
|
|
})
|
|
)
|
|
).toThrow(PluginCapabilityUseJobError);
|
|
});
|
|
|
|
test("rejects an outbox envelope whose tenant differs from the payload tenant", () => {
|
|
expect(() => parsePluginCapabilityUseJob({ ...validBatch(), tenantId: "other-tenant" })).toThrow(PluginCapabilityUseJobError);
|
|
});
|
|
|
|
test("inherits invocation defaults when entry omits them", () => {
|
|
const parsed = parsePluginCapabilityUseJob(
|
|
validBatch({
|
|
entries: [
|
|
{
|
|
id: "row-x",
|
|
capability: "log",
|
|
outcome: "success",
|
|
timestamp: "2026-05-17T20:00:00.000Z",
|
|
},
|
|
],
|
|
})
|
|
);
|
|
expect(parsed.payload.entries[0]?.tenantId).toBe("t1");
|
|
expect(parsed.payload.entries[0]?.pluginId).toBe("de.acme.slack");
|
|
expect(parsed.payload.entries[0]?.pluginInvocationId).toBe("inv-1");
|
|
});
|
|
});
|
|
|
|
describe("handlePluginCapabilityUseJob", () => {
|
|
test("persists every entry from a valid batch", async () => {
|
|
const { store, inserts } = makeStore();
|
|
const result = await handlePluginCapabilityUseJob(validBatch(), { store });
|
|
expect(result.outcome).toBe("persisted");
|
|
expect(result.inserted).toBe(2);
|
|
expect(inserts).toHaveLength(1);
|
|
expect(inserts[0]).toHaveLength(2);
|
|
expect(inserts[0]?.[0]?.timestamp).toBeInstanceOf(Date);
|
|
});
|
|
|
|
test("normalises undefined optional fields to null", async () => {
|
|
const { store, inserts } = makeStore();
|
|
await handlePluginCapabilityUseJob(validBatch(), { store });
|
|
const row = inserts[0]?.[1];
|
|
expect(row?.payloadHash).toBeNull();
|
|
expect(row?.errorCode).toBeNull();
|
|
});
|
|
|
|
test("rejects garbage payloads without retry", async () => {
|
|
const { store } = makeStore();
|
|
const warns: Record<string, unknown>[] = [];
|
|
const result = await handlePluginCapabilityUseJob({}, {
|
|
store,
|
|
logger: {
|
|
warn: (record) => warns.push(record),
|
|
error: () => undefined,
|
|
},
|
|
});
|
|
expect(result.outcome).toBe("rejected");
|
|
expect(result.reason).toBe("INVALID_PAYLOAD");
|
|
expect(warns).toHaveLength(1);
|
|
});
|
|
|
|
test("rejects scoped-entry mismatches without inserting audit rows", async () => {
|
|
const { store, inserts } = makeStore();
|
|
const result = await handlePluginCapabilityUseJob(
|
|
validBatch({
|
|
entries: [
|
|
{
|
|
id: "row-x",
|
|
pluginInvocationId: "inv-other",
|
|
tenantId: "t1",
|
|
pluginId: "de.acme.slack",
|
|
capability: "log",
|
|
outcome: "success",
|
|
timestamp: "2026-05-17T20:00:00.000Z",
|
|
},
|
|
],
|
|
}),
|
|
{ store }
|
|
);
|
|
expect(result).toEqual({ outcome: "rejected", inserted: 0, reason: "INVALID_PAYLOAD" });
|
|
expect(inserts).toHaveLength(0);
|
|
});
|
|
|
|
test("propagates transient DB errors so dispatcher retries", async () => {
|
|
const failingStore: PluginCapabilityUseStore = {
|
|
async insertMany() {
|
|
throw new Error("connection refused");
|
|
},
|
|
};
|
|
await expect(
|
|
handlePluginCapabilityUseJob(validBatch(), { store: failingStore })
|
|
).rejects.toThrow(/connection refused/);
|
|
});
|
|
|
|
test("treats duplicate receiver delivery as an idempotent zero-insert", async () => {
|
|
const inserts: ReadonlyArray<PluginCapabilityUseRow>[] = [];
|
|
const store: PluginCapabilityUseStore = {
|
|
async insertMany(rows) {
|
|
inserts.push(rows);
|
|
return { inserted: 0 };
|
|
},
|
|
};
|
|
|
|
const result = await handlePluginCapabilityUseJob(validBatch(), { store });
|
|
|
|
expect(result).toEqual({ outcome: "persisted", inserted: 0 });
|
|
expect(inserts).toHaveLength(1);
|
|
});
|
|
|
|
// F-003 — hash chain stamping.
|
|
describe("hash chain stamping (F-003)", () => {
|
|
test("stamps every inserted row with prevHash + rowHash", async () => {
|
|
const { store, inserts } = makeStore();
|
|
const result = await handlePluginCapabilityUseJob(validBatch(), { store });
|
|
expect(result.outcome).toBe("persisted");
|
|
const rows = inserts[0]!;
|
|
expect(rows.length).toBeGreaterThan(0);
|
|
for (const row of rows) {
|
|
expect(row.rowHash).toMatch(/^[0-9a-f]{64}$/);
|
|
}
|
|
// Within a batch each row's prevHash must equal the previous row's rowHash.
|
|
for (let i = 1; i < rows.length; i++) {
|
|
expect(rows[i]!.prevHash).toBe(rows[i - 1]!.rowHash);
|
|
}
|
|
// The genesis row's prevHash is null (no chain head supplied).
|
|
expect(rows[0]!.prevHash).toBeNull();
|
|
});
|
|
|
|
test("seeds prevHash from getChainHead when supplied", async () => {
|
|
const { inserts } = makeStore();
|
|
const fakeChainHead = "f".repeat(64);
|
|
const store: PluginCapabilityUseStore = {
|
|
async insertMany(rows) {
|
|
inserts.push(rows);
|
|
return { inserted: rows.length };
|
|
},
|
|
async getChainHead() {
|
|
return fakeChainHead;
|
|
},
|
|
};
|
|
await handlePluginCapabilityUseJob(validBatch(), { store });
|
|
const rows = inserts[0]!;
|
|
expect(rows[0]!.prevHash).toBe(fakeChainHead);
|
|
});
|
|
|
|
test("falls back to null seed when getChainHead throws", async () => {
|
|
const { inserts } = makeStore();
|
|
const store: PluginCapabilityUseStore = {
|
|
async insertMany(rows) {
|
|
inserts.push(rows);
|
|
return { inserted: rows.length };
|
|
},
|
|
async getChainHead() {
|
|
throw new Error("DB unavailable");
|
|
},
|
|
};
|
|
const result = await handlePluginCapabilityUseJob(validBatch(), { store });
|
|
expect(result.outcome).toBe("persisted");
|
|
expect(inserts[0]![0]!.prevHash).toBeNull();
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("createPrismaPluginCapabilityUseStore", () => {
|
|
test("uses createMany with skipDuplicates so outbox redelivery is idempotent", async () => {
|
|
const calls: unknown[] = [];
|
|
const prisma: PluginCapabilityUseStorePrisma = {
|
|
pluginCapabilityUse: {
|
|
async createMany(args) {
|
|
calls.push(args);
|
|
return { count: args.data.length };
|
|
},
|
|
async findFirst() {
|
|
return null;
|
|
},
|
|
},
|
|
};
|
|
const store = createPrismaPluginCapabilityUseStore(prisma);
|
|
|
|
const result = await store.insertMany([
|
|
{
|
|
id: "row-1",
|
|
pluginInvocationId: "inv-1",
|
|
tenantId: "t1",
|
|
pluginId: "de.acme.slack",
|
|
capability: "log",
|
|
outcome: "success",
|
|
payloadHash: null,
|
|
errorCode: null,
|
|
durationMs: null,
|
|
timestamp: new Date("2026-05-17T20:00:00.000Z"),
|
|
prevHash: null,
|
|
rowHash: "a".repeat(64),
|
|
},
|
|
]);
|
|
|
|
expect(result).toEqual({ inserted: 1 });
|
|
expect(calls).toEqual([
|
|
{
|
|
data: expect.arrayContaining([expect.objectContaining({ id: "row-1" })]),
|
|
skipDuplicates: true,
|
|
},
|
|
]);
|
|
});
|
|
|
|
test("reads the latest tenant chain head for cross-batch hash continuity", async () => {
|
|
const calls: unknown[] = [];
|
|
const prisma: PluginCapabilityUseStorePrisma = {
|
|
pluginCapabilityUse: {
|
|
async createMany() {
|
|
return { count: 0 };
|
|
},
|
|
async findFirst(args) {
|
|
calls.push(args);
|
|
return { rowHash: "f".repeat(64) };
|
|
},
|
|
},
|
|
};
|
|
const store = createPrismaPluginCapabilityUseStore(prisma);
|
|
|
|
await expect(store.getChainHead?.("t1")).resolves.toBe("f".repeat(64));
|
|
expect(calls).toEqual([
|
|
{
|
|
where: { tenantId: "t1", rowHash: { not: null } },
|
|
select: { rowHash: true },
|
|
orderBy: [{ timestamp: "desc" }, { id: "desc" }],
|
|
},
|
|
]);
|
|
});
|
|
});
|