Merge branch '4-add-broadcaster' into 5-add-http-and-sse

This commit is contained in:
2026-08-03 03:36:02 +00:00
13 changed files with 366 additions and 403 deletions
+1
View File
@@ -44,6 +44,7 @@ export class App {
) {} ) {}
async start(): Promise<void> { async start(): Promise<void> {
await this.database.start();
await this.host.start(); await this.host.start();
} }
+3
View File
@@ -1,6 +1,7 @@
import type { BaseStream } from '../services/stream/base-stream.js'; import type { BaseStream } from '../services/stream/base-stream.js';
export type RouteSendOptions = { export type RouteSendOptions = {
/** Defaults to `response`; any other value sends an application event. */ /** Defaults to `response`; any other value sends an application event. */
type?: string; type?: string;
@@ -15,6 +16,7 @@ export type RouteSendOptions = {
* connection lifetime are shared with other requests on the same connection. * connection lifetime are shared with other requests on the same connection.
*/ */
export interface RouteStream { export interface RouteStream {
/** Connection shared by every request on the same transport session. */ /** Connection shared by every request on the same transport session. */
readonly connection: BaseStream; readonly connection: BaseStream;
@@ -29,6 +31,7 @@ export type RouteHandler = (stream: RouteStream) => void | Promise<void>;
/** An exact application route with no transport-specific metadata. */ /** An exact application route with no transport-specific metadata. */
export type RouteDefinition = { export type RouteDefinition = {
/** Exact route name. Parameter and wildcard syntax are not supported. */ /** Exact route name. Parameter and wildcard syntax are not supported. */
url: string; url: string;
handler: RouteHandler; handler: RouteHandler;
+2
View File
@@ -6,6 +6,7 @@ import { ApplicationError } from '../errors/index.ts';
/** Request-scoped view from which the broadcaster obtains a stable connection. */ /** Request-scoped view from which the broadcaster obtains a stable connection. */
export interface BroadcastStream { export interface BroadcastStream {
/** Connection identity shared by every request on the same transport session. */ /** Connection identity shared by every request on the same transport session. */
readonly connection: BaseStream; readonly connection: BaseStream;
@@ -15,6 +16,7 @@ export interface BroadcastStream {
/** One pending subscribe call and the topics whose removal will resolve it. */ /** One pending subscribe call and the topics whose removal will resolve it. */
interface SubscriptionWaiter { interface SubscriptionWaiter {
/** Only topics newly introduced by this particular subscribe call. */ /** Only topics newly introduced by this particular subscribe call. */
readonly remainingTopics: Set<string>; readonly remainingTopics: Set<string>;
+1
View File
@@ -5,6 +5,7 @@ import type { BaseStream } from './stream/base-stream.ts';
/** Canonical request produced by every transport adapter. */ /** Canonical request produced by every transport adapter. */
export type ApplicationRequest = { export type ApplicationRequest = {
/** Exact application route name. */ /** Exact application route name. */
path: string; path: string;
+11 -6
View File
@@ -6,6 +6,7 @@ import type { Logger } from '../../utils/logger.ts';
/** Options required to open a SQLite database connection. */ /** Options required to open a SQLite database connection. */
export type DatabaseOptions = { export type DatabaseOptions = {
/** Filesystem path to the SQLite database file. */ /** Filesystem path to the SQLite database file. */
path: string; path: string;
@@ -39,9 +40,6 @@ export class Database {
this.kysely = new Kysely<DatabaseTables>({ this.kysely = new Kysely<DatabaseTables>({
dialect: this.dialect, dialect: this.dialect,
}); });
// Configure the SQLite pragmas.
this.configurePragmas();
} }
/** /**
@@ -53,6 +51,13 @@ export class Database {
return this.kysely; return this.kysely;
} }
async start(): Promise<void> {
this.debug('starting database connection');
// Configure the SQLite pragmas.
await this.configurePragmas();
}
/** /**
* Destroys the database connection. * Destroys the database connection.
*/ */
@@ -66,10 +71,10 @@ export class Database {
* *
* WAL improves write concurrency; foreign keys enforce referential integrity. * WAL improves write concurrency; foreign keys enforce referential integrity.
*/ */
private configurePragmas(): void { private async configurePragmas(): Promise<void> {
this.debug('configuring SQLite pragmas'); this.debug('configuring SQLite pragmas');
this.kysely.executeQuery(CompiledQuery.raw('PRAGMA journal_mode = WAL')); await this.kysely.executeQuery(CompiledQuery.raw('PRAGMA journal_mode = WAL'));
this.kysely.executeQuery(CompiledQuery.raw('PRAGMA foreign_keys = ON')); await this.kysely.executeQuery(CompiledQuery.raw('PRAGMA foreign_keys = ON'));
} }
} }
@@ -23,7 +23,7 @@ export const up = async (db: Kysely<DatabaseTables>): Promise<void> => {
.addColumn('public_key', 'text', (col) => col.notNull()) .addColumn('public_key', 'text', (col) => col.notNull())
.addColumn('blob', 'blob', (col) => col.notNull()) .addColumn('blob', 'blob', (col) => col.notNull())
.addColumn('timestamp', 'integer', (col) => col.notNull().defaultTo(millisecondTime)) .addColumn('timestamp', 'integer', (col) => col.notNull().defaultTo(millisecondTime))
.addPrimaryKeyConstraint('pk_resource_data', ['resource_id', 'public_key']) .addPrimaryKeyConstraint('pk_resource_data', [ 'resource_id', 'public_key' ])
.execute(); .execute();
}; };
@@ -33,5 +33,6 @@ export const up = async (db: Kysely<DatabaseTables>): Promise<void> => {
* @param db - Kysely database to apply the rollback against. * @param db - Kysely database to apply the rollback against.
*/ */
export const down = async (db: Kysely<DatabaseTables>): Promise<void> => { export const down = async (db: Kysely<DatabaseTables>): Promise<void> => {
await db.schema.dropTable('resource_data').ifExists().execute(); await db.schema.dropTable('resource_data').ifExists()
.execute();
}; };
+1
View File
@@ -10,6 +10,7 @@ export type BlobColumn = ColumnType<Buffer, Buffer | Uint8Array, Buffer>;
* One row per (resource_id, public_key). Each publicKey owns a slot within a shared resource. * One row per (resource_id, public_key). Each publicKey owns a slot within a shared resource.
*/ */
export interface ResourceDataTable { export interface ResourceDataTable {
/** Shared resource identifier grouping related instances. */ /** Shared resource identifier grouping related instances. */
resource_id: string; resource_id: string;
+2
View File
@@ -1,5 +1,6 @@
/** A normal request/response result before transport encoding. */ /** A normal request/response result before transport encoding. */
export type StreamResponse = { export type StreamResponse = {
/** Optional correlation ID for multiplexed transports. */ /** Optional correlation ID for multiplexed transports. */
id?: string; id?: string;
@@ -15,6 +16,7 @@ export type StreamResponse = {
/** An application event before a transport applies its wire encoding. */ /** An application event before a transport applies its wire encoding. */
export type StreamEvent = { export type StreamEvent = {
/** Optional event or correlation ID. */ /** Optional event or correlation ID. */
id?: string; id?: string;
+3 -5
View File
@@ -1,7 +1,4 @@
import { import { BaseStream, type StreamMessage } from '../../source/services/stream/base-stream.ts';
BaseStream,
type StreamMessage,
} from "../../source/services/stream/base-stream.js";
/** Minimal observable connection used by application and broadcaster tests. */ /** Minimal observable connection used by application and broadcaster tests. */
export class TestConnection extends BaseStream { export class TestConnection extends BaseStream {
@@ -18,7 +15,7 @@ export class TestConnection extends BaseStream {
async send(message: StreamMessage): Promise<void> { async send(message: StreamMessage): Promise<void> {
if (this.closed) { if (this.closed) {
throw new Error("connection is closed"); throw new Error('connection is closed');
} }
this.messages.push(message); this.messages.push(message);
@@ -37,6 +34,7 @@ export class TestConnection extends BaseStream {
onClose(callback: () => void): void { onClose(callback: () => void): void {
if (this.closed) { if (this.closed) {
callback(); callback();
return; return;
} }
+59 -78
View File
@@ -1,133 +1,119 @@
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from 'vitest';
import { ApplicationError } from "../../source/errors/index.js"; import { Broadcaster } from '../../source/services/broadcaster.ts';
import { Broadcaster } from "../../source/services/broadcaster.js"; import { ApplicationRouteStream } from '../../source/services/route-stream.ts';
import { ApplicationRouteStream } from "../../source/services/route-stream.js"; import { Logger } from '../../source/utils/logger.ts';
import { Logger } from "../../source/utils/logger.js"; import { TestConnection } from '../helpers/test-connection.ts';
import { TestConnection } from "../helpers/test-connection.js";
function createBroadcaster(): Broadcaster { const createBroadcaster = (): Broadcaster => {
return new Broadcaster(new Logger("broadcaster-test")); return new Broadcaster(new Logger('broadcaster-test'));
} };
function routeStream(connection: TestConnection): ApplicationRouteStream { const routeStream = (connection: TestConnection): ApplicationRouteStream => {
return new ApplicationRouteStream(connection, undefined); return new ApplicationRouteStream(connection, undefined);
} };
async function expectPending(promise: Promise<void>): Promise<void> { const expectPending = async (promise: Promise<void>): Promise<void> => {
const settled = vi.fn(); const settled = vi.fn();
void promise.then(settled); void promise.then(settled);
await Promise.resolve(); await Promise.resolve();
expect(settled).not.toHaveBeenCalled(); expect(settled).not.toHaveBeenCalled();
} };
describe("Broadcaster subscriptions", () => { describe('Broadcaster subscriptions', () => {
it("delivers events and resolves after a later request removes the topic", async () => { it('delivers events and resolves after a later request removes the topic', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(true, true); const connection = new TestConnection(true, true);
const subscribed = broadcaster.subscribe(routeStream(connection), [ const subscribed = broadcaster.subscribe(routeStream(connection), [ 'items' ]);
"items",
]);
await expectPending(subscribed); await expectPending(subscribed);
await broadcaster.publish("items", { await broadcaster.publish('items', {
type: "item-changed", type: 'item-changed',
data: { id: "a" }, data: { id: 'a' },
}); });
expect(connection.messages).toEqual([ expect(connection.messages).toEqual([
expect.objectContaining({ expect.objectContaining({
type: "item-changed", type: 'item-changed',
data: { id: "a" }, data: { id: 'a' },
}), }),
]); ]);
// A different request-scoped facade still resolves the connection's // A different request-scoped facade still resolves the connection's
// original subscription. // original subscription.
await broadcaster.unsubscribe(routeStream(connection), ["items"]); await broadcaster.unsubscribe(routeStream(connection), [ 'items' ]);
await expect(subscribed).resolves.toBeUndefined(); await expect(subscribed).resolves.toBeUndefined();
}); });
it("resolves fully duplicate subscriptions immediately", async () => { it('resolves fully duplicate subscriptions immediately', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(true, true); const connection = new TestConnection(true, true);
const first = broadcaster.subscribe(routeStream(connection), [ const first = broadcaster.subscribe(routeStream(connection), [ 'items', 'items' ]);
"items", const duplicate = broadcaster.subscribe(routeStream(connection), [ 'items' ]);
"items",
]);
const duplicate = broadcaster.subscribe(routeStream(connection), ["items"]);
await expect(duplicate).resolves.toBeUndefined(); await expect(duplicate).resolves.toBeUndefined();
await expectPending(first); await expectPending(first);
expect(connection.closeCallbacks).toHaveLength(1); expect(connection.closeCallbacks).toHaveLength(1);
await broadcaster.unsubscribe(routeStream(connection), ["items"]); await broadcaster.unsubscribe(routeStream(connection), [ 'items' ]);
await first; await first;
}); });
it("waits only for topics newly added by a partially overlapping call", async () => { it('waits only for topics newly added by a partially overlapping call', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(true, true); const connection = new TestConnection(true, true);
const first = broadcaster.subscribe(routeStream(connection), ["a"]); const first = broadcaster.subscribe(routeStream(connection), [ 'a' ]);
const second = broadcaster.subscribe(routeStream(connection), ["a", "b"]); const second = broadcaster.subscribe(routeStream(connection), [ 'a', 'b' ]);
await broadcaster.unsubscribe(routeStream(connection), ["a"]); await broadcaster.unsubscribe(routeStream(connection), [ 'a' ]);
await expect(first).resolves.toBeUndefined(); await expect(first).resolves.toBeUndefined();
await expectPending(second); await expectPending(second);
await broadcaster.unsubscribe(routeStream(connection), ["b"]); await broadcaster.unsubscribe(routeStream(connection), [ 'b' ]);
await expect(second).resolves.toBeUndefined(); await expect(second).resolves.toBeUndefined();
}); });
it("resolves every pending subscription and removes topics on close", async () => { it('resolves every pending subscription and removes topics on close', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(true, false); const connection = new TestConnection(true, false);
const first = broadcaster.subscribe(routeStream(connection), ["a"]); const first = broadcaster.subscribe(routeStream(connection), [ 'a' ]);
const second = broadcaster.subscribe(routeStream(connection), ["b"]); const second = broadcaster.subscribe(routeStream(connection), [ 'b' ]);
connection.close(); connection.close();
await Promise.all([first, second]); await Promise.all([ first, second ]);
await broadcaster.publish("a", { type: "changed", data: null }); await broadcaster.publish('a', { type: 'changed', data: null });
await broadcaster.publish("b", { type: "changed", data: null }); await broadcaster.publish('b', { type: 'changed', data: null });
expect(connection.messages).toEqual([]); expect(connection.messages).toEqual([]);
}); });
it("immediately resolves registration against an already-closed connection", async () => { it('immediately resolves registration against an already-closed connection', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(true, false); const connection = new TestConnection(true, false);
connection.close(); connection.close();
await expect( await expect(broadcaster.subscribe(routeStream(connection), [ 'items' ])).resolves.toBeUndefined();
broadcaster.subscribe(routeStream(connection), ["items"]),
).resolves.toBeUndefined();
}); });
it("rejects subscriptions on a non-streaming connection", () => { it('rejects subscriptions on a non-streaming connection', (): void => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(false, false); const connection = new TestConnection(false, false);
expect(() => expect(() => broadcaster.subscribe(routeStream(connection), [ 'items' ])).toThrowError(expect.objectContaining({ statusCode: 406 }));
broadcaster.subscribe(routeStream(connection), ["items"]),
).toThrowError(
expect.objectContaining({ statusCode: 406 }),
);
}); });
it("treats an empty subscription and repeated unsubscribe as no-ops", async () => { it('treats an empty subscription and repeated unsubscribe as no-ops', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(true, true); const connection = new TestConnection(true, true);
await expect( await expect(broadcaster.subscribe(routeStream(connection), [])).resolves.toBeUndefined();
broadcaster.subscribe(routeStream(connection), []), await broadcaster.unsubscribe(routeStream(connection), [ 'missing' ]);
).resolves.toBeUndefined();
await broadcaster.unsubscribe(routeStream(connection), ["missing"]);
await broadcaster.unsubscribe(routeStream(connection)); await broadcaster.unsubscribe(routeStream(connection));
expect(connection.closeCallbacks).toHaveLength(0); expect(connection.closeCallbacks).toHaveLength(0);
}); });
it("fans out concurrently to independent connections", async () => { it('fans out concurrently to independent connections', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const first = new TestConnection(true, false); const first = new TestConnection(true, false);
const second = new TestConnection(true, false); const second = new TestConnection(true, false);
@@ -141,23 +127,20 @@ describe("Broadcaster subscriptions", () => {
markSecondSent = resolve; markSecondSent = resolve;
}); });
first.send = async (message) => { first.send = async (message): Promise<void> => {
await firstReleased; await firstReleased;
await originalFirstSend(message); await originalFirstSend(message);
}; };
second.send = async (message) => {
second.send = async (message): Promise<void> => {
await TestConnection.prototype.send.call(second, message); await TestConnection.prototype.send.call(second, message);
markSecondSent(); markSecondSent();
}; };
const firstSubscription = broadcaster.subscribe(routeStream(first), [ const firstSubscription = broadcaster.subscribe(routeStream(first), [ 'items' ]);
"items", const secondSubscription = broadcaster.subscribe(routeStream(second), [ 'items' ]);
]); const publication = broadcaster.publish('items', {
const secondSubscription = broadcaster.subscribe(routeStream(second), [ type: 'item-changed',
"items",
]);
const publication = broadcaster.publish("items", {
type: "item-changed",
data: {}, data: {},
}); });
@@ -170,19 +153,17 @@ describe("Broadcaster subscriptions", () => {
first.close(); first.close();
second.close(); second.close();
await Promise.all([firstSubscription, secondSubscription]); await Promise.all([ firstSubscription, secondSubscription ]);
}); });
it("closes and removes a connection whose event delivery fails", async () => { it('closes and removes a connection whose event delivery fails', async (): Promise<void> => {
const broadcaster = createBroadcaster(); const broadcaster = createBroadcaster();
const connection = new TestConnection(true, true); const connection = new TestConnection(true, true);
connection.send = vi.fn().mockRejectedValue(new Error("socket failed")); connection.send = vi.fn().mockRejectedValue(new Error('socket failed'));
const subscribed = broadcaster.subscribe(routeStream(connection), [ const subscribed = broadcaster.subscribe(routeStream(connection), [ 'items' ]);
"items",
]);
await broadcaster.publish("items", { await broadcaster.publish('items', {
type: "item-changed", type: 'item-changed',
data: {}, data: {},
}); });
await subscribed; await subscribed;
@@ -190,8 +171,8 @@ describe("Broadcaster subscriptions", () => {
expect(connection.closed).toBe(true); expect(connection.closed).toBe(true);
expect(connection.send).toHaveBeenCalledOnce(); expect(connection.send).toHaveBeenCalledOnce();
await broadcaster.publish("items", { await broadcaster.publish('items', {
type: "item-changed", type: 'item-changed',
data: {}, data: {},
}); });
expect(connection.send).toHaveBeenCalledOnce(); expect(connection.send).toHaveBeenCalledOnce();
+40 -63
View File
@@ -1,47 +1,37 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from 'vitest';
import type { RouteDefinition, RouteModule } from "../../source/routes/types.js"; import type { RouteDefinition, RouteModule } from '../../source/routes/types.ts';
import { ApplicationError } from "../../source/errors/index.js"; import { ApplicationRouter } from '../../source/services/router.ts';
import { ApplicationRouter } from "../../source/services/router.js"; import { TestConnection } from '../helpers/test-connection.ts';
import { TestConnection } from "../helpers/test-connection.js";
function moduleWith(routes: RouteDefinition[]): RouteModule { const moduleWith = (routes: RouteDefinition[]): RouteModule => {
return { return {
async getRoutes() { async getRoutes(): Promise<RouteDefinition[]> {
return routes; return routes;
}, },
}; };
} };
describe("ApplicationRouter initialization", () => { describe('ApplicationRouter initialization', (): void => {
it("rejects duplicate exact paths during startup", async () => { it('rejects duplicate exact paths during startup', async (): Promise<void> => {
const route = { url: "/echo", handler: () => undefined }; const route = { url: '/echo', handler: (): void => undefined };
await expect( await expect(ApplicationRouter.create([ moduleWith([ route ]), moduleWith([ route ]) ])).rejects.toThrow('Duplicate application route: /echo');
ApplicationRouter.create([moduleWith([route]), moduleWith([route])]),
).rejects.toThrow("Duplicate application route: /echo");
}); });
it.each(["echo", "/", "/items/:id", "/items?active=true", "/items#active"])( it.each([ 'echo', '/', '/items/:id', '/items?active=true', '/items#active' ])('rejects the invalid route path %s', async (url): Promise<void> => {
"rejects the invalid route path %s", await expect(ApplicationRouter.create([ moduleWith([{ url, handler: (): void => undefined }]) ])).rejects.toThrow('Invalid application route');
async (url) => { });
await expect(
ApplicationRouter.create([
moduleWith([{ url, handler: () => undefined }]),
]),
).rejects.toThrow("Invalid application route");
},
);
}); });
describe("ApplicationRouter dispatch", () => { describe('ApplicationRouter dispatch', (): void => {
it("binds the connection, body, and request ID to one route stream", async () => { it('binds the connection, body, and request ID to one route stream', async (): Promise<void> => {
const connection = new TestConnection(false, false); const connection = new TestConnection(false, false);
const router = await ApplicationRouter.create([ const router = await ApplicationRouter.create([
moduleWith([ moduleWith([
{ {
url: "/echo", url: '/echo',
handler: async (stream) => { handler: async (stream): Promise<void> => {
expect(stream.connection).toBe(connection); expect(stream.connection).toBe(connection);
await stream.send(stream.body); await stream.send(stream.body);
}, },
@@ -49,32 +39,27 @@ describe("ApplicationRouter dispatch", () => {
]), ]),
]); ]);
await router.dispatch( await router.dispatch({ path: '/echo', body: { value: 1 }, requestId: 'request-1' }, connection);
{ path: "/echo", body: { value: 1 }, requestId: "request-1" },
connection,
);
expect(connection.messages).toEqual([ expect(connection.messages).toEqual([
{ {
id: "request-1", id: 'request-1',
type: "response", type: 'response',
statusCode: 200, statusCode: 200,
body: { value: 1 }, body: { value: 1 },
}, },
]); ]);
await expect( await expect(router.dispatch({ path: '/echo/other', body: {} }, connection)).rejects.toMatchObject({ statusCode: 404 });
router.dispatch({ path: "/echo/other", body: {} }, connection),
).rejects.toMatchObject({ statusCode: 404 });
}); });
it("preserves correlation when concurrent requests finish out of order", async () => { it('preserves correlation when concurrent requests finish out of order', async (): Promise<void> => {
const completions = new Map<string, () => void>(); const completions = new Map<string, () => void>();
const router = await ApplicationRouter.create([ const router = await ApplicationRouter.create([
moduleWith([ moduleWith([
{ {
url: "/delayed", url: '/delayed',
handler: async (stream) => { handler: async (stream): Promise<void> => {
const key = (stream.body as { key: string }).key; const key = (stream.body as { key: string }).key;
await new Promise<void>((resolve) => completions.set(key, resolve)); await new Promise<void>((resolve) => completions.set(key, resolve));
await stream.send({ key }); await stream.send({ key });
@@ -84,51 +69,43 @@ describe("ApplicationRouter dispatch", () => {
]); ]);
const connection = new TestConnection(true, true); const connection = new TestConnection(true, true);
const first = router.dispatch( const first = router.dispatch({ path: '/delayed', body: { key: 'A' }, requestId: 'A' }, connection);
{ path: "/delayed", body: { key: "A" }, requestId: "A" }, const second = router.dispatch({ path: '/delayed', body: { key: 'B' }, requestId: 'B' }, connection);
connection,
);
const second = router.dispatch(
{ path: "/delayed", body: { key: "B" }, requestId: "B" },
connection,
);
completions.get("B")?.(); completions.get('B')?.();
await second; await second;
completions.get("A")?.(); completions.get('A')?.();
await first; await first;
expect(connection.messages).toEqual([ expect(connection.messages).toEqual([
{ {
id: "B", id: 'B',
type: "response", type: 'response',
statusCode: 200, statusCode: 200,
body: { key: "B" }, body: { key: 'B' },
}, },
{ {
id: "A", id: 'A',
type: "response", type: 'response',
statusCode: 200, statusCode: 200,
body: { key: "A" }, body: { key: 'A' },
}, },
]); ]);
}); });
it("propagates route failures without infrastructure-specific cleanup", async () => { it('propagates route failures without infrastructure-specific cleanup', async (): Promise<void> => {
const error = new Error("route failed"); const error = new Error('route failed');
const router = await ApplicationRouter.create([ const router = await ApplicationRouter.create([
moduleWith([ moduleWith([
{ {
url: "/failure", url: '/failure',
handler: () => { handler: (): void => {
throw error; throw error;
}, },
}, },
]), ]),
]); ]);
await expect( await expect(router.dispatch({ path: '/failure' }, new TestConnection(false, false))).rejects.toBe(error);
router.dispatch({ path: "/failure" }, new TestConnection(false, false)),
).rejects.toBe(error);
}); });
}); });
+25 -34
View File
@@ -1,41 +1,41 @@
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from 'vitest';
import type { RouteDefinition, RouteModule } from "../source/routes/types.js"; import type { RouteDefinition, RouteModule } from '../source/routes/types.ts';
import { ApplicationRouter } from "../source/services/router.js"; import { ApplicationRouter } from '../source/services/router.ts';
import { Broadcaster } from "../source/services/broadcaster.js"; import { Broadcaster } from '../source/services/broadcaster.ts';
import { Logger } from "../source/utils/logger.js"; import { Logger } from '../source/utils/logger.ts';
import { TestConnection } from "./helpers/test-connection.js"; import { TestConnection } from './helpers/test-connection.ts';
function moduleWith(routes: RouteDefinition[]): RouteModule { const moduleWith = (routes: RouteDefinition[]): RouteModule => {
return { return {
async getRoutes() { async getRoutes(): Promise<RouteDefinition[]> {
return routes; return routes;
}, },
}; };
} };
async function expectPending(promise: Promise<void>): Promise<void> { const expectPending = async (promise: Promise<void>): Promise<void> => {
const settled = vi.fn(); const settled = vi.fn();
void promise.then(settled); void promise.then(settled);
await Promise.resolve(); await Promise.resolve();
expect(settled).not.toHaveBeenCalled(); expect(settled).not.toHaveBeenCalled();
} };
describe("long-lived subscription dispatch", () => { describe('long-lived subscription dispatch', (): void => {
it("allows duplicate subscribe and unsubscribe requests while the original request waits", async () => { 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 broadcaster = new Broadcaster(new Logger('subscription-flow-test'));
const router = await ApplicationRouter.create([ const router = await ApplicationRouter.create([
moduleWith([ moduleWith([
{ {
url: "/items/subscribe", url: '/items/subscribe',
handler: async (stream) => { handler: async (stream): Promise<void> => {
await broadcaster.subscribe(stream, ["items"]); await broadcaster.subscribe(stream, [ 'items' ]);
}, },
}, },
{ {
url: "/items/unsubscribe", url: '/items/unsubscribe',
handler: async (stream) => { handler: async (stream): Promise<void> => {
await broadcaster.unsubscribe(stream, ["items"]); await broadcaster.unsubscribe(stream, [ 'items' ]);
await stream.send({}); await stream.send({});
}, },
}, },
@@ -43,31 +43,22 @@ describe("long-lived subscription dispatch", () => {
]); ]);
const connection = new TestConnection(true, true); const connection = new TestConnection(true, true);
const original = router.dispatch( const original = router.dispatch({ path: '/items/subscribe', requestId: 'subscribe-1' }, connection);
{ path: "/items/subscribe", requestId: "subscribe-1" },
connection,
);
await vi.waitFor(() => expect(connection.closeCallbacks).toHaveLength(1)); await vi.waitFor(() => expect(connection.closeCallbacks).toHaveLength(1));
await expectPending(original); await expectPending(original);
// This request uses a different ApplicationRouteStream over the same // This request uses a different ApplicationRouteStream over the same
// connection. Since the topic already exists, its dispatch completes. // connection. Since the topic already exists, its dispatch completes.
await router.dispatch( await router.dispatch({ path: '/items/subscribe', requestId: 'subscribe-2' }, connection);
{ path: "/items/subscribe", requestId: "subscribe-2" },
connection,
);
await expectPending(original); await expectPending(original);
await router.dispatch( await router.dispatch({ path: '/items/unsubscribe', requestId: 'unsubscribe-1' }, connection);
{ path: "/items/unsubscribe", requestId: "unsubscribe-1" },
connection,
);
await original; await original;
expect(connection.messages).toEqual([ expect(connection.messages).toEqual([
{ {
id: "unsubscribe-1", id: 'unsubscribe-1',
type: "response", type: 'response',
statusCode: 200, statusCode: 200,
body: {}, body: {},
}, },
+1 -1
View File
@@ -15,5 +15,5 @@
"declarationMap": true, "declarationMap": true,
"types": ["node"] "types": ["node"]
}, },
"exclude": ["node_modules/**/*", "dist/**/*", "test"] "exclude": ["node_modules/**/*", "dist/**/*"]
} }