This commit is contained in:
2026-09-02 10:03:55 +00:00
8 changed files with 241 additions and 159 deletions
+113 -29
View File
@@ -1,9 +1,35 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import type { RouteDefinition, RouteModule } from '../../source/routes/types.ts';
import { ApplicationRouter } from '../../source/services/router.ts';
import { TestConnection } from '../helpers/test-connection.ts';
import type { AuthSecp256k1 } from '../../source/auth/auth.ts';
/**
* A controlled request is a request that is controlled by the test.
* It is used to control the request flow and ensure that the request is completed in the correct order.
*/
type ControlledRequest = {
request: Promise<void>;
started: Promise<void>;
release: () => void;
};
/**
* A mock of the AuthSecp256k1 service
*/
const auth = {
verifySignature: vi.fn().mockResolvedValue(true),
verifyUniqueRequest: vi.fn().mockResolvedValue(true),
assertTimestampFreshness: vi.fn().mockResolvedValue(true),
} as unknown as AuthSecp256k1;
/**
* A helper function to create a route module with the given routes
* @param routes - The routes to create the module with
* @returns The created route module
*/
const moduleWith = (routes: RouteDefinition[]): RouteModule => {
return {
async getRoutes(): Promise<RouteDefinition[]> {
@@ -16,75 +42,130 @@ describe('ApplicationRouter initialization', (): void => {
it('rejects duplicate exact paths during startup', async (): Promise<void> => {
const route = { url: '/echo', handler: (): void => undefined };
await expect(ApplicationRouter.create([ moduleWith([ route ]), moduleWith([ route ]) ])).rejects.toThrow('Duplicate application route: /echo');
await expect(ApplicationRouter.create({ auth }, [ 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): Promise<void> => {
await expect(ApplicationRouter.create([ moduleWith([{ url, handler: (): void => undefined }]) ])).rejects.toThrow('Invalid application route');
await expect(ApplicationRouter.create({ auth }, [ moduleWith([{ url, handler: (): void => undefined }]) ])).rejects.toThrow('Invalid application route');
});
});
describe('ApplicationRouter dispatch', (): void => {
it('binds the connection, body, and request ID to one route stream', async (): Promise<void> => {
const connection = new TestConnection(false, false);
const router = await ApplicationRouter.create([
const router = await ApplicationRouter.create({ auth }, [
moduleWith([
{
url: '/echo',
handler: async (stream): Promise<void> => {
expect(stream.connection).toBe(connection);
expect(stream.path).toBe('/echo');
expect(stream.headers).toEqual({ 'x-request-token': 'route-1' });
expect(stream.headers).toEqual({ 'x-public-key': 'public-key', 'x-signature': 'signature', 'x-timestamp': '1000' });
await stream.send(stream.body);
},
},
]),
]);
await router.dispatch({ path: '/echo', body: { value: 1 }, requestId: 'request-1', headers: { 'x-request-token': 'route-1' } }, connection);
await router.dispatch(
{
path: '/echo',
body: { value: 1 },
requestId: '1',
headers: { 'x-public-key': 'public-key', 'x-signature': 'signature', 'x-timestamp': '1000' },
},
connection,
);
expect(connection.messages).toEqual([
{
id: 'request-1',
id: '1',
type: 'response',
statusCode: 200,
body: { value: 1 },
},
]);
await expect(router.dispatch({ path: '/echo/other', body: {} }, connection)).rejects.toMatchObject({ statusCode: 404 });
await expect(router.dispatch(
{ path: '/echo/other', body: {}, headers: { 'x-public-key': 'public-key', 'x-signature': 'signature', 'x-timestamp': '1000' } },
connection,
)).rejects.toMatchObject({ statusCode: 404 });
});
it('preserves correlation when concurrent requests finish out of order', async (): Promise<void> => {
const completions = new Map<string, () => void>();
const router = await ApplicationRouter.create([
const router = await ApplicationRouter.create({ auth }, [
moduleWith([
{
url: '/delayed',
handler: async (stream): Promise<void> => {
const key = (stream.body as { key: string }).key;
const token = stream.headers['x-request-token'];
await new Promise<void>((resolve) => completions.set(key, resolve));
await stream.send({ key, token });
const { key, signalStarted, released } = stream.body as {
key: string;
signalStarted: () => void;
released: Promise<void>;
};
signalStarted();
await released;
await stream.send({ key });
},
},
]),
]);
const connection = new TestConnection(true, true);
const first = router.dispatch(
{ path: '/delayed', body: { key: 'A' }, requestId: 'A', headers: { 'x-request-token': 'token-a' } },
connection,
);
const second = router.dispatch(
{ path: '/delayed', body: { key: 'B' }, requestId: 'B', headers: { 'x-request-token': 'token-b' } },
connection,
);
const connection = new TestConnection(false, false);
completions.get('B')?.();
await second;
completions.get('A')?.();
await first;
const createControlledRequest = (key: string): ControlledRequest => {
const { promise: started, resolve: signalStarted } = Promise.withResolvers<void>();
const { promise: released, resolve: release } = Promise.withResolvers<void>();
const request = router.dispatch(
{
path: '/delayed',
body: {
key,
signalStarted,
released,
},
requestId: key,
headers: {
'x-public-key': 'public-key',
'x-signature': 'signature',
'x-timestamp': '1000',
},
},
connection,
);
return {
request,
started,
release,
};
};
const first = createControlledRequest('A');
const second = createControlledRequest('B');
expect(connection.messages).toEqual([]);
await Promise.all([ first.started, second.started ]);
second.release();
await second.request;
expect(connection.messages).toEqual([
{
id: 'B',
type: 'response',
statusCode: 200,
body: { key: 'B' },
},
]);
first.release();
await first.request;
expect(connection.messages).toEqual([
{
@@ -104,7 +185,7 @@ describe('ApplicationRouter dispatch', (): void => {
it('propagates route failures without infrastructure-specific cleanup', async (): Promise<void> => {
const error = new Error('route failed');
const router = await ApplicationRouter.create([
const router = await ApplicationRouter.create({ auth }, [
moduleWith([
{
url: '/failure',
@@ -115,6 +196,9 @@ describe('ApplicationRouter dispatch', (): void => {
]),
]);
await expect(router.dispatch({ path: '/failure' }, new TestConnection(false, false))).rejects.toBe(error);
await expect(router.dispatch(
{ path: '/failure', headers: { 'x-public-key': 'public-key', 'x-signature': 'signature', 'x-timestamp': '1000' } },
new TestConnection(false, false),
)).rejects.toBe(error);
});
});