Rename src to source
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
BaseStream,
|
||||
type StreamMessage,
|
||||
} from "../../source/services/stream/base-stream.js";
|
||||
|
||||
/** Minimal observable connection used by application and broadcaster tests. */
|
||||
export class TestConnection extends BaseStream {
|
||||
readonly messages: StreamMessage[] = [];
|
||||
readonly closeCallbacks: Array<() => void> = [];
|
||||
closed = false;
|
||||
|
||||
constructor(
|
||||
readonly streaming: boolean,
|
||||
readonly bidirectional: boolean,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async send(message: StreamMessage): Promise<void> {
|
||||
if (this.closed) {
|
||||
throw new Error("connection is closed");
|
||||
}
|
||||
|
||||
this.messages.push(message);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.closed = true;
|
||||
const callbacks = this.closeCallbacks.splice(0);
|
||||
callbacks.forEach((callback) => callback());
|
||||
}
|
||||
|
||||
onClose(callback: () => void): void {
|
||||
if (this.closed) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
this.closeCallbacks.push(callback);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { DataRoute } from "../../source/routes/resources.js";
|
||||
import { UnauthorizedError } from "../../source/errors/index.js";
|
||||
import { type BaseBroadcaster } from "../../source/services/broadcaster.js";
|
||||
import { ApplicationRouteStream } from "../../source/services/route-stream.js";
|
||||
import { Database } from "../../source/services/storage/database.js";
|
||||
import { TestConnection } from "../helpers/test-connection.js";
|
||||
import { HTTP_STATUS_CODE_NOT_ACCEPTED } from "../../source/constants.js";
|
||||
|
||||
function createBroadcasterStub() {
|
||||
return {
|
||||
subscribe: vi.fn(),
|
||||
unsubscribe: vi.fn().mockResolvedValue(undefined),
|
||||
publish: vi.fn(),
|
||||
sendEvent: vi.fn(),
|
||||
} as unknown as BaseBroadcaster;
|
||||
}
|
||||
|
||||
describe("DataRoute subscriptions", () => {
|
||||
it("subscribes to future resource changes until removal", async () => {
|
||||
let resolveRemoved: () => void = () => undefined;
|
||||
const removed = new Promise<void>((resolve) => {
|
||||
resolveRemoved = resolve;
|
||||
});
|
||||
const storage = {
|
||||
db: {
|
||||
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 ApplicationRouteStream),
|
||||
).rejects.toBeInstanceOf(UnauthorizedError);
|
||||
|
||||
expect(storage.db.transaction).not.toHaveBeenCalled()
|
||||
expect(broadcaster.publish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ApplicationError } from "../../source/errors/index.js";
|
||||
import { Broadcaster } from "../../source/services/broadcaster.js";
|
||||
import { ApplicationRouteStream } from "../../source/services/route-stream.js";
|
||||
import { Logger } from "../../source/utils/logger.js";
|
||||
import { TestConnection } from "../helpers/test-connection.js";
|
||||
|
||||
function createBroadcaster(): Broadcaster {
|
||||
return new Broadcaster(new Logger("broadcaster-test"));
|
||||
}
|
||||
|
||||
function routeStream(connection: TestConnection): ApplicationRouteStream {
|
||||
return new ApplicationRouteStream(connection, undefined);
|
||||
}
|
||||
|
||||
async function expectPending(promise: Promise<void>): Promise<void> {
|
||||
const settled = vi.fn();
|
||||
void promise.then(settled);
|
||||
await Promise.resolve();
|
||||
expect(settled).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
describe("Broadcaster subscriptions", () => {
|
||||
it("delivers events and resolves after a later request removes the topic", async () => {
|
||||
const broadcaster = createBroadcaster();
|
||||
const connection = new TestConnection(true, true);
|
||||
const subscribed = broadcaster.subscribe(routeStream(connection), [
|
||||
"items",
|
||||
]);
|
||||
|
||||
await expectPending(subscribed);
|
||||
await broadcaster.publish("items", {
|
||||
type: "item-changed",
|
||||
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();
|
||||
});
|
||||
|
||||
it("resolves fully duplicate subscriptions immediately", async () => {
|
||||
const broadcaster = createBroadcaster();
|
||||
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) => {
|
||||
await firstReleased;
|
||||
await originalFirstSend(message);
|
||||
};
|
||||
second.send = async (message) => {
|
||||
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 () => {
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
|
||||
import { Config } from '../../source/services/config.ts';
|
||||
|
||||
/**
|
||||
* Tests that the config defaults to a 1 MiB request body limit.
|
||||
*/
|
||||
const testConfigDefaultsTo1MiBRequestBodyLimit = (): void => {
|
||||
const config = Config.from({
|
||||
database: {},
|
||||
server: {},
|
||||
auth: {},
|
||||
});
|
||||
|
||||
expect(config.server.maxRequestBodyBytes).toBe(1024 * 1024);
|
||||
expect(config.database.path).toBe('data.db');
|
||||
expect(config.server.port).toBe(3000);
|
||||
expect(config.server.host).toBe('0.0.0.0');
|
||||
expect(config.server.cors.origin).toBe('*');
|
||||
expect(config.server.cors.methods).toEqual([ 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' ]);
|
||||
expect(config.server.cors.allowedHeaders).toEqual([ 'Content-Type', 'cache-control', 'X-Timestamp', 'X-PublicKey', 'X-Signature' ]);
|
||||
expect(config.auth.timestampWindowMs).toBe(300000);
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests that the config loads the request body limit from the environment.
|
||||
*/
|
||||
const testConfigLoadsRequestBodyLimitFromEnvironment = (): void => {
|
||||
vi.stubEnv('SERVER_MAX_REQUEST_BODY_BYTES', '2048');
|
||||
|
||||
expect(Config.fromEnv().server.maxRequestBodyBytes).toBe(2048);
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests that the config rejects an invalid request body limit.
|
||||
*/
|
||||
const testConfigRejectsInvalidRequestBodyLimit = (): void => {
|
||||
expect(() =>
|
||||
Config.from({
|
||||
database: {},
|
||||
server: { maxRequestBodyBytes: '0' },
|
||||
auth: {},
|
||||
})).toThrow();
|
||||
};
|
||||
|
||||
/**
|
||||
* tests that the config loads the database path from the environment.
|
||||
*/
|
||||
const testConfigLoadsDatabasePathFromEnvironment = (): void => {
|
||||
vi.stubEnv('DATABASE_PATH', 'test.db');
|
||||
|
||||
expect(Config.fromEnv().database.path).toBe('test.db');
|
||||
};
|
||||
|
||||
/**
|
||||
* tests that the config loads the server port from the environment.
|
||||
*/
|
||||
const testConfigLoadsServerPortFromEnvironment = (): void => {
|
||||
vi.stubEnv('SERVER_PORT', '3000');
|
||||
|
||||
expect(Config.fromEnv().server.port).toBe(3000);
|
||||
};
|
||||
|
||||
/**
|
||||
* tests that the config loads the server host from the environment.
|
||||
*/
|
||||
const testConfigLoadsServerHostFromEnvironment = (): void => {
|
||||
vi.stubEnv('SERVER_HOST', '0.0.0.0');
|
||||
|
||||
expect(Config.fromEnv().server.host).toBe('0.0.0.0');
|
||||
};
|
||||
|
||||
/**
|
||||
* tests that the config loads the cors configuration from the environment.
|
||||
*/
|
||||
const testConfigLoadsCorsConfigurationFromEnvironment = (): void => {
|
||||
vi.stubEnv('CORS_ORIGIN', '*');
|
||||
|
||||
expect(Config.fromEnv().server.cors.origin).toBe('*');
|
||||
};
|
||||
|
||||
/**
|
||||
* tests that the config loads the cors methods from the environment.
|
||||
*/
|
||||
const testConfigLoadsCorsMethodsFromEnvironment = (): void => {
|
||||
vi.stubEnv('CORS_METHODS', 'GET,POST,PUT,DELETE,OPTIONS');
|
||||
|
||||
expect(Config.fromEnv().server.cors.methods).toEqual([ 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' ]);
|
||||
};
|
||||
|
||||
/**
|
||||
* tests that the config loads the cors allowed headers from the environment.
|
||||
*/
|
||||
const testConfigLoadsCorsAllowedHeadersFromEnvironment = (): void => {
|
||||
vi.stubEnv('CORS_ALLOWED_HEADERS', 'Content-Type,cache-control,X-Timestamp');
|
||||
|
||||
expect(Config.fromEnv().server.cors.allowedHeaders).toEqual([ 'Content-Type', 'cache-control', 'X-Timestamp' ]);
|
||||
};
|
||||
|
||||
/**
|
||||
* tests that the config loads the auth configuration from the environment.
|
||||
*/
|
||||
const testConfigLoadsAuthConfigurationFromEnvironment = (): void => {
|
||||
vi.stubEnv('AUTH_TIMESTAMP_WINDOW_MS', '1000');
|
||||
|
||||
expect(Config.fromEnv().auth.timestampWindowMs).toBe(1000);
|
||||
};
|
||||
|
||||
describe('Config', () => {
|
||||
test('defaults to a 1 MiB request body limit', testConfigDefaultsTo1MiBRequestBodyLimit);
|
||||
test('loads the request body limit from the environment', testConfigLoadsRequestBodyLimitFromEnvironment);
|
||||
test('rejects the invalid request body limit', testConfigRejectsInvalidRequestBodyLimit);
|
||||
test('loads the database path from the environment', testConfigLoadsDatabasePathFromEnvironment);
|
||||
test('loads the server port from the environment', testConfigLoadsServerPortFromEnvironment);
|
||||
test('loads the server host from the environment', testConfigLoadsServerHostFromEnvironment);
|
||||
test('loads the cors configuration from the environment', testConfigLoadsCorsConfigurationFromEnvironment);
|
||||
test('loads the cors methods from the environment', testConfigLoadsCorsMethodsFromEnvironment);
|
||||
test('loads the cors allowed headers from the environment', testConfigLoadsCorsAllowedHeadersFromEnvironment);
|
||||
test('loads the auth configuration from the environment', testConfigLoadsAuthConfigurationFromEnvironment);
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { RouteDefinition, RouteModule } from "../../source/routes/types.js";
|
||||
import { ApplicationError } from "../../source/errors/index.js";
|
||||
import { ApplicationRouter } from "../../source/services/router.js";
|
||||
import { TestConnection } from "../helpers/test-connection.js";
|
||||
|
||||
function moduleWith(routes: RouteDefinition[]): RouteModule {
|
||||
return {
|
||||
async getRoutes() {
|
||||
return routes;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("ApplicationRouter initialization", () => {
|
||||
it("rejects duplicate exact paths during startup", async () => {
|
||||
const route = { url: "/echo", handler: () => undefined };
|
||||
|
||||
await expect(
|
||||
ApplicationRouter.create([moduleWith([route]), moduleWith([route])]),
|
||||
).rejects.toThrow("Duplicate application route: /echo");
|
||||
});
|
||||
|
||||
it.each(["echo", "/", "/items/:id", "/items?active=true", "/items#active"])(
|
||||
"rejects the invalid route path %s",
|
||||
async (url) => {
|
||||
await expect(
|
||||
ApplicationRouter.create([
|
||||
moduleWith([{ url, handler: () => undefined }]),
|
||||
]),
|
||||
).rejects.toThrow("Invalid application route");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("ApplicationRouter dispatch", () => {
|
||||
it("binds the connection, body, and request ID to one route stream", async () => {
|
||||
const connection = new TestConnection(false, false);
|
||||
const router = await ApplicationRouter.create([
|
||||
moduleWith([
|
||||
{
|
||||
url: "/echo",
|
||||
handler: async (stream) => {
|
||||
expect(stream.connection).toBe(connection);
|
||||
await stream.send(stream.body);
|
||||
},
|
||||
},
|
||||
]),
|
||||
]);
|
||||
|
||||
await router.dispatch(
|
||||
{ path: "/echo", body: { value: 1 }, requestId: "request-1" },
|
||||
connection,
|
||||
);
|
||||
|
||||
expect(connection.messages).toEqual([
|
||||
{
|
||||
id: "request-1",
|
||||
type: "response",
|
||||
statusCode: 200,
|
||||
body: { value: 1 },
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(
|
||||
router.dispatch({ path: "/echo/other", body: {} }, connection),
|
||||
).rejects.toMatchObject({ statusCode: 404 });
|
||||
});
|
||||
|
||||
it("preserves correlation when concurrent requests finish out of order", async () => {
|
||||
const completions = new Map<string, () => void>();
|
||||
const router = await ApplicationRouter.create([
|
||||
moduleWith([
|
||||
{
|
||||
url: "/delayed",
|
||||
handler: async (stream) => {
|
||||
const key = (stream.body as { key: string }).key;
|
||||
await new Promise<void>((resolve) => completions.set(key, resolve));
|
||||
await stream.send({ key });
|
||||
},
|
||||
},
|
||||
]),
|
||||
]);
|
||||
const connection = new TestConnection(true, true);
|
||||
|
||||
const first = router.dispatch(
|
||||
{ path: "/delayed", body: { key: "A" }, requestId: "A" },
|
||||
connection,
|
||||
);
|
||||
const second = router.dispatch(
|
||||
{ path: "/delayed", body: { key: "B" }, requestId: "B" },
|
||||
connection,
|
||||
);
|
||||
|
||||
completions.get("B")?.();
|
||||
await second;
|
||||
completions.get("A")?.();
|
||||
await first;
|
||||
|
||||
expect(connection.messages).toEqual([
|
||||
{
|
||||
id: "B",
|
||||
type: "response",
|
||||
statusCode: 200,
|
||||
body: { key: "B" },
|
||||
},
|
||||
{
|
||||
id: "A",
|
||||
type: "response",
|
||||
statusCode: 200,
|
||||
body: { key: "A" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("propagates route failures without infrastructure-specific cleanup", async () => {
|
||||
const error = new Error("route failed");
|
||||
const router = await ApplicationRouter.create([
|
||||
moduleWith([
|
||||
{
|
||||
url: "/failure",
|
||||
handler: () => {
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
]),
|
||||
]);
|
||||
|
||||
await expect(
|
||||
router.dispatch({ path: "/failure" }, new TestConnection(false, false)),
|
||||
).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { HonoSSEStream } from "../../../source/services/stream/hono-sse-stream.js";
|
||||
import { HttpRequestStream } from "../../../source/services/stream/http-request-stream.js";
|
||||
import { WSStream } from "../../../source/services/stream/ws-stream.js";
|
||||
|
||||
describe("stream lifecycle observers", () => {
|
||||
it("buffers exactly one normal HTTP response", async () => {
|
||||
const stream = new HttpRequestStream();
|
||||
|
||||
await stream.send({
|
||||
type: "response",
|
||||
statusCode: 200,
|
||||
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");
|
||||
});
|
||||
|
||||
it("notifies WebSocket observers registered after remote closure", () => {
|
||||
const stream = new WSStream({
|
||||
send: vi.fn(),
|
||||
close: vi.fn(),
|
||||
readyState: 1,
|
||||
});
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
import { Hono } from "hono";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { RouteDefinition } from "../../../source/routes/types.js";
|
||||
import { ApplicationError } from "../../../source/errors/index.js";
|
||||
import { ApplicationRouter } from "../../../source/services/router.js";
|
||||
import { Broadcaster } from "../../../source/services/broadcaster.js";
|
||||
import { HttpTransportRouter } from "../../../source/services/transport/http-transport.js";
|
||||
import type { AppEnv } from "../../../source/services/transport/transport-router.js";
|
||||
import { fromExtendedJson, toExtendedJson } from "@xo-cash/utils";
|
||||
import { Logger } from "../../../source/utils/logger.js";
|
||||
import { ServerHost } from "../../../source/services/server-host.js";
|
||||
|
||||
async function createApp(
|
||||
routes: RouteDefinition[] | ((broadcaster: Broadcaster) => RouteDefinition[]),
|
||||
maxRequestBodyBytes = 1024 * 1024,
|
||||
): Promise<Hono<AppEnv>> {
|
||||
const debug = new Logger("http-transport-test");
|
||||
const broadcaster = new Broadcaster(debug);
|
||||
const resolvedRoutes =
|
||||
typeof routes === "function" ? routes(broadcaster) : routes;
|
||||
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",
|
||||
handler: async (stream) => 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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { WebSocketServer } from "ws";
|
||||
|
||||
import { ApplicationRouter } from "../../../source/services/router.js";
|
||||
import {
|
||||
WsTransportRouter,
|
||||
} from "../../../source/services/transport/ws-transport.js";
|
||||
import { Logger } from "../../../source/utils/logger.js";
|
||||
import { toExtendedJson } from "@xo-cash/utils";
|
||||
|
||||
describe("WebSocket request decoding", () => {
|
||||
it("decodes the minimal route-agnostic envelope and Extended JSON body", async () => {
|
||||
await expect(
|
||||
WsTransportRouter.decodeWebSocketRequest(
|
||||
toExtendedJson({
|
||||
id: "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([
|
||||
"{}",
|
||||
'{"path":42}',
|
||||
'{"path":"/data/get","id":1}',
|
||||
'{"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 () => {
|
||||
await expect(WsTransportRouter.decodeWebSocketRequest("{")).rejects.toMatchObject({
|
||||
statusCode: 400,
|
||||
message: "Invalid JSON in WebSocket message",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("WsTransportRouter payload limits", () => {
|
||||
it("configures Hono's ws server with the requested maxPayload", async () => {
|
||||
const debug = new Logger("ws-transport-test");
|
||||
const router = await ApplicationRouter.create([]);
|
||||
const transport = new WsTransportRouter(router, debug, 1024);
|
||||
const wsServer = transport.websocketServer as unknown as WebSocketServer;
|
||||
|
||||
expect(wsServer.options.maxPayload).toBe(1024);
|
||||
await transport.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { RouteDefinition, RouteModule } from "../source/routes/types.js";
|
||||
import { ApplicationRouter } from "../source/services/router.js";
|
||||
import { Broadcaster } from "../source/services/broadcaster.js";
|
||||
import { Logger } from "../source/utils/logger.js";
|
||||
import { TestConnection } from "./helpers/test-connection.js";
|
||||
|
||||
function moduleWith(routes: RouteDefinition[]): RouteModule {
|
||||
return {
|
||||
async getRoutes() {
|
||||
return routes;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function expectPending(promise: Promise<void>): Promise<void> {
|
||||
const settled = vi.fn();
|
||||
void promise.then(settled);
|
||||
await Promise.resolve();
|
||||
expect(settled).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
describe("long-lived subscription dispatch", () => {
|
||||
it("allows duplicate subscribe and unsubscribe requests while the original request waits", async () => {
|
||||
const broadcaster = new Broadcaster(new Logger("subscription-flow-test"));
|
||||
const router = await ApplicationRouter.create([
|
||||
moduleWith([
|
||||
{
|
||||
url: "/items/subscribe",
|
||||
handler: async (stream) => {
|
||||
await broadcaster.subscribe(stream, ["items"]);
|
||||
},
|
||||
},
|
||||
{
|
||||
url: "/items/unsubscribe",
|
||||
handler: async (stream) => {
|
||||
await broadcaster.unsubscribe(stream, ["items"]);
|
||||
await stream.send({});
|
||||
},
|
||||
},
|
||||
]),
|
||||
]);
|
||||
const connection = new TestConnection(true, true);
|
||||
|
||||
const original = router.dispatch(
|
||||
{ path: "/items/subscribe", requestId: "subscribe-1" },
|
||||
connection,
|
||||
);
|
||||
await vi.waitFor(() => expect(connection.closeCallbacks).toHaveLength(1));
|
||||
await expectPending(original);
|
||||
|
||||
// This request uses a different ApplicationRouteStream over the same
|
||||
// connection. Since the topic already exists, its dispatch completes.
|
||||
await router.dispatch(
|
||||
{ path: "/items/subscribe", requestId: "subscribe-2" },
|
||||
connection,
|
||||
);
|
||||
await expectPending(original);
|
||||
|
||||
await router.dispatch(
|
||||
{ path: "/items/unsubscribe", requestId: "unsubscribe-1" },
|
||||
connection,
|
||||
);
|
||||
await original;
|
||||
|
||||
expect(connection.messages).toEqual([
|
||||
{
|
||||
id: "unsubscribe-1",
|
||||
type: "response",
|
||||
statusCode: 200,
|
||||
body: {},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Logger } from '../../source/utils/logger.ts';
|
||||
import { expect, describe, test } from 'vitest';
|
||||
|
||||
/**
|
||||
* Tests that a logger function is created and that it is a logger.
|
||||
*/
|
||||
const testLoggerCreatesLoggerFunction = (): void => {
|
||||
const logger = new Logger('test');
|
||||
expect(logger).toBeDefined();
|
||||
expect(logger.namespace).toBe('test');
|
||||
|
||||
expect(Logger.isLogger(logger)).toBe(true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests that a logger function is a logger.
|
||||
*/
|
||||
const testLoggerFunctionIsLogger = (): void => {
|
||||
const logger = new Logger('test');
|
||||
expect(Logger.isLogger(logger)).toBe(true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests that a logger extends.
|
||||
*/
|
||||
const testLoggerExtends = (): void => {
|
||||
const logger = new Logger('test');
|
||||
const extendedLogger = logger.extend('extended');
|
||||
expect(extendedLogger.namespace).toBe('test:extended');
|
||||
expect(Logger.isLogger(extendedLogger)).toBe(true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests that a logger is a logger.
|
||||
*/
|
||||
const testLoggerIsLogger = (): void => {
|
||||
const logger = new Logger('test');
|
||||
expect(Logger.isLogger(logger)).toBe(true);
|
||||
|
||||
// Test not a logger
|
||||
const notALogger = [ 'not a logger', 123, true, false, null, undefined, NaN, Infinity, -Infinity ];
|
||||
|
||||
for (const item of notALogger) {
|
||||
expect(Logger.isLogger(item)).toBe(false);
|
||||
}
|
||||
};
|
||||
|
||||
describe('Logger', () => {
|
||||
test('creates a logger function', testLoggerCreatesLoggerFunction);
|
||||
test('logger function is a logger', testLoggerFunctionIsLogger);
|
||||
test('logger extends', testLoggerExtends);
|
||||
test('logger is logger', testLoggerIsLogger);
|
||||
});
|
||||
Reference in New Issue
Block a user