796 lines
29 KiB
TypeScript
796 lines
29 KiB
TypeScript
import { afterEach, describe, expect, test, vi } from "vitest";
|
|
import { queueNames } from "@toolctrl/queue";
|
|
import type { OutboxReceiverIdempotencyStore } from "@toolctrl/db/outbox-receiver";
|
|
import { registerHook } from "@toolctrl/plugin-runtime";
|
|
import { z } from "zod";
|
|
|
|
import {
|
|
PLUGIN_HOOK_FANOUT_ENQUEUE_CONCURRENCY,
|
|
PLUGIN_HOOK_FANOUT_OUTBOX_QUEUE,
|
|
type PluginHookFanoutResult,
|
|
parsePluginHookFanoutJob,
|
|
PluginHookFanoutJobError,
|
|
runPluginHookFanoutJob,
|
|
type PluginHookFanoutDeps,
|
|
type PluginHookFanoutStore,
|
|
} from "./plugin-hook-fanout.js";
|
|
|
|
const originalNodeEnv = process.env.NODE_ENV;
|
|
|
|
afterEach(() => {
|
|
if (originalNodeEnv === undefined) {
|
|
delete process.env.NODE_ENV;
|
|
} else {
|
|
process.env.NODE_ENV = originalNodeEnv;
|
|
}
|
|
});
|
|
|
|
function envelope(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
outboxEventId: "evt_1",
|
|
tenantId: "tenant_1",
|
|
eventType: "plugin.hook.tenant.created",
|
|
payload: { tenantId: "tenant_1", slug: "acme", ownerEmail: "owner@example.test", createdAt: "2026-05-26T20:00:00.000Z" },
|
|
dispatchKey: "tenant:tenant_1:created",
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function validManifest(hooks: Array<{ name: string; export: string }>) {
|
|
return {
|
|
schemaVersion: 1 as const,
|
|
id: "com.acme.audit",
|
|
version: "1.0.0",
|
|
name: "Audit",
|
|
entry: "plugin.wasm",
|
|
wasmSha256: "a".repeat(64),
|
|
signature: "b".repeat(128),
|
|
signedBy: "c".repeat(64),
|
|
allowedHosts: [],
|
|
capabilities: [],
|
|
hooks,
|
|
};
|
|
}
|
|
|
|
function createMemoryIdempotencyStore(): OutboxReceiverIdempotencyStore & { forget(key: string): Promise<void> } {
|
|
const pending = new Set<string>();
|
|
const complete = new Map<string, unknown>();
|
|
return {
|
|
claim: vi.fn(async (key: string) => {
|
|
if (pending.has(key) || complete.has(key)) return false;
|
|
pending.add(key);
|
|
return true;
|
|
}),
|
|
complete: vi.fn(async (key: string, result: unknown) => {
|
|
pending.delete(key);
|
|
complete.set(key, result);
|
|
}),
|
|
get: vi.fn(async (key: string) => {
|
|
if (complete.has(key)) return { state: "complete" as const, result: complete.get(key) };
|
|
if (pending.has(key)) return { state: "pending" as const };
|
|
return null;
|
|
}),
|
|
forget: vi.fn(async (key: string) => {
|
|
pending.delete(key);
|
|
complete.delete(key);
|
|
}),
|
|
};
|
|
}
|
|
|
|
describe("plugin hook fanout constants", () => {
|
|
test("exports the stable outbox queue name", () => {
|
|
expect(PLUGIN_HOOK_FANOUT_OUTBOX_QUEUE).toBe("outbox.plugin-hook");
|
|
});
|
|
});
|
|
|
|
describe("parsePluginHookFanoutJob", () => {
|
|
test("parses a plugin hook outbox envelope", () => {
|
|
const parsed = parsePluginHookFanoutJob(envelope());
|
|
expect(parsed.hookName).toBe("tenant.created");
|
|
expect(parsed.tenantId).toBe("tenant_1");
|
|
});
|
|
|
|
test("rejects non-plugin-hook event types", () => {
|
|
expect(() => parsePluginHookFanoutJob(envelope({ eventType: "mail.welcome.send" }))).toThrow(PluginHookFanoutJobError);
|
|
});
|
|
|
|
test("rejects malformed plugin hook names", () => {
|
|
expect(() => parsePluginHookFanoutJob(envelope({ eventType: "plugin.hook.singleword" }))).toThrow(
|
|
/invalid plugin hook name singleword/
|
|
);
|
|
expect(() => parsePluginHookFanoutJob(envelope({ eventType: "plugin.hook.Tenant.created" }))).toThrow(
|
|
/invalid plugin hook name Tenant\.created/
|
|
);
|
|
});
|
|
|
|
test("rejects syntactically valid but unregistered plugin hook names", () => {
|
|
expect(() => parsePluginHookFanoutJob(envelope({ eventType: "plugin.hook.billing.paid" }))).toThrow(
|
|
/unsupported plugin hook name billing\.paid/
|
|
);
|
|
});
|
|
|
|
test("rejects registered hooks outside the production allowlist in production", () => {
|
|
process.env.NODE_ENV = "production";
|
|
registerHook({
|
|
name: "billing.settled",
|
|
outboxEventType: "plugin.hook.billing.settled",
|
|
payloadSchema: z.object({ invoiceId: z.string() }),
|
|
});
|
|
|
|
expect(() => parsePluginHookFanoutJob(envelope({ eventType: "plugin.hook.billing.settled" }))).toThrow(
|
|
/not production-available/
|
|
);
|
|
});
|
|
|
|
test("requires tenant scope", () => {
|
|
expect(() => parsePluginHookFanoutJob(envelope({ tenantId: null }))).toThrow(/tenantId/);
|
|
});
|
|
});
|
|
|
|
describe("runPluginHookFanoutJob", () => {
|
|
test("enqueues one plugin.invoke job per enabled subscriber declaring the hook", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
{
|
|
pluginId: "com.acme.other",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "entity.created", export: "onEntityCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:entity.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuedPlugins: string[] = [];
|
|
const enqueuePluginInvoke = vi.fn<PluginHookFanoutDeps["enqueuePluginInvoke"]>(async (descriptor) => {
|
|
enqueuedPlugins.push(descriptor.payload.pluginId);
|
|
});
|
|
const result = await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke });
|
|
|
|
expect(result).toMatchObject({ matched: 1, enqueued: 1, hookName: "tenant.created" });
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
queueName: queueNames.pluginInvoke,
|
|
jobName: "invoke-plugin",
|
|
payload: expect.objectContaining({
|
|
kind: "plugin.invoke",
|
|
tenantId: "tenant_1",
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
hookName: "onTenantCreated",
|
|
input: expect.objectContaining({ tenantId: "tenant_1", slug: "acme" }),
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
idempotencyKey: "plugin-hook:evt_1:com.acme.audit:1.0.0",
|
|
})
|
|
);
|
|
});
|
|
|
|
test("invokes the declared WASM export while preserving the logical hook name", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn<PluginHookFanoutDeps["enqueuePluginInvoke"]>(async () => undefined);
|
|
|
|
await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke });
|
|
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
hookName: "onTenantCreated",
|
|
metadata: expect.objectContaining({
|
|
logicalHookName: "tenant.created",
|
|
eventType: "plugin.hook.tenant.created",
|
|
}),
|
|
}),
|
|
}),
|
|
expect.any(Object)
|
|
);
|
|
});
|
|
|
|
test("skips enabled hook subscribers when hook consent grant is missing", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.granted",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
{
|
|
pluginId: "com.acme.ungranted",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:entity.created" }],
|
|
},
|
|
{
|
|
pluginId: "com.acme.legacy",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn<PluginHookFanoutDeps["enqueuePluginInvoke"]>(async () => undefined);
|
|
|
|
const result = await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke });
|
|
|
|
expect(result).toMatchObject({ matched: 1, enqueued: 1 });
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledTimes(1);
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
pluginId: "com.acme.granted",
|
|
}),
|
|
}),
|
|
expect.any(Object)
|
|
);
|
|
});
|
|
|
|
test("skips subscribers with invalid stored manifests", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.invalid",
|
|
version: "1.0.0",
|
|
manifest: { hooks: [{ name: "tenant.created", export: "onTenantCreated" }] },
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
{
|
|
pluginId: "com.acme.valid",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn<PluginHookFanoutDeps["enqueuePluginInvoke"]>(async () => undefined);
|
|
|
|
const result = await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke });
|
|
|
|
expect(result).toMatchObject({ matched: 1, enqueued: 1 });
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
pluginId: "com.acme.valid",
|
|
}),
|
|
}),
|
|
expect.any(Object)
|
|
);
|
|
});
|
|
|
|
test("skips per-user disabled hook subscribers when payload has userId", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.user-enabled",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "user.created", export: "onUserCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:user.created" }],
|
|
userConfigs: [{ enabled: true }],
|
|
},
|
|
{
|
|
pluginId: "com.acme.user-disabled",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "user.created", export: "onUserCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:user.created" }],
|
|
userConfigs: [{ enabled: false }],
|
|
},
|
|
{
|
|
pluginId: "com.acme.tenant-default",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "user.created", export: "onUserCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:user.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuedPlugins: string[] = [];
|
|
const enqueuePluginInvoke = vi.fn<PluginHookFanoutDeps["enqueuePluginInvoke"]>(async (descriptor) => {
|
|
enqueuedPlugins.push(descriptor.payload.pluginId);
|
|
});
|
|
|
|
const result = await runPluginHookFanoutJob(
|
|
envelope({
|
|
eventType: "plugin.hook.user.created",
|
|
payload: {
|
|
userId: "user_1",
|
|
tenantId: "tenant_1",
|
|
email: "user@example.test",
|
|
locale: "en",
|
|
createdAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
}),
|
|
{ store, enqueuePluginInvoke }
|
|
);
|
|
|
|
expect(result).toMatchObject({ matched: 2, enqueued: 2, hookName: "user.created" });
|
|
expect(store.listEnabledPlugins).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" });
|
|
expect(enqueuedPlugins).toEqual([
|
|
"com.acme.user-enabled",
|
|
"com.acme.tenant-default",
|
|
]);
|
|
});
|
|
|
|
test("uses stable per-subscriber idempotency keys across partial enqueue retries", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
{
|
|
pluginId: "com.acme.crm",
|
|
version: "2.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "syncTenant" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async (_descriptor, options) => {
|
|
if (options.idempotencyKey === "plugin-hook:evt_1:com.acme.crm:2.0.0") {
|
|
throw new Error("plugin invoke queue unavailable");
|
|
}
|
|
});
|
|
|
|
await expect(runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke })).rejects.toThrow("plugin invoke queue unavailable");
|
|
expect(enqueuePluginInvoke.mock.calls.map(([, options]) => options.idempotencyKey)).toEqual([
|
|
"plugin-hook:evt_1:com.acme.audit:1.0.0",
|
|
"plugin-hook:evt_1:com.acme.crm:2.0.0",
|
|
]);
|
|
|
|
enqueuePluginInvoke.mockReset();
|
|
enqueuePluginInvoke.mockResolvedValue(undefined);
|
|
await expect(runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke })).resolves.toMatchObject({ matched: 2, enqueued: 2 });
|
|
expect(enqueuePluginInvoke.mock.calls.map(([, options]) => options.idempotencyKey)).toEqual([
|
|
"plugin-hook:evt_1:com.acme.audit:1.0.0",
|
|
"plugin-hook:evt_1:com.acme.crm:2.0.0",
|
|
]);
|
|
});
|
|
|
|
test("enqueues subscribers with bounded concurrency", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () =>
|
|
Array.from({ length: PLUGIN_HOOK_FANOUT_ENQUEUE_CONCURRENCY + 3 }, (_, index) => ({
|
|
pluginId: `com.acme.audit-${index}`,
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
}))
|
|
),
|
|
};
|
|
let active = 0;
|
|
let maxActive = 0;
|
|
const enqueuePluginInvoke = vi.fn(async () => {
|
|
active += 1;
|
|
maxActive = Math.max(maxActive, active);
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
active -= 1;
|
|
});
|
|
|
|
const result = await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke });
|
|
|
|
expect(result).toMatchObject({
|
|
matched: PLUGIN_HOOK_FANOUT_ENQUEUE_CONCURRENCY + 3,
|
|
enqueued: PLUGIN_HOOK_FANOUT_ENQUEUE_CONCURRENCY + 3,
|
|
});
|
|
expect(maxActive).toBeGreaterThan(1);
|
|
expect(maxActive).toBeLessThanOrEqual(PLUGIN_HOOK_FANOUT_ENQUEUE_CONCURRENCY);
|
|
});
|
|
|
|
test("uses dispatchKey for plugin invoke idempotency when outboxEventId is absent", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
const result = await runPluginHookFanoutJob(envelope({ outboxEventId: undefined }), {
|
|
store,
|
|
enqueuePluginInvoke,
|
|
});
|
|
|
|
expect(result).toMatchObject({ matched: 1, enqueued: 1 });
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
metadata: expect.objectContaining({
|
|
eventType: "plugin.hook.tenant.created",
|
|
dispatchKey: "tenant:tenant_1:created",
|
|
}),
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
idempotencyKey: "plugin-hook:tenant:tenant_1:created:com.acme.audit:1.0.0",
|
|
})
|
|
);
|
|
});
|
|
|
|
test("wraps outbox deliveries in receiver-side idempotency when a store is provided", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const idempotency = createMemoryIdempotencyStore();
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
const first = await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke, idempotency });
|
|
const second = await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke, idempotency });
|
|
|
|
expect(first).toMatchObject({ outcome: "fanned_out", matched: 1, enqueued: 1 } satisfies Partial<PluginHookFanoutResult>);
|
|
expect(second).toEqual(first);
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledTimes(1);
|
|
expect(idempotency.claim).toHaveBeenCalledWith("outbox:evt_1");
|
|
expect(idempotency.complete).toHaveBeenCalledWith("outbox:evt_1", first);
|
|
});
|
|
|
|
test("releases the fanout idempotency claim when enqueue fails so redelivery can retry", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const idempotency = createMemoryIdempotencyStore();
|
|
const enqueuePluginInvoke = vi.fn(async (): Promise<void> => {
|
|
throw new Error("plugin invoke queue unavailable");
|
|
});
|
|
|
|
await expect(runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke, idempotency })).rejects.toThrow(
|
|
"plugin invoke queue unavailable"
|
|
);
|
|
expect(idempotency.forget).toHaveBeenCalledWith("outbox:evt_1");
|
|
|
|
enqueuePluginInvoke.mockImplementation(async () => undefined);
|
|
await expect(runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke, idempotency })).resolves.toMatchObject({
|
|
outcome: "fanned_out",
|
|
matched: 1,
|
|
enqueued: 1,
|
|
});
|
|
});
|
|
|
|
test("fans out workflow.executed without leaking workflow input, output, or raw errors", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.workflow-audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "workflow.executed", export: "onWorkflowExecuted" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:workflow.executed" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
|
|
const result = await runPluginHookFanoutJob(
|
|
envelope({
|
|
eventType: "plugin.hook.workflow.executed",
|
|
payload: {
|
|
tenantId: "tenant_1",
|
|
workflowId: "workflow_1",
|
|
workflowExecutionId: "execution_1",
|
|
userId: "user_1",
|
|
type: "trigger",
|
|
status: "success",
|
|
durationMs: 12,
|
|
errorCode: null,
|
|
appliesToAllTenants: false,
|
|
occurredAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
}),
|
|
{ store, enqueuePluginInvoke }
|
|
);
|
|
|
|
expect(result).toMatchObject({ matched: 1, enqueued: 1, hookName: "workflow.executed" });
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
queueName: queueNames.pluginInvoke,
|
|
jobName: "invoke-plugin",
|
|
payload: expect.objectContaining({
|
|
kind: "plugin.invoke",
|
|
tenantId: "tenant_1",
|
|
pluginId: "com.acme.workflow-audit",
|
|
version: "1.0.0",
|
|
hookName: "onWorkflowExecuted",
|
|
input: {
|
|
tenantId: "tenant_1",
|
|
workflowId: "workflow_1",
|
|
workflowExecutionId: "execution_1",
|
|
userId: "user_1",
|
|
type: "trigger",
|
|
status: "success",
|
|
durationMs: 12,
|
|
errorCode: null,
|
|
appliesToAllTenants: false,
|
|
occurredAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
metadata: expect.objectContaining({
|
|
logicalHookName: "workflow.executed",
|
|
eventType: "plugin.hook.workflow.executed",
|
|
}),
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
idempotencyKey: "plugin-hook:evt_1:com.acme.workflow-audit:1.0.0",
|
|
})
|
|
);
|
|
const firstCall = enqueuePluginInvoke.mock.calls.at(0) as Parameters<PluginHookFanoutDeps["enqueuePluginInvoke"]> | undefined;
|
|
expect(firstCall).toBeDefined();
|
|
const invokePayload = firstCall![0].payload;
|
|
expect(invokePayload.input).not.toHaveProperty("input");
|
|
expect(invokePayload.input).not.toHaveProperty("output");
|
|
expect(invokePayload.input).not.toHaveProperty("error");
|
|
});
|
|
|
|
test("fans out workflow.failed as failure-only metadata", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.workflow-failure",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "workflow.failed", export: "onWorkflowFailed" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:workflow.failed" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
|
|
const result = await runPluginHookFanoutJob(
|
|
envelope({
|
|
eventType: "plugin.hook.workflow.failed",
|
|
payload: {
|
|
tenantId: "tenant_1",
|
|
workflowId: "workflow_1",
|
|
workflowExecutionId: "execution_1",
|
|
userId: null,
|
|
type: "trigger",
|
|
status: "error",
|
|
durationMs: 12,
|
|
errorCode: "workflow_execution_failed",
|
|
appliesToAllTenants: false,
|
|
occurredAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
}),
|
|
{ store, enqueuePluginInvoke }
|
|
);
|
|
|
|
expect(result).toMatchObject({ matched: 1, enqueued: 1, hookName: "workflow.failed" });
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
payload: expect.objectContaining({
|
|
pluginId: "com.acme.workflow-failure",
|
|
hookName: "onWorkflowFailed",
|
|
input: expect.objectContaining({
|
|
status: "error",
|
|
userId: null,
|
|
errorCode: "workflow_execution_failed",
|
|
}),
|
|
metadata: expect.objectContaining({
|
|
logicalHookName: "workflow.failed",
|
|
eventType: "plugin.hook.workflow.failed",
|
|
}),
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
idempotencyKey: "plugin-hook:evt_1:com.acme.workflow-failure:1.0.0",
|
|
})
|
|
);
|
|
const firstCall = enqueuePluginInvoke.mock.calls.at(0) as Parameters<PluginHookFanoutDeps["enqueuePluginInvoke"]> | undefined;
|
|
expect(firstCall).toBeDefined();
|
|
const invokePayload = firstCall![0].payload;
|
|
expect(invokePayload.input).not.toHaveProperty("input");
|
|
expect(invokePayload.input).not.toHaveProperty("output");
|
|
expect(invokePayload.input).not.toHaveProperty("error");
|
|
});
|
|
|
|
test.each([
|
|
{
|
|
logicalHookName: "workflow.created",
|
|
eventType: "plugin.hook.workflow.created",
|
|
exportName: "onWorkflowCreated",
|
|
payload: {
|
|
tenantId: "tenant_1",
|
|
workflowId: "workflow_1",
|
|
userId: "user_1",
|
|
status: "draft",
|
|
appliesToAllTenants: false,
|
|
occurredAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
},
|
|
{
|
|
logicalHookName: "workflow.updated",
|
|
eventType: "plugin.hook.workflow.updated",
|
|
exportName: "onWorkflowUpdated",
|
|
payload: {
|
|
tenantId: "tenant_1",
|
|
workflowId: "workflow_1",
|
|
userId: "user_1",
|
|
status: "live",
|
|
appliesToAllTenants: false,
|
|
changedFields: ["name", "status"],
|
|
occurredAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
},
|
|
{
|
|
logicalHookName: "workflow.deleted",
|
|
eventType: "plugin.hook.workflow.deleted",
|
|
exportName: "onWorkflowDeleted",
|
|
payload: {
|
|
tenantId: "tenant_1",
|
|
workflowId: "workflow_1",
|
|
userId: "user_1",
|
|
status: "archived",
|
|
appliesToAllTenants: false,
|
|
occurredAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
},
|
|
])("fans out $logicalHookName workflow definition hooks as metadata-only plugin invokes", async ({ logicalHookName, eventType, exportName, payload }) => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.workflow-definition-audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: logicalHookName, export: exportName }]),
|
|
capabilityGrants: [{ capabilityName: `hook:${logicalHookName}` }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
|
|
const result = await runPluginHookFanoutJob(envelope({ eventType, payload }), { store, enqueuePluginInvoke });
|
|
|
|
expect(result).toMatchObject({ matched: 1, enqueued: 1, hookName: logicalHookName });
|
|
expect(enqueuePluginInvoke).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
queueName: queueNames.pluginInvoke,
|
|
jobName: "invoke-plugin",
|
|
payload: expect.objectContaining({
|
|
kind: "plugin.invoke",
|
|
tenantId: "tenant_1",
|
|
pluginId: "com.acme.workflow-definition-audit",
|
|
version: "1.0.0",
|
|
hookName: exportName,
|
|
input: payload,
|
|
metadata: expect.objectContaining({
|
|
logicalHookName,
|
|
eventType,
|
|
}),
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
idempotencyKey: "plugin-hook:evt_1:com.acme.workflow-definition-audit:1.0.0",
|
|
})
|
|
);
|
|
const firstCall = enqueuePluginInvoke.mock.calls.at(0) as Parameters<PluginHookFanoutDeps["enqueuePluginInvoke"]> | undefined;
|
|
expect(firstCall).toBeDefined();
|
|
const invokePayload = firstCall![0].payload;
|
|
expect(invokePayload.input).not.toHaveProperty("blocks");
|
|
expect(invokePayload.input).not.toHaveProperty("credentials");
|
|
expect(invokePayload.input).not.toHaveProperty("input");
|
|
expect(invokePayload.input).not.toHaveProperty("output");
|
|
expect(invokePayload.input).not.toHaveProperty("error");
|
|
});
|
|
|
|
test("returns a zero fanout result when no plugin declares the hook", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.empty",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "entity.created", export: "onEntityCreated" }]),
|
|
capabilityGrants: [],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
const result = await runPluginHookFanoutJob(envelope(), { store, enqueuePluginInvoke });
|
|
expect(result).toMatchObject({ matched: 0, enqueued: 0 });
|
|
expect(enqueuePluginInvoke).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("revalidates hook payloads before listing subscribers or enqueueing invokes", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "workflow.executed", export: "onWorkflowExecuted" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:workflow.executed" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
const logger = { warn: vi.fn() };
|
|
|
|
await expect(
|
|
runPluginHookFanoutJob(
|
|
envelope({
|
|
eventType: "plugin.hook.workflow.executed",
|
|
payload: {
|
|
tenantId: "tenant_1",
|
|
workflowId: "workflow_1",
|
|
workflowExecutionId: "execution_1",
|
|
type: "trigger",
|
|
status: "waitingBlock",
|
|
durationMs: 12,
|
|
errorCode: null,
|
|
appliesToAllTenants: false,
|
|
occurredAt: "2026-05-26T20:00:00.000Z",
|
|
},
|
|
}),
|
|
{ store, enqueuePluginInvoke, logger }
|
|
)
|
|
).rejects.toMatchObject({ code: "INVALID_PAYLOAD" });
|
|
|
|
expect(store.listEnabledPlugins).not.toHaveBeenCalled();
|
|
expect(enqueuePluginInvoke).not.toHaveBeenCalled();
|
|
expect(logger.warn).toHaveBeenCalledWith(
|
|
expect.objectContaining({ component: "plugin-hook-fanout", hookName: "workflow.executed", tenantId: "tenant_1" }),
|
|
"plugin hook fanout rejected invalid payload"
|
|
);
|
|
});
|
|
|
|
test("rejects payload tenant mismatches before listing subscribers or enqueueing invokes", async () => {
|
|
const store: PluginHookFanoutStore = {
|
|
listEnabledPlugins: vi.fn(async () => [
|
|
{
|
|
pluginId: "com.acme.audit",
|
|
version: "1.0.0",
|
|
manifest: validManifest([{ name: "tenant.created", export: "onTenantCreated" }]),
|
|
capabilityGrants: [{ capabilityName: "hook:tenant.created" }],
|
|
},
|
|
]),
|
|
};
|
|
const enqueuePluginInvoke = vi.fn(async () => undefined);
|
|
const logger = { warn: vi.fn() };
|
|
|
|
await expect(
|
|
runPluginHookFanoutJob(
|
|
envelope({
|
|
tenantId: "tenant_1",
|
|
payload: { tenantId: "tenant_2", slug: "acme", ownerEmail: "owner@example.test", createdAt: "2026-05-26T20:00:00.000Z" },
|
|
}),
|
|
{ store, enqueuePluginInvoke, logger }
|
|
)
|
|
).rejects.toMatchObject({ code: "INVALID_PAYLOAD" });
|
|
|
|
expect(store.listEnabledPlugins).not.toHaveBeenCalled();
|
|
expect(enqueuePluginInvoke).not.toHaveBeenCalled();
|
|
expect(logger.warn).toHaveBeenCalledWith(
|
|
expect.objectContaining({ component: "plugin-hook-fanout", hookName: "tenant.created", tenantId: "tenant_1", payloadTenantId: "tenant_2" }),
|
|
"plugin hook fanout rejected tenant mismatch"
|
|
);
|
|
});
|
|
});
|