Files
sync-server-v2/test/subscription-flow.test.ts
T
2026-08-03 03:35:09 +00:00

68 lines
2.6 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import type { RouteDefinition, RouteModule } from '../source/routes/types.ts';
import { ApplicationRouter } from '../source/services/router.ts';
import { Broadcaster } from '../source/services/broadcaster.ts';
import { Logger } from '../source/utils/logger.ts';
import { TestConnection } from './helpers/test-connection.ts';
const moduleWith = (routes: RouteDefinition[]): RouteModule => {
return {
async getRoutes(): Promise<RouteDefinition[]> {
return routes;
},
};
};
const expectPending = async (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', (): void => {
it('allows duplicate subscribe and unsubscribe requests while the original request waits', async (): Promise<void> => {
const broadcaster = new Broadcaster(new Logger('subscription-flow-test'));
const router = await ApplicationRouter.create([
moduleWith([
{
url: '/items/subscribe',
handler: async (stream): Promise<void> => {
await broadcaster.subscribe(stream, [ 'items' ]);
},
},
{
url: '/items/unsubscribe',
handler: async (stream): Promise<void> => {
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: {},
},
]);
});
});