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,120 @@
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
|
||||
import { Config } from '../../src/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,53 @@
|
||||
import { Logger } from '../../src/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