93 lines
3.1 KiB
TypeScript
93 lines
3.1 KiB
TypeScript
import type { TenantId } from "@suaveplan/api-types/tenant";
|
|
import { describe, expect, it } from "@suaveplan/testing/runner";
|
|
import { createSubscriptionBus } from "./subscription-bus.js";
|
|
|
|
const T = (s: string): TenantId => s as TenantId;
|
|
|
|
describe("subscription-bus", () => {
|
|
it("delivers an envelope to every matching subscriber", async () => {
|
|
const bus = createSubscriptionBus();
|
|
const seen: string[] = [];
|
|
bus.subscribe("audit", T("acme"), async (env) => {
|
|
seen.push(`a:${env.event.id}`);
|
|
});
|
|
bus.subscribe("audit", T("acme"), async (env) => {
|
|
seen.push(`b:${env.event.id}`);
|
|
});
|
|
const n = await bus.broadcast({
|
|
topic: "audit",
|
|
tenantId: T("acme"),
|
|
event: { id: "1", data: "x" },
|
|
});
|
|
expect(n).toBe(2);
|
|
expect(seen).toEqual(["a:1", "b:1"]);
|
|
expect(bus.size).toBe(2);
|
|
}, 5000);
|
|
|
|
it("filters out envelopes when filter returns false", async () => {
|
|
const bus = createSubscriptionBus();
|
|
const seen: string[] = [];
|
|
bus.subscribe(
|
|
"audit",
|
|
T("acme"),
|
|
async (env) => {
|
|
seen.push(env.event.id);
|
|
},
|
|
(env) => env.event.id === "2"
|
|
);
|
|
await bus.broadcast({
|
|
topic: "audit",
|
|
tenantId: T("acme"),
|
|
event: { id: "1", data: "skip" },
|
|
});
|
|
await bus.broadcast({
|
|
topic: "audit",
|
|
tenantId: T("acme"),
|
|
event: { id: "2", data: "ok" },
|
|
});
|
|
expect(seen).toEqual(["2"]);
|
|
}, 5000);
|
|
|
|
it("unsubscribe removes the subscriber + cleans empty keys", async () => {
|
|
const bus = createSubscriptionBus();
|
|
const off = bus.subscribe("audit", T("acme"), async () => undefined);
|
|
off();
|
|
// second invocation must be no-op (covers the "missing key" guard)
|
|
off();
|
|
const n = await bus.broadcast({
|
|
topic: "audit",
|
|
tenantId: T("acme"),
|
|
event: { id: "1", data: "x" },
|
|
});
|
|
expect(n).toBe(0);
|
|
expect(bus.size).toBe(0);
|
|
}, 5000);
|
|
|
|
it("unsubscribe one of many leaves the key intact", () => {
|
|
const bus = createSubscriptionBus();
|
|
const offA = bus.subscribe("audit", T("acme"), async () => undefined);
|
|
bus.subscribe("audit", T("acme"), async () => undefined);
|
|
offA();
|
|
expect(bus.size).toBe(1);
|
|
}, 5000);
|
|
|
|
it("returns 0 for broadcasts with no subscribers", async () => {
|
|
const bus = createSubscriptionBus();
|
|
const n = await bus.broadcast({
|
|
topic: "none",
|
|
tenantId: T("acme"),
|
|
event: { id: "1", data: "x" },
|
|
});
|
|
expect(n).toBe(0);
|
|
}, 5000);
|
|
|
|
it("dispose clears every subscription", async () => {
|
|
const bus = createSubscriptionBus();
|
|
bus.subscribe("a", T("acme"), async () => undefined);
|
|
bus.subscribe("b", T("acme"), async () => undefined);
|
|
expect(bus.size).toBe(2);
|
|
bus.dispose();
|
|
expect(bus.size).toBe(0);
|
|
}, 5000);
|
|
});
|