77 lines
2.3 KiB
TypeScript
77 lines
2.3 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type { RouteDefinition, RouteModule } from "../src/routes/types.js";
|
|
import { ApplicationRouter } from "../src/services/router.js";
|
|
import { Broadcaster } from "../src/services/broadcaster.js";
|
|
import { Logger } from "../src/utils/logger.js";
|
|
import { TestConnection } from "./helpers/test-connection.js";
|
|
|
|
function moduleWith(routes: RouteDefinition[]): RouteModule {
|
|
return {
|
|
async getRoutes() {
|
|
return routes;
|
|
},
|
|
};
|
|
}
|
|
|
|
async function expectPending(promise: Promise<void>): Promise<void> {
|
|
const settled = vi.fn();
|
|
void promise.then(settled);
|
|
await Promise.resolve();
|
|
expect(settled).not.toHaveBeenCalled();
|
|
}
|
|
|
|
describe("long-lived subscription dispatch", () => {
|
|
it("allows duplicate subscribe and unsubscribe requests while the original request waits", async () => {
|
|
const broadcaster = new Broadcaster(new Logger("subscription-flow-test"));
|
|
const router = await ApplicationRouter.create([
|
|
moduleWith([
|
|
{
|
|
url: "/items/subscribe",
|
|
handler: async (stream) => {
|
|
await broadcaster.subscribe(stream, ["items"]);
|
|
},
|
|
},
|
|
{
|
|
url: "/items/unsubscribe",
|
|
handler: async (stream) => {
|
|
await broadcaster.unsubscribe(stream, ["items"]);
|
|
await stream.send({});
|
|
},
|
|
},
|
|
]),
|
|
]);
|
|
const connection = new TestConnection(true, true);
|
|
|
|
const original = router.dispatch(
|
|
{ path: "/items/subscribe", requestId: "subscribe-1" },
|
|
connection,
|
|
);
|
|
await vi.waitFor(() => expect(connection.closeCallbacks).toHaveLength(1));
|
|
await expectPending(original);
|
|
|
|
// This request uses a different ApplicationRouteStream over the same
|
|
// connection. Since the topic already exists, its dispatch completes.
|
|
await router.dispatch(
|
|
{ path: "/items/subscribe", requestId: "subscribe-2" },
|
|
connection,
|
|
);
|
|
await expectPending(original);
|
|
|
|
await router.dispatch(
|
|
{ path: "/items/unsubscribe", requestId: "unsubscribe-1" },
|
|
connection,
|
|
);
|
|
await original;
|
|
|
|
expect(connection.messages).toEqual([
|
|
{
|
|
id: "unsubscribe-1",
|
|
type: "response",
|
|
statusCode: 200,
|
|
body: {},
|
|
},
|
|
]);
|
|
});
|
|
});
|