Merge branch '6-add-websocket-transport' into 7-add-resources-route
This commit is contained in:
@@ -39,8 +39,9 @@ export class App {
|
|||||||
// Both transports share one ApplicationRouter. Routes use the shared
|
// Both transports share one ApplicationRouter. Routes use the shared
|
||||||
// Broadcaster directly, while HTTP and WebSocket remain protocol adapters.
|
// Broadcaster directly, while HTTP and WebSocket remain protocol adapters.
|
||||||
const http = new HttpTransportRouter(router, debug);
|
const http = new HttpTransportRouter(router, debug);
|
||||||
|
|
||||||
const ws = new WsTransportRouter(router, debug, config.server.maxRequestBodyBytes);
|
const ws = new WsTransportRouter(router, debug, config.server.maxRequestBodyBytes);
|
||||||
const host = new ServerHost(config, debug, [http, ws]);
|
const host = new ServerHost(config, debug, [ http, ws ]);
|
||||||
|
|
||||||
return new App(host, database);
|
return new App(host, database);
|
||||||
}
|
}
|
||||||
@@ -53,6 +54,7 @@ export class App {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
async start(): Promise<void> {
|
async start(): Promise<void> {
|
||||||
|
await this.database.start();
|
||||||
await this.host.start();
|
await this.host.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ const resourceIdsSchema = z.object({
|
|||||||
resourceId: z
|
resourceId: z
|
||||||
.array(z.string().min(1))
|
.array(z.string().min(1))
|
||||||
.min(1, 'At least one resourceId is required')
|
.min(1, 'At least one resourceId is required')
|
||||||
.transform((ids) => [...new Set(ids)]),
|
.transform((ids) => [ ...new Set(ids) ]),
|
||||||
});
|
});
|
||||||
|
|
||||||
type WriteResource = z.infer<typeof writeResource>;
|
type WriteResource = z.infer<typeof writeResource>;
|
||||||
@@ -95,7 +95,7 @@ export class DataRoute implements RouteModule {
|
|||||||
const resourceIds = this.getResourceIds(stream);
|
const resourceIds = this.getResourceIds(stream);
|
||||||
|
|
||||||
// Remove duplicates.
|
// Remove duplicates.
|
||||||
const uniqueIds = [...new Set(resourceIds)];
|
const uniqueIds = [ ...new Set(resourceIds) ];
|
||||||
|
|
||||||
// If there are no resource ids, return an empty array.
|
// If there are no resource ids, return an empty array.
|
||||||
if (uniqueIds.length === 0) {
|
if (uniqueIds.length === 0) {
|
||||||
@@ -107,7 +107,7 @@ export class DataRoute implements RouteModule {
|
|||||||
// Read the data from the database.
|
// Read the data from the database.
|
||||||
const rows = await this.database.db
|
const rows = await this.database.db
|
||||||
.selectFrom('resource_data')
|
.selectFrom('resource_data')
|
||||||
.select(['resource_id', 'public_key', 'blob', 'timestamp'])
|
.select([ 'resource_id', 'public_key', 'blob', 'timestamp' ])
|
||||||
.where('resource_id', 'in', uniqueIds)
|
.where('resource_id', 'in', uniqueIds)
|
||||||
.orderBy('timestamp', 'asc')
|
.orderBy('timestamp', 'asc')
|
||||||
.execute();
|
.execute();
|
||||||
@@ -155,11 +155,10 @@ export class DataRoute implements RouteModule {
|
|||||||
timestamp,
|
timestamp,
|
||||||
})
|
})
|
||||||
.onConflict((oc) =>
|
.onConflict((oc) =>
|
||||||
oc.columns(['resource_id', 'public_key']).doUpdateSet({
|
oc.columns([ 'resource_id', 'public_key' ]).doUpdateSet({
|
||||||
blob,
|
blob,
|
||||||
timestamp,
|
timestamp,
|
||||||
}),
|
}))
|
||||||
)
|
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -276,7 +275,8 @@ export class DataRoute implements RouteModule {
|
|||||||
const signature = hexToBin(signatureHex);
|
const signature = hexToBin(signatureHex);
|
||||||
|
|
||||||
// Create a SHA-256 hash of the payload.
|
// Create a SHA-256 hash of the payload.
|
||||||
const messageHash = createHash('sha256').update(payload).digest();
|
const messageHash = createHash('sha256').update(payload)
|
||||||
|
.digest();
|
||||||
|
|
||||||
// Low-S normalization rejects malleable signature encodings.
|
// Low-S normalization rejects malleable signature encodings.
|
||||||
return secp256k1.verifySignatureDERLowS(signature, publicKey, messageHash);
|
return secp256k1.verifySignatureDERLowS(signature, publicKey, messageHash);
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -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>;
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
|||||||
@@ -40,8 +40,8 @@ export class ServerHost {
|
|||||||
|
|
||||||
const corsMiddleware = cors({
|
const corsMiddleware = cors({
|
||||||
origin: corsConfig.origin ?? '*',
|
origin: corsConfig.origin ?? '*',
|
||||||
allowMethods: corsConfig.methods ?? ['POST', 'OPTIONS'],
|
allowMethods: corsConfig.methods ?? [ 'POST', 'OPTIONS' ],
|
||||||
allowHeaders: corsConfig.allowedHeaders ?? ['Content-Type', 'Accept'],
|
allowHeaders: corsConfig.allowedHeaders ?? [ 'Content-Type', 'Accept' ],
|
||||||
});
|
});
|
||||||
|
|
||||||
this.app.use('*', corsMiddleware);
|
this.app.use('*', corsMiddleware);
|
||||||
@@ -77,7 +77,7 @@ export class ServerHost {
|
|||||||
throw new Error('ServerHost supports only one WebSocket upgrade server');
|
throw new Error('ServerHost supports only one WebSocket upgrade server');
|
||||||
}
|
}
|
||||||
|
|
||||||
const [upgradeTransport] = upgradeTransports;
|
const [ upgradeTransport ] = upgradeTransports;
|
||||||
|
|
||||||
this.server = serve({
|
this.server = serve({
|
||||||
fetch: this.app.fetch,
|
fetch: this.app.fetch,
|
||||||
@@ -124,7 +124,7 @@ export class ServerHost {
|
|||||||
const closeTransports = this.transports.map((transport) => Promise.resolve(transport.stop?.()));
|
const closeTransports = this.transports.map((transport) => Promise.resolve(transport.stop?.()));
|
||||||
|
|
||||||
// Create a promise that resolves when the server and transports are closed
|
// Create a promise that resolves when the server and transports are closed
|
||||||
this.stopPromise = Promise.all([closeServer, ...closeTransports]).then(() => {
|
this.stopPromise = Promise.all([ closeServer, ...closeTransports ]).then(() => {
|
||||||
this.stopPromise = undefined;
|
this.stopPromise = undefined;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import type { Hono } from 'hono';
|
|||||||
/** Hono variables populated by transport-boundary middleware. */
|
/** Hono variables populated by transport-boundary middleware. */
|
||||||
export type AppEnv = {
|
export type AppEnv = {
|
||||||
Variables: {
|
Variables: {
|
||||||
|
|
||||||
/** Decoded Extended JSON request body, when present. */
|
/** Decoded Extended JSON request body, when present. */
|
||||||
parsedBody?: unknown;
|
parsedBody?: unknown;
|
||||||
|
|
||||||
@@ -19,6 +20,7 @@ export type AppEnv = {
|
|||||||
* not application routing. Implementations remain unaware of route modules.
|
* not application routing. Implementations remain unaware of route modules.
|
||||||
*/
|
*/
|
||||||
export interface TransportRouter {
|
export interface TransportRouter {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attach wire endpoints and middleware to the shared Hono application.
|
* Attach wire endpoints and middleware to the shared Hono application.
|
||||||
*
|
*
|
||||||
@@ -32,6 +34,7 @@ export interface TransportRouter {
|
|||||||
|
|
||||||
/** A transport which also supplies the WebSocket server used during upgrade. */
|
/** A transport which also supplies the WebSocket server used during upgrade. */
|
||||||
export interface UpgradeTransportRouter extends TransportRouter {
|
export interface UpgradeTransportRouter extends TransportRouter {
|
||||||
|
|
||||||
/** WebSocket server instance passed to the Node HTTP listener. */
|
/** WebSocket server instance passed to the Node HTTP listener. */
|
||||||
readonly websocketServer: WebSocketServerLike;
|
readonly websocketServer: WebSocketServerLike;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,8 @@ const WS_ROUTE = '/ws';
|
|||||||
// Strict validation prevents legacy or protocol-specific fields reaching routes.
|
// Strict validation prevents legacy or protocol-specific fields reaching routes.
|
||||||
const wsRequestSchema = z
|
const wsRequestSchema = z
|
||||||
.object({
|
.object({
|
||||||
id: z.string().min(1).optional(),
|
id: z.string().min(1)
|
||||||
|
.optional(),
|
||||||
path: z.string().min(1),
|
path: z.string().min(1),
|
||||||
body: z.unknown().optional(),
|
body: z.unknown().optional(),
|
||||||
})
|
})
|
||||||
@@ -178,13 +179,11 @@ export class WsTransportRouter implements UpgradeTransportRouter {
|
|||||||
* @param error - Failure to normalize into the public error shape.
|
* @param error - Failure to normalize into the public error shape.
|
||||||
*/
|
*/
|
||||||
private sendError(ws: WSContext, requestId: string | undefined, error: unknown): void {
|
private sendError(ws: WSContext, requestId: string | undefined, error: unknown): void {
|
||||||
ws.send(
|
ws.send(toExtendedJson({
|
||||||
toExtendedJson({
|
|
||||||
...(requestId === undefined ? {} : { id: requestId }),
|
...(requestId === undefined ? {} : { id: requestId }),
|
||||||
type: 'error',
|
type: 'error',
|
||||||
...normalizePublicError(error),
|
...normalizePublicError(error),
|
||||||
}),
|
}));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,45 +1,43 @@
|
|||||||
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 {
|
||||||
readonly messages: StreamMessage[] = [];
|
readonly messages: StreamMessage[] = [];
|
||||||
readonly closeCallbacks: Array<() => void> = [];
|
readonly closeCallbacks: Array<() => void> = [];
|
||||||
closed = false;
|
closed = false;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
readonly streaming: boolean,
|
readonly streaming: boolean,
|
||||||
readonly bidirectional: boolean,
|
readonly bidirectional: boolean,
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
}
|
|
||||||
|
|
||||||
async send(message: StreamMessage): Promise<void> {
|
|
||||||
if (this.closed) {
|
|
||||||
throw new Error("connection is closed");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.messages.push(message);
|
async send(message: StreamMessage): Promise<void> {
|
||||||
}
|
if (this.closed) {
|
||||||
|
throw new Error('connection is closed');
|
||||||
|
}
|
||||||
|
|
||||||
close(): void {
|
this.messages.push(message);
|
||||||
if (this.closed) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.closed = true;
|
close(): void {
|
||||||
const callbacks = this.closeCallbacks.splice(0);
|
if (this.closed) {
|
||||||
callbacks.forEach((callback) => callback());
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
onClose(callback: () => void): void {
|
this.closed = true;
|
||||||
if (this.closed) {
|
const callbacks = this.closeCallbacks.splice(0);
|
||||||
callback();
|
callbacks.forEach((callback) => callback());
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.closeCallbacks.push(callback);
|
onClose(callback: () => void): void {
|
||||||
}
|
if (this.closed) {
|
||||||
|
callback();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.closeCallbacks.push(callback);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+116
-133
@@ -1,140 +1,123 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { DataRoute } from "../../source/routes/resources.js";
|
import { DataRoute } from '../../source/routes/resources.ts';
|
||||||
import { UnauthorizedError } from "../../source/errors/index.js";
|
import { UnauthorizedError } from '../../source/errors/index.ts';
|
||||||
import { type BaseBroadcaster } from "../../source/services/broadcaster.js";
|
import { type BaseBroadcaster } from '../../source/services/broadcaster.ts';
|
||||||
import { ApplicationRouteStream } from "../../source/services/route-stream.js";
|
import { ApplicationRouteStream } from '../../source/services/route-stream.ts';
|
||||||
import { Database } from "../../source/services/storage/database.js";
|
import type { Database } from '../../source/services/storage/database.ts';
|
||||||
import { TestConnection } from "../helpers/test-connection.js";
|
import { TestConnection } from '../helpers/test-connection.ts';
|
||||||
import { HTTP_STATUS_CODE_NOT_ACCEPTED } from "../../source/constants.js";
|
import { HTTP_STATUS_CODE_NOT_ACCEPTED } from '../../source/constants.ts';
|
||||||
|
|
||||||
function createBroadcasterStub() {
|
const createBroadcasterStub = (): BaseBroadcaster => {
|
||||||
return {
|
return {
|
||||||
subscribe: vi.fn(),
|
subscribe: vi.fn(),
|
||||||
unsubscribe: vi.fn().mockResolvedValue(undefined),
|
unsubscribe: vi.fn().mockResolvedValue(undefined),
|
||||||
publish: vi.fn(),
|
publish: vi.fn(),
|
||||||
sendEvent: vi.fn(),
|
sendEvent: vi.fn(),
|
||||||
} as unknown as BaseBroadcaster;
|
} as unknown as BaseBroadcaster;
|
||||||
}
|
};
|
||||||
|
|
||||||
describe("DataRoute subscriptions", () => {
|
describe('DataRoute subscriptions', (): void => {
|
||||||
it("subscribes to future resource changes until removal", async () => {
|
it('subscribes to future resource changes until removal', async (): Promise<void> => {
|
||||||
let resolveRemoved: () => void = () => undefined;
|
let resolveRemoved: () => void = () => undefined;
|
||||||
const removed = new Promise<void>((resolve) => {
|
const removed = new Promise<void>((resolve) => {
|
||||||
resolveRemoved = resolve;
|
resolveRemoved = resolve;
|
||||||
});
|
});
|
||||||
const storage = {
|
const storage = {
|
||||||
db: {
|
db: {
|
||||||
transaction: vi.fn(),
|
transaction: vi.fn(),
|
||||||
},
|
|
||||||
} as unknown as Database;
|
|
||||||
const broadcaster = createBroadcasterStub();
|
|
||||||
vi.mocked(broadcaster.subscribe).mockReturnValue(removed);
|
|
||||||
const connection = new TestConnection(true, false);
|
|
||||||
const stream = new ApplicationRouteStream(connection, {
|
|
||||||
resourceId: ["a", "b"],
|
|
||||||
});
|
|
||||||
const route = new DataRoute(storage, broadcaster, 0);
|
|
||||||
|
|
||||||
const execution = route.subscribeData(stream);
|
|
||||||
|
|
||||||
expect(broadcaster.subscribe).toHaveBeenCalledWith(
|
|
||||||
stream,
|
|
||||||
["resource:a", "resource:b"],
|
|
||||||
);
|
|
||||||
expect(storage.db.transaction).not.toHaveBeenCalled();
|
|
||||||
expect(connection.messages).toEqual([]);
|
|
||||||
await expect(
|
|
||||||
Promise.race([
|
|
||||||
execution.then(() => "settled"),
|
|
||||||
Promise.resolve("pending"),
|
|
||||||
]),
|
|
||||||
).resolves.toBe("pending");
|
|
||||||
|
|
||||||
resolveRemoved();
|
|
||||||
await execution;
|
|
||||||
});
|
|
||||||
|
|
||||||
it("unsubscribes a bidirectional connection and acknowledges the request", async () => {
|
|
||||||
const storage = {
|
|
||||||
db: {
|
|
||||||
transaction: vi.fn(),
|
|
||||||
},
|
|
||||||
} as unknown as Database;
|
|
||||||
const broadcaster = createBroadcasterStub();
|
|
||||||
const connection = new TestConnection(true, true);
|
|
||||||
const stream = new ApplicationRouteStream(
|
|
||||||
connection,
|
|
||||||
{ resourceId: ["a"] },
|
|
||||||
"unsubscribe-1",
|
|
||||||
);
|
|
||||||
const route = new DataRoute(storage, broadcaster, 0);
|
|
||||||
|
|
||||||
await route.unsubscribeData(stream);
|
|
||||||
|
|
||||||
expect(broadcaster.unsubscribe).toHaveBeenCalledWith(stream, [
|
|
||||||
"resource:a",
|
|
||||||
]);
|
|
||||||
expect(connection.messages).toEqual([
|
|
||||||
{
|
|
||||||
id: "unsubscribe-1",
|
|
||||||
type: "response",
|
|
||||||
statusCode: 200,
|
|
||||||
body: {},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects selective unsubscribe on a one-way connection", async () => {
|
|
||||||
const storage = {
|
|
||||||
db: {
|
|
||||||
transaction: vi.fn(),
|
|
||||||
},
|
|
||||||
} as unknown as Database;
|
|
||||||
const broadcaster = createBroadcasterStub();
|
|
||||||
const stream = new ApplicationRouteStream(new TestConnection(true, false), {
|
|
||||||
resourceId: ["a"],
|
|
||||||
});
|
|
||||||
const route = new DataRoute(storage, broadcaster, 0);
|
|
||||||
|
|
||||||
await expect(route.unsubscribeData(stream)).rejects.toMatchObject({ statusCode: HTTP_STATUS_CODE_NOT_ACCEPTED });
|
|
||||||
expect(broadcaster.unsubscribe).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("DataRoute resource write auth", () => {
|
|
||||||
it("rejects an invalid resource signature before writing the batch", async () => {
|
|
||||||
const storage = {
|
|
||||||
db: {
|
|
||||||
transaction: vi.fn(),
|
|
||||||
},
|
|
||||||
} as unknown as Database;
|
|
||||||
|
|
||||||
const broadcaster = createBroadcasterStub()
|
|
||||||
const route = new DataRoute(storage, broadcaster, 0);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
route.writeData({
|
|
||||||
connection: new TestConnection(true, true),
|
|
||||||
streaming: true,
|
|
||||||
bidirectional: true,
|
|
||||||
send: vi.fn(),
|
|
||||||
body: {
|
|
||||||
resources: [
|
|
||||||
{
|
|
||||||
id: "resource-a",
|
|
||||||
publicKey: "not-a-public-key",
|
|
||||||
timestamp: Date.now(),
|
|
||||||
signature: "not-a-signature",
|
|
||||||
value: new Uint8Array([1, 2, 3]),
|
|
||||||
},
|
},
|
||||||
],
|
} as unknown as Database;
|
||||||
},
|
const broadcaster = createBroadcasterStub();
|
||||||
} as unknown as ApplicationRouteStream),
|
vi.mocked(broadcaster.subscribe).mockReturnValue(removed);
|
||||||
).rejects.toBeInstanceOf(UnauthorizedError);
|
const connection = new TestConnection(true, false);
|
||||||
|
const stream = new ApplicationRouteStream(connection, {
|
||||||
|
resourceId: [ 'a', 'b' ],
|
||||||
|
});
|
||||||
|
const route = new DataRoute(storage, broadcaster, 0);
|
||||||
|
|
||||||
expect(storage.db.transaction).not.toHaveBeenCalled()
|
const execution = route.subscribeData(stream);
|
||||||
expect(broadcaster.publish).not.toHaveBeenCalled();
|
|
||||||
});
|
expect(broadcaster.subscribe).toHaveBeenCalledWith(stream, [ 'resource:a', 'resource:b' ]);
|
||||||
|
expect(storage.db.transaction).not.toHaveBeenCalled();
|
||||||
|
expect(connection.messages).toEqual([]);
|
||||||
|
await expect(Promise.race([ execution.then(() => 'settled'), Promise.resolve('pending') ])).resolves.toBe('pending');
|
||||||
|
|
||||||
|
resolveRemoved();
|
||||||
|
await execution;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unsubscribes a bidirectional connection and acknowledges the request', async (): Promise<void> => {
|
||||||
|
const storage = {
|
||||||
|
db: {
|
||||||
|
transaction: vi.fn(),
|
||||||
|
},
|
||||||
|
} as unknown as Database;
|
||||||
|
const broadcaster = createBroadcasterStub();
|
||||||
|
const connection = new TestConnection(true, true);
|
||||||
|
const stream = new ApplicationRouteStream(connection, { resourceId: [ 'a' ] }, 'unsubscribe-1');
|
||||||
|
const route = new DataRoute(storage, broadcaster, 0);
|
||||||
|
|
||||||
|
await route.unsubscribeData(stream);
|
||||||
|
|
||||||
|
expect(broadcaster.unsubscribe).toHaveBeenCalledWith(stream, [ 'resource:a' ]);
|
||||||
|
expect(connection.messages).toEqual([
|
||||||
|
{
|
||||||
|
id: 'unsubscribe-1',
|
||||||
|
type: 'response',
|
||||||
|
statusCode: 200,
|
||||||
|
body: {},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects selective unsubscribe on a one-way connection', async (): Promise<void> => {
|
||||||
|
const storage = {
|
||||||
|
db: {
|
||||||
|
transaction: vi.fn(),
|
||||||
|
},
|
||||||
|
} as unknown as Database;
|
||||||
|
const broadcaster = createBroadcasterStub();
|
||||||
|
const stream = new ApplicationRouteStream(new TestConnection(true, false), {
|
||||||
|
resourceId: [ 'a' ],
|
||||||
|
});
|
||||||
|
const route = new DataRoute(storage, broadcaster, 0);
|
||||||
|
|
||||||
|
await expect(route.unsubscribeData(stream)).rejects.toMatchObject({ statusCode: HTTP_STATUS_CODE_NOT_ACCEPTED });
|
||||||
|
expect(broadcaster.unsubscribe).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('DataRoute resource write auth', (): void => {
|
||||||
|
it('rejects an invalid resource signature before writing the batch', async (): Promise<void> => {
|
||||||
|
const storage = {
|
||||||
|
db: {
|
||||||
|
transaction: vi.fn(),
|
||||||
|
},
|
||||||
|
} as unknown as Database;
|
||||||
|
|
||||||
|
const broadcaster = createBroadcasterStub();
|
||||||
|
const route = new DataRoute(storage, broadcaster, 0);
|
||||||
|
|
||||||
|
await expect(route.writeData({
|
||||||
|
connection: new TestConnection(true, true),
|
||||||
|
streaming: true,
|
||||||
|
bidirectional: true,
|
||||||
|
send: vi.fn(),
|
||||||
|
body: {
|
||||||
|
resources: [
|
||||||
|
{
|
||||||
|
id: 'resource-a',
|
||||||
|
publicKey: 'not-a-public-key',
|
||||||
|
timestamp: Date.now(),
|
||||||
|
signature: 'not-a-signature',
|
||||||
|
value: new Uint8Array([ 1, 2, 3 ]),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
} as unknown as ApplicationRouteStream)).rejects.toBeInstanceOf(UnauthorizedError);
|
||||||
|
|
||||||
|
expect(storage.db.transaction).not.toHaveBeenCalled();
|
||||||
|
expect(broadcaster.publish).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+158
-177
@@ -1,199 +1,180 @@
|
|||||||
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.objectContaining({
|
||||||
|
type: 'item-changed',
|
||||||
|
data: { id: 'a' },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// A different request-scoped facade still resolves the connection's
|
||||||
|
// original subscription.
|
||||||
|
await broadcaster.unsubscribe(routeStream(connection), [ 'items' ]);
|
||||||
|
await expect(subscribed).resolves.toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(connection.messages).toEqual([
|
it('resolves fully duplicate subscriptions immediately', async (): Promise<void> => {
|
||||||
expect.objectContaining({
|
const broadcaster = createBroadcaster();
|
||||||
type: "item-changed",
|
const connection = new TestConnection(true, true);
|
||||||
data: { id: "a" },
|
const first = broadcaster.subscribe(routeStream(connection), [ 'items', 'items' ]);
|
||||||
}),
|
const duplicate = broadcaster.subscribe(routeStream(connection), [ 'items' ]);
|
||||||
]);
|
|
||||||
|
|
||||||
// A different request-scoped facade still resolves the connection's
|
await expect(duplicate).resolves.toBeUndefined();
|
||||||
// original subscription.
|
await expectPending(first);
|
||||||
await broadcaster.unsubscribe(routeStream(connection), ["items"]);
|
expect(connection.closeCallbacks).toHaveLength(1);
|
||||||
await expect(subscribed).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves fully duplicate subscriptions immediately", async () => {
|
await broadcaster.unsubscribe(routeStream(connection), [ 'items' ]);
|
||||||
const broadcaster = createBroadcaster();
|
await first;
|
||||||
const connection = new TestConnection(true, true);
|
|
||||||
const first = broadcaster.subscribe(routeStream(connection), [
|
|
||||||
"items",
|
|
||||||
"items",
|
|
||||||
]);
|
|
||||||
const duplicate = broadcaster.subscribe(routeStream(connection), ["items"]);
|
|
||||||
|
|
||||||
await expect(duplicate).resolves.toBeUndefined();
|
|
||||||
await expectPending(first);
|
|
||||||
expect(connection.closeCallbacks).toHaveLength(1);
|
|
||||||
|
|
||||||
await broadcaster.unsubscribe(routeStream(connection), ["items"]);
|
|
||||||
await first;
|
|
||||||
});
|
|
||||||
|
|
||||||
it("waits only for topics newly added by a partially overlapping call", async () => {
|
|
||||||
const broadcaster = createBroadcaster();
|
|
||||||
const connection = new TestConnection(true, true);
|
|
||||||
const first = broadcaster.subscribe(routeStream(connection), ["a"]);
|
|
||||||
const second = broadcaster.subscribe(routeStream(connection), ["a", "b"]);
|
|
||||||
|
|
||||||
await broadcaster.unsubscribe(routeStream(connection), ["a"]);
|
|
||||||
await expect(first).resolves.toBeUndefined();
|
|
||||||
await expectPending(second);
|
|
||||||
|
|
||||||
await broadcaster.unsubscribe(routeStream(connection), ["b"]);
|
|
||||||
await expect(second).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves every pending subscription and removes topics on close", async () => {
|
|
||||||
const broadcaster = createBroadcaster();
|
|
||||||
const connection = new TestConnection(true, false);
|
|
||||||
const first = broadcaster.subscribe(routeStream(connection), ["a"]);
|
|
||||||
const second = broadcaster.subscribe(routeStream(connection), ["b"]);
|
|
||||||
|
|
||||||
connection.close();
|
|
||||||
await Promise.all([first, second]);
|
|
||||||
await broadcaster.publish("a", { type: "changed", data: null });
|
|
||||||
await broadcaster.publish("b", { type: "changed", data: null });
|
|
||||||
|
|
||||||
expect(connection.messages).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("immediately resolves registration against an already-closed connection", async () => {
|
|
||||||
const broadcaster = createBroadcaster();
|
|
||||||
const connection = new TestConnection(true, false);
|
|
||||||
connection.close();
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
broadcaster.subscribe(routeStream(connection), ["items"]),
|
|
||||||
).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects subscriptions on a non-streaming connection", () => {
|
|
||||||
const broadcaster = createBroadcaster();
|
|
||||||
const connection = new TestConnection(false, false);
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
broadcaster.subscribe(routeStream(connection), ["items"]),
|
|
||||||
).toThrowError(
|
|
||||||
expect.objectContaining({ statusCode: 406 }),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("treats an empty subscription and repeated unsubscribe as no-ops", async () => {
|
|
||||||
const broadcaster = createBroadcaster();
|
|
||||||
const connection = new TestConnection(true, true);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
broadcaster.subscribe(routeStream(connection), []),
|
|
||||||
).resolves.toBeUndefined();
|
|
||||||
await broadcaster.unsubscribe(routeStream(connection), ["missing"]);
|
|
||||||
await broadcaster.unsubscribe(routeStream(connection));
|
|
||||||
|
|
||||||
expect(connection.closeCallbacks).toHaveLength(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("fans out concurrently to independent connections", async () => {
|
|
||||||
const broadcaster = createBroadcaster();
|
|
||||||
const first = new TestConnection(true, false);
|
|
||||||
const second = new TestConnection(true, false);
|
|
||||||
const originalFirstSend = first.send.bind(first);
|
|
||||||
let releaseFirst: () => void = () => undefined;
|
|
||||||
const firstReleased = new Promise<void>((resolve) => {
|
|
||||||
releaseFirst = resolve;
|
|
||||||
});
|
|
||||||
let markSecondSent: () => void = () => undefined;
|
|
||||||
const secondSent = new Promise<void>((resolve) => {
|
|
||||||
markSecondSent = resolve;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
first.send = async (message) => {
|
it('waits only for topics newly added by a partially overlapping call', async (): Promise<void> => {
|
||||||
await firstReleased;
|
const broadcaster = createBroadcaster();
|
||||||
await originalFirstSend(message);
|
const connection = new TestConnection(true, true);
|
||||||
};
|
const first = broadcaster.subscribe(routeStream(connection), [ 'a' ]);
|
||||||
second.send = async (message) => {
|
const second = broadcaster.subscribe(routeStream(connection), [ 'a', 'b' ]);
|
||||||
await TestConnection.prototype.send.call(second, message);
|
|
||||||
markSecondSent();
|
|
||||||
};
|
|
||||||
|
|
||||||
const firstSubscription = broadcaster.subscribe(routeStream(first), [
|
await broadcaster.unsubscribe(routeStream(connection), [ 'a' ]);
|
||||||
"items",
|
await expect(first).resolves.toBeUndefined();
|
||||||
]);
|
await expectPending(second);
|
||||||
const secondSubscription = broadcaster.subscribe(routeStream(second), [
|
|
||||||
"items",
|
await broadcaster.unsubscribe(routeStream(connection), [ 'b' ]);
|
||||||
]);
|
await expect(second).resolves.toBeUndefined();
|
||||||
const publication = broadcaster.publish("items", {
|
|
||||||
type: "item-changed",
|
|
||||||
data: {},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await secondSent;
|
it('resolves every pending subscription and removes topics on close', async (): Promise<void> => {
|
||||||
releaseFirst();
|
const broadcaster = createBroadcaster();
|
||||||
await publication;
|
const connection = new TestConnection(true, false);
|
||||||
|
const first = broadcaster.subscribe(routeStream(connection), [ 'a' ]);
|
||||||
|
const second = broadcaster.subscribe(routeStream(connection), [ 'b' ]);
|
||||||
|
|
||||||
expect(first.messages).toHaveLength(1);
|
connection.close();
|
||||||
expect(second.messages).toHaveLength(1);
|
await Promise.all([ first, second ]);
|
||||||
|
await broadcaster.publish('a', { type: 'changed', data: null });
|
||||||
|
await broadcaster.publish('b', { type: 'changed', data: null });
|
||||||
|
|
||||||
first.close();
|
expect(connection.messages).toEqual([]);
|
||||||
second.close();
|
|
||||||
await Promise.all([firstSubscription, secondSubscription]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("closes and removes a connection whose event delivery fails", async () => {
|
|
||||||
const broadcaster = createBroadcaster();
|
|
||||||
const connection = new TestConnection(true, true);
|
|
||||||
connection.send = vi.fn().mockRejectedValue(new Error("socket failed"));
|
|
||||||
const subscribed = broadcaster.subscribe(routeStream(connection), [
|
|
||||||
"items",
|
|
||||||
]);
|
|
||||||
|
|
||||||
await broadcaster.publish("items", {
|
|
||||||
type: "item-changed",
|
|
||||||
data: {},
|
|
||||||
});
|
});
|
||||||
await subscribed;
|
|
||||||
|
|
||||||
expect(connection.closed).toBe(true);
|
it('immediately resolves registration against an already-closed connection', async (): Promise<void> => {
|
||||||
expect(connection.send).toHaveBeenCalledOnce();
|
const broadcaster = createBroadcaster();
|
||||||
|
const connection = new TestConnection(true, false);
|
||||||
|
connection.close();
|
||||||
|
|
||||||
await broadcaster.publish("items", {
|
await expect(broadcaster.subscribe(routeStream(connection), [ 'items' ])).resolves.toBeUndefined();
|
||||||
type: "item-changed",
|
});
|
||||||
data: {},
|
|
||||||
|
it('rejects subscriptions on a non-streaming connection', (): void => {
|
||||||
|
const broadcaster = createBroadcaster();
|
||||||
|
const connection = new TestConnection(false, false);
|
||||||
|
|
||||||
|
expect(() => broadcaster.subscribe(routeStream(connection), [ 'items' ])).toThrowError(expect.objectContaining({ statusCode: 406 }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats an empty subscription and repeated unsubscribe as no-ops', async (): Promise<void> => {
|
||||||
|
const broadcaster = createBroadcaster();
|
||||||
|
const connection = new TestConnection(true, true);
|
||||||
|
|
||||||
|
await expect(broadcaster.subscribe(routeStream(connection), [])).resolves.toBeUndefined();
|
||||||
|
await broadcaster.unsubscribe(routeStream(connection), [ 'missing' ]);
|
||||||
|
await broadcaster.unsubscribe(routeStream(connection));
|
||||||
|
|
||||||
|
expect(connection.closeCallbacks).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fans out concurrently to independent connections', async (): Promise<void> => {
|
||||||
|
const broadcaster = createBroadcaster();
|
||||||
|
const first = new TestConnection(true, false);
|
||||||
|
const second = new TestConnection(true, false);
|
||||||
|
const originalFirstSend = first.send.bind(first);
|
||||||
|
let releaseFirst: () => void = () => undefined;
|
||||||
|
const firstReleased = new Promise<void>((resolve) => {
|
||||||
|
releaseFirst = resolve;
|
||||||
|
});
|
||||||
|
let markSecondSent: () => void = () => undefined;
|
||||||
|
const secondSent = new Promise<void>((resolve) => {
|
||||||
|
markSecondSent = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
first.send = async (message): Promise<void> => {
|
||||||
|
await firstReleased;
|
||||||
|
await originalFirstSend(message);
|
||||||
|
};
|
||||||
|
|
||||||
|
second.send = async (message): Promise<void> => {
|
||||||
|
await TestConnection.prototype.send.call(second, message);
|
||||||
|
markSecondSent();
|
||||||
|
};
|
||||||
|
|
||||||
|
const firstSubscription = broadcaster.subscribe(routeStream(first), [ 'items' ]);
|
||||||
|
const secondSubscription = broadcaster.subscribe(routeStream(second), [ 'items' ]);
|
||||||
|
const publication = broadcaster.publish('items', {
|
||||||
|
type: 'item-changed',
|
||||||
|
data: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
await secondSent;
|
||||||
|
releaseFirst();
|
||||||
|
await publication;
|
||||||
|
|
||||||
|
expect(first.messages).toHaveLength(1);
|
||||||
|
expect(second.messages).toHaveLength(1);
|
||||||
|
|
||||||
|
first.close();
|
||||||
|
second.close();
|
||||||
|
await Promise.all([ firstSubscription, secondSubscription ]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes and removes a connection whose event delivery fails', async (): Promise<void> => {
|
||||||
|
const broadcaster = createBroadcaster();
|
||||||
|
const connection = new TestConnection(true, true);
|
||||||
|
connection.send = vi.fn().mockRejectedValue(new Error('socket failed'));
|
||||||
|
const subscribed = broadcaster.subscribe(routeStream(connection), [ 'items' ]);
|
||||||
|
|
||||||
|
await broadcaster.publish('items', {
|
||||||
|
type: 'item-changed',
|
||||||
|
data: {},
|
||||||
|
});
|
||||||
|
await subscribed;
|
||||||
|
|
||||||
|
expect(connection.closed).toBe(true);
|
||||||
|
expect(connection.send).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
await broadcaster.publish('items', {
|
||||||
|
type: 'item-changed',
|
||||||
|
data: {},
|
||||||
|
});
|
||||||
|
expect(connection.send).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
expect(connection.send).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
+94
-117
@@ -1,134 +1,111 @@
|
|||||||
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);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
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 });
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,62 +1,58 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { HonoSSEStream } from "../../../source/services/stream/hono-sse-stream.js";
|
import { HonoSSEStream } from '../../../source/services/stream/hono-sse-stream.ts';
|
||||||
import { HttpRequestStream } from "../../../source/services/stream/http-request-stream.js";
|
import { HttpRequestStream } from '../../../source/services/stream/http-request-stream.ts';
|
||||||
import { WSStream } from "../../../source/services/stream/ws-stream.js";
|
import { WSStream } from '../../../source/services/stream/ws-stream.ts';
|
||||||
|
|
||||||
describe("stream lifecycle observers", () => {
|
describe('stream lifecycle observers', (): void => {
|
||||||
it("buffers exactly one normal HTTP response", async () => {
|
it('buffers exactly one normal HTTP response', async (): Promise<void> => {
|
||||||
const stream = new HttpRequestStream();
|
const stream = new HttpRequestStream();
|
||||||
|
|
||||||
await stream.send({
|
await stream.send({
|
||||||
type: "response",
|
type: 'response',
|
||||||
statusCode: 200,
|
statusCode: 200,
|
||||||
body: { ok: true },
|
body: { ok: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(stream.getResponse()).toEqual({
|
||||||
|
type: 'response',
|
||||||
|
statusCode: 200,
|
||||||
|
body: { ok: true },
|
||||||
|
});
|
||||||
|
await expect(stream.send({
|
||||||
|
type: 'response',
|
||||||
|
statusCode: 200,
|
||||||
|
body: { second: true },
|
||||||
|
})).rejects.toThrow('only send one response');
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(stream.getResponse()).toEqual({
|
it('notifies WebSocket observers registered after remote closure', (): void => {
|
||||||
type: "response",
|
const stream = new WSStream({
|
||||||
statusCode: 200,
|
send: vi.fn(),
|
||||||
body: { ok: true },
|
close: vi.fn(),
|
||||||
|
readyState: 1,
|
||||||
|
});
|
||||||
|
const onClose = vi.fn();
|
||||||
|
|
||||||
|
stream.markClosed();
|
||||||
|
stream.onClose(onClose);
|
||||||
|
|
||||||
|
expect(onClose).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
await expect(
|
|
||||||
stream.send({
|
|
||||||
type: "response",
|
|
||||||
statusCode: 200,
|
|
||||||
body: { second: true },
|
|
||||||
}),
|
|
||||||
).rejects.toThrow("only send one response");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("notifies WebSocket observers registered after remote closure", () => {
|
it('notifies SSE observers registered after local closure', async (): Promise<void> => {
|
||||||
const stream = new WSStream({
|
const streamApi = {
|
||||||
send: vi.fn(),
|
writeSSE: vi.fn(),
|
||||||
close: vi.fn(),
|
close: vi.fn(),
|
||||||
readyState: 1,
|
};
|
||||||
|
const stream = new HonoSSEStream(streamApi as unknown as ConstructorParameters<typeof HonoSSEStream>[0]);
|
||||||
|
const onClose = vi.fn();
|
||||||
|
|
||||||
|
await stream.close();
|
||||||
|
stream.onClose(onClose);
|
||||||
|
await stream.close();
|
||||||
|
|
||||||
|
expect(streamApi.close).toHaveBeenCalledOnce();
|
||||||
|
expect(onClose).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
const onClose = vi.fn();
|
|
||||||
|
|
||||||
stream.markClosed();
|
|
||||||
stream.onClose(onClose);
|
|
||||||
|
|
||||||
expect(onClose).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("notifies SSE observers registered after local closure", () => {
|
|
||||||
const streamApi = {
|
|
||||||
writeSSE: vi.fn(),
|
|
||||||
close: vi.fn(),
|
|
||||||
};
|
|
||||||
const stream = new HonoSSEStream(
|
|
||||||
streamApi as unknown as ConstructorParameters<typeof HonoSSEStream>[0],
|
|
||||||
);
|
|
||||||
const onClose = vi.fn();
|
|
||||||
|
|
||||||
stream.close();
|
|
||||||
stream.onClose(onClose);
|
|
||||||
stream.close();
|
|
||||||
|
|
||||||
expect(streamApi.close).toHaveBeenCalledOnce();
|
|
||||||
expect(onClose).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,242 +1,237 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from 'hono';
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import type { RouteDefinition } from "../../../source/routes/types.js";
|
import type { RouteDefinition } from '../../../source/routes/types.ts';
|
||||||
import { ApplicationError } from "../../../source/errors/index.js";
|
import { ApplicationError } from '../../../source/errors/index.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 { HttpTransportRouter } from "../../../source/services/transport/http-transport.js";
|
import { HttpTransportRouter } from '../../../source/services/transport/http-transport.ts';
|
||||||
import type { AppEnv } from "../../../source/services/transport/transport-router.js";
|
import type { AppEnv } from '../../../source/services/transport/transport-router.ts';
|
||||||
import { fromExtendedJson, toExtendedJson } from "@xo-cash/utils";
|
import { fromExtendedJson, toExtendedJson } from '@xo-cash/utils';
|
||||||
import { Logger } from "../../../source/utils/logger.js";
|
import { Logger } from '../../../source/utils/logger.ts';
|
||||||
import { ServerHost } from "../../../source/services/server-host.js";
|
import { ServerHost } from '../../../source/services/server-host.ts';
|
||||||
|
|
||||||
async function createApp(
|
const createApp = async (
|
||||||
routes: RouteDefinition[] | ((broadcaster: Broadcaster) => RouteDefinition[]),
|
routes: RouteDefinition[] | ((broadcaster: Broadcaster) => RouteDefinition[]),
|
||||||
maxRequestBodyBytes = 1024 * 1024,
|
maxRequestBodyBytes = 1024 * 1024,
|
||||||
): Promise<Hono<AppEnv>> {
|
): Promise<Hono<AppEnv>> => {
|
||||||
const debug = new Logger("http-transport-test");
|
const debug = new Logger('http-transport-test');
|
||||||
const broadcaster = new Broadcaster(debug);
|
const broadcaster = new Broadcaster(debug);
|
||||||
const resolvedRoutes =
|
const resolvedRoutes = typeof routes === 'function' ? routes(broadcaster) : routes;
|
||||||
typeof routes === "function" ? routes(broadcaster) : routes;
|
const router = await ApplicationRouter.create([
|
||||||
const router = await ApplicationRouter.create([
|
|
||||||
{
|
|
||||||
async getRoutes() {
|
|
||||||
return resolvedRoutes;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const transport = new HttpTransportRouter(router, debug);
|
|
||||||
const app = new Hono<AppEnv>();
|
|
||||||
|
|
||||||
app.onError(HttpTransportRouter.createErrorHandler(debug));
|
|
||||||
app.use("*", ServerHost.limitBodySizeMiddleware(maxRequestBodyBytes, debug));
|
|
||||||
app.use("*", HttpTransportRouter.createExtJsonMiddleware(debug));
|
|
||||||
transport.register(app);
|
|
||||||
return app;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("HttpTransportRouter", () => {
|
|
||||||
it("runs normal HTTP through a non-streaming route stream", async () => {
|
|
||||||
const app = await createApp([
|
|
||||||
{
|
|
||||||
url: "/echo",
|
|
||||||
handler: async (stream) => stream.send(stream.body),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const value = new Uint8Array([1, 2, 3]);
|
|
||||||
|
|
||||||
const response = await app.request("/echo", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: toExtendedJson({ value }),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(response.status).toBe(200);
|
|
||||||
expect(fromExtendedJson(await response.text())).toEqual({ value });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 204 when a normal HTTP route sends nothing", async () => {
|
|
||||||
const app = await createApp([
|
|
||||||
{
|
|
||||||
url: "/nothing",
|
|
||||||
handler: () => undefined,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const response = await app.request("/nothing", { method: "POST" });
|
|
||||||
|
|
||||||
expect(response.status).toBe(204);
|
|
||||||
expect(await response.text()).toBe("");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns normalized errors for non-streaming requests", async () => {
|
|
||||||
const app = await createApp([]);
|
|
||||||
|
|
||||||
const missing = await app.request("/missing", { method: "POST" });
|
|
||||||
expect(missing.status).toBe(404);
|
|
||||||
expect(await missing.json()).toEqual({
|
|
||||||
statusCode: 404,
|
|
||||||
error: "No route found for /missing",
|
|
||||||
});
|
|
||||||
|
|
||||||
const invalid = await app.request("/missing", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: "{",
|
|
||||||
});
|
|
||||||
expect(invalid.status).toBe(400);
|
|
||||||
expect(await invalid.json()).toEqual({
|
|
||||||
statusCode: 400,
|
|
||||||
error: "Invalid JSON in request body",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects subscribe when normal HTTP has no streaming capability", async () => {
|
|
||||||
const app = await createApp((broadcaster) => [
|
|
||||||
{
|
|
||||||
url: "/items/subscribe",
|
|
||||||
handler: async (stream) => {
|
|
||||||
await broadcaster.subscribe(stream, ["items"]);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const response = await app.request("/items/subscribe", { method: "POST" });
|
|
||||||
|
|
||||||
expect(response.status).toBe(406);
|
|
||||||
expect(await response.json()).toMatchObject({ statusCode: 406 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("sends SSE route errors as events and closes only that stream", async () => {
|
|
||||||
const app = await createApp([
|
|
||||||
{
|
|
||||||
url: "/items/subscribe",
|
|
||||||
handler: () => {
|
|
||||||
throw new Error("private storage failure");
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const response = await app.request("/items/subscribe", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { accept: "text/event-stream" },
|
|
||||||
});
|
|
||||||
const events = await response.text();
|
|
||||||
|
|
||||||
expect(response.status).toBe(200);
|
|
||||||
expect(events).toContain("event: error");
|
|
||||||
expect(events).toContain(
|
|
||||||
'data: {"statusCode":500,"error":"Internal Server Error"}',
|
|
||||||
);
|
|
||||||
expect(events).not.toContain("private storage failure");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("sends a normal route as one SSE response event and then closes", async () => {
|
|
||||||
const app = await createApp([
|
|
||||||
{
|
|
||||||
url: "/echo",
|
|
||||||
handler: (stream) => stream.send({ ok: true }),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const response = await app.request("/echo", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { accept: "text/event-stream" },
|
|
||||||
});
|
|
||||||
const events = await response.text();
|
|
||||||
|
|
||||||
expect(response.status).toBe(200);
|
|
||||||
expect(events).toContain("event: response");
|
|
||||||
expect(events).toContain('data: {"ok":true}');
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps SSE open until the route's subscription promise resolves", async () => {
|
|
||||||
let removeSubscription: () => Promise<void> = async () => undefined;
|
|
||||||
let markSubscribed: () => void = () => undefined;
|
|
||||||
const subscribed = new Promise<void>((resolve) => {
|
|
||||||
markSubscribed = resolve;
|
|
||||||
});
|
|
||||||
const app = await createApp((broadcaster) => [
|
|
||||||
{
|
|
||||||
url: "/items/subscribe",
|
|
||||||
handler: async (stream) => {
|
|
||||||
const topics = ["items"];
|
|
||||||
removeSubscription = () => broadcaster.unsubscribe(stream, topics);
|
|
||||||
|
|
||||||
const removed = broadcaster.subscribe(stream, topics);
|
|
||||||
markSubscribed();
|
|
||||||
await removed;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const response = await app.request("/items/subscribe", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { accept: "text/event-stream" },
|
|
||||||
});
|
|
||||||
const body = response.text();
|
|
||||||
const completed = vi.fn();
|
|
||||||
void body.then(completed);
|
|
||||||
|
|
||||||
await subscribed;
|
|
||||||
await Promise.resolve();
|
|
||||||
expect(completed).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
await removeSubscription();
|
|
||||||
|
|
||||||
expect(await body).toBe("");
|
|
||||||
expect(completed).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects unsubscribe over non-bidirectional SSE", async () => {
|
|
||||||
const app = await createApp((broadcaster) => [
|
|
||||||
{
|
|
||||||
url: "/items/unsubscribe",
|
|
||||||
handler: async (stream) => {
|
|
||||||
if (!stream.bidirectional) {
|
|
||||||
throw new ApplicationError(
|
|
||||||
400,
|
|
||||||
"This route requires an existing bidirectional stream",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await broadcaster.unsubscribe(stream, ["items"]);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const response = await app.request("/items/unsubscribe", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { accept: "text/event-stream" },
|
|
||||||
});
|
|
||||||
const events = await response.text();
|
|
||||||
|
|
||||||
expect(response.status).toBe(200);
|
|
||||||
expect(events).toContain("event: error");
|
|
||||||
expect(events).toContain('"statusCode":400');
|
|
||||||
});
|
|
||||||
it("rejects HTTP bodies larger than the configured byte limit", async () => {
|
|
||||||
const app = await createApp(
|
|
||||||
[
|
|
||||||
{
|
{
|
||||||
url: "/echo",
|
async getRoutes(): Promise<RouteDefinition[]> {
|
||||||
handler: async (stream) => stream.send(stream.body),
|
return resolvedRoutes;
|
||||||
|
},
|
||||||
},
|
},
|
||||||
],
|
]);
|
||||||
32,
|
const transport = new HttpTransportRouter(router, debug);
|
||||||
);
|
const app = new Hono<AppEnv>();
|
||||||
|
|
||||||
const response = await app.request("/echo", {
|
app.onError(HttpTransportRouter.createErrorHandler(debug));
|
||||||
method: "POST",
|
app.use('*', ServerHost.limitBodySizeMiddleware(maxRequestBodyBytes, debug));
|
||||||
headers: { "content-type": "application/json" },
|
app.use('*', HttpTransportRouter.createExtJsonMiddleware(debug));
|
||||||
body: JSON.stringify({ value: "x".repeat(64) }),
|
transport.register(app);
|
||||||
|
|
||||||
|
return app;
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('HttpTransportRouter', (): void => {
|
||||||
|
it('runs normal HTTP through a non-streaming route stream', async (): Promise<void> => {
|
||||||
|
const app = await createApp([
|
||||||
|
{
|
||||||
|
url: '/echo',
|
||||||
|
handler: async (stream): Promise<void> => stream.send(stream.body),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const value = new Uint8Array([ 1, 2, 3 ]);
|
||||||
|
|
||||||
|
const response = await app.request('/echo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: toExtendedJson({ value }),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(fromExtendedJson(await response.text())).toEqual({ value });
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(response.status).toBe(413);
|
it('returns 204 when a normal HTTP route sends nothing', async (): Promise<void> => {
|
||||||
expect(await response.json()).toEqual({
|
const app = await createApp([
|
||||||
statusCode: 413,
|
{
|
||||||
error: "Request body exceeds the 32 byte limit",
|
url: '/nothing',
|
||||||
|
handler: (): void => undefined,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const response = await app.request('/nothing', { method: 'POST' });
|
||||||
|
|
||||||
|
expect(response.status).toBe(204);
|
||||||
|
expect(await response.text()).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns normalized errors for non-streaming requests', async (): Promise<void> => {
|
||||||
|
const app = await createApp([]);
|
||||||
|
|
||||||
|
const missing = await app.request('/missing', { method: 'POST' });
|
||||||
|
expect(missing.status).toBe(404);
|
||||||
|
expect(await missing.json()).toEqual({
|
||||||
|
statusCode: 404,
|
||||||
|
error: 'No route found for /missing',
|
||||||
|
});
|
||||||
|
|
||||||
|
const invalid = await app.request('/missing', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: '{',
|
||||||
|
});
|
||||||
|
expect(invalid.status).toBe(400);
|
||||||
|
expect(await invalid.json()).toEqual({
|
||||||
|
statusCode: 400,
|
||||||
|
error: 'Invalid JSON in request body',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects subscribe when normal HTTP has no streaming capability', async (): Promise<void> => {
|
||||||
|
const app = await createApp((broadcaster) => [
|
||||||
|
{
|
||||||
|
url: '/items/subscribe',
|
||||||
|
handler: async (stream): Promise<void> => {
|
||||||
|
await broadcaster.subscribe(stream, [ 'items' ]);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const response = await app.request('/items/subscribe', { method: 'POST' });
|
||||||
|
|
||||||
|
expect(response.status).toBe(406);
|
||||||
|
expect(await response.json()).toMatchObject({ statusCode: 406 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends SSE route errors as events and closes only that stream', async (): Promise<void> => {
|
||||||
|
const app = await createApp([
|
||||||
|
{
|
||||||
|
url: '/items/subscribe',
|
||||||
|
handler: (): void => {
|
||||||
|
throw new Error('private storage failure');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const response = await app.request('/items/subscribe', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { accept: 'text/event-stream' },
|
||||||
|
});
|
||||||
|
const events = await response.text();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(events).toContain('event: error');
|
||||||
|
expect(events).toContain('data: {"statusCode":500,"error":"Internal Server Error"}');
|
||||||
|
expect(events).not.toContain('private storage failure');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends a normal route as one SSE response event and then closes', async (): Promise<void> => {
|
||||||
|
const app = await createApp([
|
||||||
|
{
|
||||||
|
url: '/echo',
|
||||||
|
handler: (stream): Promise<void> => stream.send({ ok: true }),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const response = await app.request('/echo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { accept: 'text/event-stream' },
|
||||||
|
});
|
||||||
|
const events = await response.text();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(events).toContain('event: response');
|
||||||
|
expect(events).toContain('data: {"ok":true}');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps SSE open until the route's subscription promise resolves", async (): Promise<void> => {
|
||||||
|
let removeSubscription: () => Promise<void> = async () => undefined;
|
||||||
|
let markSubscribed: () => void = () => undefined;
|
||||||
|
const subscribed = new Promise<void>((resolve) => {
|
||||||
|
markSubscribed = resolve;
|
||||||
|
});
|
||||||
|
const app = await createApp((broadcaster) => [
|
||||||
|
{
|
||||||
|
url: '/items/subscribe',
|
||||||
|
handler: async (stream): Promise<void> => {
|
||||||
|
const topics = [ 'items' ];
|
||||||
|
removeSubscription = (): Promise<void> => broadcaster.unsubscribe(stream, topics);
|
||||||
|
|
||||||
|
const removed = broadcaster.subscribe(stream, topics);
|
||||||
|
markSubscribed();
|
||||||
|
await removed;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const response = await app.request('/items/subscribe', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { accept: 'text/event-stream' },
|
||||||
|
});
|
||||||
|
const body = response.text();
|
||||||
|
const completed = vi.fn();
|
||||||
|
void body.then(completed);
|
||||||
|
|
||||||
|
await subscribed;
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(completed).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await removeSubscription();
|
||||||
|
|
||||||
|
expect(await body).toBe('');
|
||||||
|
expect(completed).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects unsubscribe over non-bidirectional SSE', async (): Promise<void> => {
|
||||||
|
const app = await createApp((broadcaster) => [
|
||||||
|
{
|
||||||
|
url: '/items/unsubscribe',
|
||||||
|
handler: async (stream): Promise<void> => {
|
||||||
|
if (!stream.bidirectional) {
|
||||||
|
throw new ApplicationError(400, 'This route requires an existing bidirectional stream');
|
||||||
|
}
|
||||||
|
|
||||||
|
await broadcaster.unsubscribe(stream, [ 'items' ]);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const response = await app.request('/items/unsubscribe', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { accept: 'text/event-stream' },
|
||||||
|
});
|
||||||
|
const events = await response.text();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(events).toContain('event: error');
|
||||||
|
expect(events).toContain('"statusCode":400');
|
||||||
|
});
|
||||||
|
it('rejects HTTP bodies larger than the configured byte limit', async (): Promise<void> => {
|
||||||
|
const app = await createApp(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
url: '/echo',
|
||||||
|
handler: async (stream): Promise<void> => stream.send(stream.body),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
32,
|
||||||
|
);
|
||||||
|
|
||||||
|
const response = await app.request('/echo', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({ value: 'x'.repeat(64) }),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.status).toBe(413);
|
||||||
|
expect(await response.json()).toEqual({
|
||||||
|
statusCode: 413,
|
||||||
|
error: 'Request body exceeds the 32 byte limit',
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,58 +1,48 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from 'vitest';
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import { WebSocketServer } from "ws";
|
import type { WebSocketServer } from 'ws';
|
||||||
|
|
||||||
import { ApplicationRouter } from "../../../source/services/router.js";
|
import { ApplicationRouter } from '../../../source/services/router.ts';
|
||||||
import {
|
import { WsTransportRouter } from '../../../source/services/transport/ws-transport.ts';
|
||||||
WsTransportRouter,
|
import { Logger } from '../../../source/utils/logger.ts';
|
||||||
} from "../../../source/services/transport/ws-transport.js";
|
import { toExtendedJson } from '@xo-cash/utils';
|
||||||
import { Logger } from "../../../source/utils/logger.js";
|
|
||||||
import { toExtendedJson } from "@xo-cash/utils";
|
|
||||||
|
|
||||||
describe("WebSocket request decoding", () => {
|
describe('WebSocket request decoding', (): void => {
|
||||||
it("decodes the minimal route-agnostic envelope and Extended JSON body", async () => {
|
it('decodes the minimal route-agnostic envelope and Extended JSON body', async (): Promise<void> => {
|
||||||
await expect(
|
await expect(WsTransportRouter.decodeWebSocketRequest(toExtendedJson({
|
||||||
WsTransportRouter.decodeWebSocketRequest(
|
id: 'request-1',
|
||||||
toExtendedJson({
|
path: '/data/write',
|
||||||
id: "request-1",
|
body: { value: new Uint8Array([ 1, 2, 3 ]) },
|
||||||
path: "/data/write",
|
}))).resolves.toEqual({
|
||||||
body: { value: new Uint8Array([1, 2, 3]) },
|
requestId: 'request-1',
|
||||||
}),
|
path: '/data/write',
|
||||||
),
|
body: { value: new Uint8Array([ 1, 2, 3 ]) },
|
||||||
).resolves.toEqual({
|
});
|
||||||
requestId: "request-1",
|
|
||||||
path: "/data/write",
|
|
||||||
body: { value: new Uint8Array([1, 2, 3]) },
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
it.each([
|
it.each([ '{}', '{"path":42}', '{"path":"/data/get","id":1}', '{"path":"/data/get","method":"POST"}' ])(
|
||||||
"{}",
|
'rejects an invalid envelope: %s',
|
||||||
'{"path":42}',
|
async (payload) => {
|
||||||
'{"path":"/data/get","id":1}',
|
await expect(WsTransportRouter.decodeWebSocketRequest(payload)).rejects.toBeInstanceOf(z.ZodError);
|
||||||
'{"path":"/data/get","method":"POST"}',
|
},
|
||||||
])("rejects an invalid envelope: %s", async (payload) => {
|
|
||||||
await expect(WsTransportRouter.decodeWebSocketRequest(payload)).rejects.toBeInstanceOf(
|
|
||||||
z.ZodError,
|
|
||||||
);
|
);
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects malformed JSON", async () => {
|
it('rejects malformed JSON', async (): Promise<void> => {
|
||||||
await expect(WsTransportRouter.decodeWebSocketRequest("{")).rejects.toMatchObject({
|
await expect(WsTransportRouter.decodeWebSocketRequest('{')).rejects.toMatchObject({
|
||||||
statusCode: 400,
|
statusCode: 400,
|
||||||
message: "Invalid JSON in WebSocket message",
|
message: 'Invalid JSON in WebSocket message',
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("WsTransportRouter payload limits", () => {
|
describe('WsTransportRouter payload limits', (): void => {
|
||||||
it("configures Hono's ws server with the requested maxPayload", async () => {
|
it("configures Hono's ws server with the requested maxPayload", async () => {
|
||||||
const debug = new Logger("ws-transport-test");
|
const debug = new Logger('ws-transport-test');
|
||||||
const router = await ApplicationRouter.create([]);
|
const router = await ApplicationRouter.create([]);
|
||||||
const transport = new WsTransportRouter(router, debug, 1024);
|
const transport = new WsTransportRouter(router, debug, 1024);
|
||||||
const wsServer = transport.websocketServer as unknown as WebSocketServer;
|
const wsServer = transport.websocketServer as unknown as WebSocketServer;
|
||||||
|
|
||||||
expect(wsServer.options.maxPayload).toBe(1024);
|
expect(wsServer.options.maxPayload).toBe(1024);
|
||||||
await transport.stop();
|
await transport.stop();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,76 +1,67 @@
|
|||||||
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 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(
|
const expectPending = async (promise: Promise<void>): Promise<void> => {
|
||||||
{ path: "/items/subscribe", requestId: "subscribe-1" },
|
const settled = vi.fn();
|
||||||
connection,
|
void promise.then(settled);
|
||||||
);
|
await Promise.resolve();
|
||||||
await vi.waitFor(() => expect(connection.closeCallbacks).toHaveLength(1));
|
expect(settled).not.toHaveBeenCalled();
|
||||||
await expectPending(original);
|
};
|
||||||
|
|
||||||
// This request uses a different ApplicationRouteStream over the same
|
describe('long-lived subscription dispatch', (): void => {
|
||||||
// connection. Since the topic already exists, its dispatch completes.
|
it('allows duplicate subscribe and unsubscribe requests while the original request waits', async (): Promise<void> => {
|
||||||
await router.dispatch(
|
const broadcaster = new Broadcaster(new Logger('subscription-flow-test'));
|
||||||
{ path: "/items/subscribe", requestId: "subscribe-2" },
|
const router = await ApplicationRouter.create([
|
||||||
connection,
|
moduleWith([
|
||||||
);
|
{
|
||||||
await expectPending(original);
|
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);
|
||||||
|
|
||||||
await router.dispatch(
|
const original = router.dispatch({ path: '/items/subscribe', requestId: 'subscribe-1' }, connection);
|
||||||
{ path: "/items/unsubscribe", requestId: "unsubscribe-1" },
|
await vi.waitFor(() => expect(connection.closeCallbacks).toHaveLength(1));
|
||||||
connection,
|
await expectPending(original);
|
||||||
);
|
|
||||||
await original;
|
|
||||||
|
|
||||||
expect(connection.messages).toEqual([
|
// This request uses a different ApplicationRouteStream over the same
|
||||||
{
|
// connection. Since the topic already exists, its dispatch completes.
|
||||||
id: "unsubscribe-1",
|
await router.dispatch({ path: '/items/subscribe', requestId: 'subscribe-2' }, connection);
|
||||||
type: "response",
|
await expectPending(original);
|
||||||
statusCode: 200,
|
|
||||||
body: {},
|
await router.dispatch({ path: '/items/unsubscribe', requestId: 'unsubscribe-1' }, connection);
|
||||||
},
|
await original;
|
||||||
]);
|
|
||||||
});
|
expect(connection.messages).toEqual([
|
||||||
|
{
|
||||||
|
id: 'unsubscribe-1',
|
||||||
|
type: 'response',
|
||||||
|
statusCode: 200,
|
||||||
|
body: {},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+1
-1
@@ -15,5 +15,5 @@
|
|||||||
"declarationMap": true,
|
"declarationMap": true,
|
||||||
"types": ["node"]
|
"types": ["node"]
|
||||||
},
|
},
|
||||||
"exclude": ["node_modules/**/*", "dist/**/*", "test"]
|
"exclude": ["node_modules/**/*", "dist/**/*"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user