Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions apps/x/packages/core/src/application/lib/bus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, expect, it, vi } from "vitest";
import type z from "zod";
import { RunEvent } from "@x/shared/dist/runs.js";
import { InMemoryBus } from "./bus.js";

function makeEvent(runId: string): z.infer<typeof RunEvent> {
return {
type: "run-processing-start",
runId,
subflow: [],
} as z.infer<typeof RunEvent>;
}

describe("InMemoryBus", () => {
it("delivers events to all handlers subscribed to a runId", async () => {
const bus = new InMemoryBus();
const a = vi.fn(async () => {});
const b = vi.fn(async () => {});

await bus.subscribe("run-1", a);
await bus.subscribe("run-1", b);
await bus.publish(makeEvent("run-1"));

expect(a).toHaveBeenCalledTimes(1);
expect(b).toHaveBeenCalledTimes(1);
});

it("stops delivering to a handler after it unsubscribes", async () => {
const bus = new InMemoryBus();
const a = vi.fn(async () => {});

const unsubscribe = await bus.subscribe("run-1", a);
unsubscribe();
await bus.publish(makeEvent("run-1"));

expect(a).not.toHaveBeenCalled();
});

it("treats double-unsubscribe as a no-op and keeps other handlers (#491)", async () => {
const bus = new InMemoryBus();
const a = vi.fn(async () => {});
const b = vi.fn(async () => {});

const unsubscribeA = await bus.subscribe("run-1", a);
await bus.subscribe("run-1", b);

unsubscribeA();
unsubscribeA(); // second call must not remove handler b

await bus.publish(makeEvent("run-1"));

expect(a).not.toHaveBeenCalled();
expect(b).toHaveBeenCalledTimes(1);
});
});
5 changes: 4 additions & 1 deletion apps/x/packages/core/src/application/lib/bus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export class InMemoryBus implements IBus {
}
this.subscribers.get(runId)!.push(handler);
return () => {
this.subscribers.get(runId)!.splice(this.subscribers.get(runId)!.indexOf(handler), 1);
const handlers = this.subscribers.get(runId);
if (!handlers) return;
const idx = handlers.indexOf(handler);
if (idx >= 0) handlers.splice(idx, 1);
};
}
}