36b0929fae
* Add server beta runtime foundation * Address server beta review findings * Resolve server beta review comments * Tighten server beta review follow-ups * Harden server beta auth and search * Avoid unnecessary FTS rebuilds * Block scoped keys from creating projects * Release BullMQ claims best effort on close * Address server beta review blockers * Reset BullMQ claims best effort * Add Postgres observation storage foundation * feat(server-beta): add independent runtime service Introduce src/server/runtime/ as a self-contained server-beta runtime that owns its lifecycle, Postgres bootstrap, and HTTP boundary without depending on WorkerService. ServerBetaService wraps the existing Server class, exposes /healthz and /v1/info with runtime="server-beta", and persists state to dedicated paths (.server-beta.pid|.port|.runtime.json). The four boundary managers (queue, generation worker, provider registry, event broadcaster) are intentionally disabled in this phase and report their status through /v1/info; later phases activate them. Adds plans/2026-05-07-finish-bullmq-branch-ship-plan.md to track the remaining work for this branch. Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(server-beta): route CLI lifecycle and bundle separate runtime scripts/build-hooks.js now produces plugin/scripts/server-beta-service.cjs as a separate Node CJS bundle, alongside the existing worker-service bundle. The server-beta runtime is now installable independently. src/npx-cli/commands/server.ts routes start|stop|restart|status to the server-beta lifecycle instead of the legacy worker. The worker keeps its own start|stop|restart|status under the worker namespace; the two runtimes can be operated independently. src/services/worker-service.ts adds a server-* command parser branch that delegates to the sibling server-beta-service.cjs bundle so direct worker-service invocations still route to the right runtime. tests/npx-cli-server-namespace.test.ts updated to expect server-beta lifecycle routing. Includes rebuilt plugin/scripts/*.cjs bundles produced by build-and-sync. Phase 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(server-beta): add BullMQ job queue primitives Introduce src/server/jobs/ as the queue-side primitives that Phase 3 of the server-beta runtime needs to operate. types.ts defines a discriminated union over the four job kinds (event, event-batch, summary, reindex) and maps each to a per-kind BullMQ queue name and deterministic-ID prefix. job-id.ts builds deterministic, colon-free BullMQ jobIds from (kind, team, project, source). The colon ban exists because BullMQ uses ':' as a Redis key separator internally; embedding ':' in jobIds breaks scan and state lookups. ServerJobQueue.ts is a thin wrapper over BullMQ Queue + Worker that enforces autorun:false, default concurrency 1, and an attached error listener — all per BullMQ docs requirements. Test seams accept queue and worker factories so unit tests do not need Redis. outbox.ts publishes through the Postgres ObservationGenerationJob repository as canonical history. enqueueOutbox writes the row first, then publishes to BullMQ; if BullMQ throws, the row is transitioned to failed and a failed event is appended. reconcileOnStartup re-enqueues queued + processing rows after a restart, replacing terminal BullMQ jobs that may still be holding the deterministic ID slot. markCompleted and markFailed wrap transitionStatus and append the matching event row. Includes 20 unit tests covering deterministic ID stability, colon-free output, queue lifecycle, error-listener attachment, double-start refusal, idempotent enqueue, BullMQ failure rollback, startup reconciliation, max-attempts skipping, and completion / failure / retry transitions. Phase 3 commit 1 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(server-beta): activate queue boundary in runtime service Wire ActiveServerBetaQueueManager into the server-beta runtime graph. The active manager owns one ServerJobQueue per generation kind (event, event-batch, summary, reindex) and surfaces lane metadata through boundary health. Selection is opt-in and fail-fast: if CLAUDE_MEM_QUEUE_ENGINE is set to bullmq the active manager is constructed (and any Redis/config error throws — no silent fallback to SQLite, per Phase 3 anti-pattern guard). For any other engine the disabled boundary remains so worker-era and test setups stay compatible. Widens ServerBetaBoundaryHealth.status to a discriminated union ('disabled' | 'active' | 'errored') with optional details. The disabled adapter still emits status='disabled', which keeps the existing server-beta-service test green. ServerBetaService receives the manager through a new optional queueManager field on CreateServerBetaServiceOptions so test graphs and Phase 4 wiring can inject custom managers. Adds tests/server/runtime/active-queue-manager.test.ts covering bullmq guard, active health shape, per-kind queue access, close behavior, and post-close errored health. Phase 3 commit 2 of plans/2026-05-07-server-beta-independent-bullmq-observation-runtime.md. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(server-beta): cap /v1/events/batch at 500 events Prevents unbounded array DoS surface flagged in PR review. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
420 lines
12 KiB
TypeScript
420 lines
12 KiB
TypeScript
import { describe, it, expect, mock, beforeEach, afterEach, spyOn } from 'bun:test';
|
|
import { logger } from '../../src/utils/logger.js';
|
|
|
|
import { Server } from '../../src/services/server/Server.js';
|
|
import type { RouteHandler, ServerOptions } from '../../src/services/server/Server.js';
|
|
|
|
let loggerSpies: ReturnType<typeof spyOn>[] = [];
|
|
|
|
describe('Server', () => {
|
|
let server: Server;
|
|
let mockOptions: ServerOptions;
|
|
|
|
beforeEach(() => {
|
|
loggerSpies = [
|
|
spyOn(logger, 'info').mockImplementation(() => {}),
|
|
spyOn(logger, 'debug').mockImplementation(() => {}),
|
|
spyOn(logger, 'warn').mockImplementation(() => {}),
|
|
spyOn(logger, 'error').mockImplementation(() => {}),
|
|
];
|
|
|
|
mockOptions = {
|
|
getInitializationComplete: () => true,
|
|
getMcpReady: () => true,
|
|
onShutdown: mock(() => Promise.resolve()),
|
|
onRestart: mock(() => Promise.resolve()),
|
|
workerPath: '/test/worker-service.cjs',
|
|
getAiStatus: () => ({
|
|
provider: 'claude',
|
|
authMethod: 'cli',
|
|
lastInteraction: null,
|
|
}),
|
|
};
|
|
});
|
|
|
|
afterEach(async () => {
|
|
loggerSpies.forEach(spy => spy.mockRestore());
|
|
if (server && server.getHttpServer()) {
|
|
try {
|
|
await server.close();
|
|
} catch {
|
|
// Ignore errors on cleanup
|
|
}
|
|
}
|
|
mock.restore();
|
|
});
|
|
|
|
describe('constructor', () => {
|
|
it('should create Express app', () => {
|
|
server = new Server(mockOptions);
|
|
|
|
expect(server.app).toBeDefined();
|
|
expect(typeof server.app.get).toBe('function');
|
|
expect(typeof server.app.post).toBe('function');
|
|
expect(typeof server.app.use).toBe('function');
|
|
});
|
|
|
|
it('should expose app as readonly property', () => {
|
|
server = new Server(mockOptions);
|
|
|
|
expect(server.app).toBeDefined();
|
|
|
|
expect(typeof server.app.listen).toBe('function');
|
|
});
|
|
|
|
it('should register pre-body-parser routes before normal middleware', async () => {
|
|
server = new Server({
|
|
...mockOptions,
|
|
preBodyParserRoutes: [{
|
|
setupRoutes(app) {
|
|
app.post('/api/auth/*splat', (req, res) => {
|
|
res.json({
|
|
bodyParsed: req.body !== undefined,
|
|
});
|
|
});
|
|
},
|
|
}],
|
|
});
|
|
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/auth/session`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Origin: 'http://localhost:37777',
|
|
},
|
|
body: JSON.stringify({ ok: true }),
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(response.headers.get('access-control-allow-origin')).toBe('http://localhost:37777');
|
|
|
|
const body = await response.json();
|
|
expect(body.bodyParsed).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('listen', () => {
|
|
it('should start server on specified port', async () => {
|
|
server = new Server(mockOptions);
|
|
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const httpServer = server.getHttpServer();
|
|
expect(httpServer).not.toBeNull();
|
|
expect(httpServer!.listening).toBe(true);
|
|
});
|
|
|
|
it('should reject if port is already in use', async () => {
|
|
server = new Server(mockOptions);
|
|
const server2 = new Server(mockOptions);
|
|
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
await expect(server2.listen(testPort, '127.0.0.1')).rejects.toThrow();
|
|
|
|
const httpServer = server2.getHttpServer();
|
|
if (httpServer) {
|
|
expect(httpServer.listening).toBe(false);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('close', () => {
|
|
it('should stop server from listening after close', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const httpServerBefore = server.getHttpServer();
|
|
expect(httpServerBefore).not.toBeNull();
|
|
expect(httpServerBefore!.listening).toBe(true);
|
|
|
|
try {
|
|
await server.close();
|
|
} catch (e: any) {
|
|
if (e.code !== 'ERR_SERVER_NOT_RUNNING') {
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
const httpServerAfter = server.getHttpServer();
|
|
if (httpServerAfter) {
|
|
expect(httpServerAfter.listening).toBe(false);
|
|
}
|
|
});
|
|
|
|
it('should handle close when server not started', async () => {
|
|
server = new Server(mockOptions);
|
|
|
|
await expect(server.close()).resolves.toBeUndefined();
|
|
});
|
|
|
|
it('should allow starting a new server on same port after close', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
try {
|
|
await server.close();
|
|
} catch (e: any) {
|
|
if (e.code !== 'ERR_SERVER_NOT_RUNNING') {
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
await new Promise(resolve => setTimeout(resolve, 100));
|
|
|
|
const server2 = new Server(mockOptions);
|
|
await server2.listen(testPort, '127.0.0.1');
|
|
|
|
expect(server2.getHttpServer()!.listening).toBe(true);
|
|
|
|
try {
|
|
await server2.close();
|
|
} catch {
|
|
// Ignore cleanup errors
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('getHttpServer', () => {
|
|
it('should return null before listen', () => {
|
|
server = new Server(mockOptions);
|
|
|
|
expect(server.getHttpServer()).toBeNull();
|
|
});
|
|
|
|
it('should return http.Server after listen', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const httpServer = server.getHttpServer();
|
|
expect(httpServer).not.toBeNull();
|
|
expect(httpServer!.listening).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('registerRoutes', () => {
|
|
it('should call setupRoutes on route handler', () => {
|
|
server = new Server(mockOptions);
|
|
|
|
const setupRoutesMock = mock(() => {});
|
|
const mockRouteHandler: RouteHandler = {
|
|
setupRoutes: setupRoutesMock,
|
|
};
|
|
|
|
server.registerRoutes(mockRouteHandler);
|
|
|
|
expect(setupRoutesMock).toHaveBeenCalledTimes(1);
|
|
expect(setupRoutesMock).toHaveBeenCalledWith(server.app);
|
|
});
|
|
|
|
it('should register multiple route handlers', () => {
|
|
server = new Server(mockOptions);
|
|
|
|
const handler1Mock = mock(() => {});
|
|
const handler2Mock = mock(() => {});
|
|
|
|
const handler1: RouteHandler = { setupRoutes: handler1Mock };
|
|
const handler2: RouteHandler = { setupRoutes: handler2Mock };
|
|
|
|
server.registerRoutes(handler1);
|
|
server.registerRoutes(handler2);
|
|
|
|
expect(handler1Mock).toHaveBeenCalledTimes(1);
|
|
expect(handler2Mock).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
|
|
describe('finalizeRoutes', () => {
|
|
it('should not throw when called', () => {
|
|
server = new Server(mockOptions);
|
|
|
|
expect(() => server.finalizeRoutes()).not.toThrow();
|
|
});
|
|
});
|
|
|
|
describe('health endpoint', () => {
|
|
it('should return 200 with status ok', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
const body = await response.json();
|
|
expect(body.status).toBe('ok');
|
|
});
|
|
|
|
it('should include initialization status', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
|
|
const body = await response.json();
|
|
|
|
expect(body.initialized).toBe(true);
|
|
expect(body.mcpReady).toBe(true);
|
|
});
|
|
|
|
it('should reflect initialization state changes', async () => {
|
|
let isInitialized = false;
|
|
const dynamicOptions: ServerOptions = {
|
|
getInitializationComplete: () => isInitialized,
|
|
getMcpReady: () => true,
|
|
onShutdown: mock(() => Promise.resolve()),
|
|
onRestart: mock(() => Promise.resolve()),
|
|
workerPath: '/test/worker-service.cjs',
|
|
getAiStatus: () => ({ provider: 'claude', authMethod: 'cli', lastInteraction: null }),
|
|
};
|
|
|
|
server = new Server(dynamicOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
let response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
|
|
let body = await response.json();
|
|
expect(body.initialized).toBe(false);
|
|
|
|
isInitialized = true;
|
|
|
|
response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
|
|
body = await response.json();
|
|
expect(body.initialized).toBe(true);
|
|
});
|
|
|
|
it('should include platform and pid', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
|
|
const body = await response.json();
|
|
|
|
expect(body.platform).toBeDefined();
|
|
expect(body.pid).toBeDefined();
|
|
expect(typeof body.pid).toBe('number');
|
|
});
|
|
|
|
it('should return degraded health when BullMQ Redis health is errored', async () => {
|
|
server = new Server({
|
|
...mockOptions,
|
|
getQueueHealth: () => ({
|
|
engine: 'bullmq',
|
|
redis: {
|
|
status: 'error',
|
|
mode: 'external',
|
|
host: '127.0.0.1',
|
|
port: 6379,
|
|
prefix: 'test_prefix',
|
|
error: 'connection refused',
|
|
},
|
|
}),
|
|
});
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
|
|
const body = await response.json();
|
|
|
|
expect(response.status).toBe(503);
|
|
expect(body.status).toBe('degraded');
|
|
expect(body.queue.redis.status).toBe('error');
|
|
});
|
|
});
|
|
|
|
describe('readiness endpoint', () => {
|
|
it('should return 200 when initialized', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/readiness`);
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
const body = await response.json();
|
|
expect(body.status).toBe('ready');
|
|
});
|
|
|
|
it('should return 503 when not initialized', async () => {
|
|
const uninitializedOptions: ServerOptions = {
|
|
getInitializationComplete: () => false,
|
|
getMcpReady: () => false,
|
|
onShutdown: mock(() => Promise.resolve()),
|
|
onRestart: mock(() => Promise.resolve()),
|
|
workerPath: '/test/worker-service.cjs',
|
|
getAiStatus: () => ({ provider: 'claude', authMethod: 'cli', lastInteraction: null }),
|
|
};
|
|
|
|
server = new Server(uninitializedOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/readiness`);
|
|
|
|
expect(response.status).toBe(503);
|
|
|
|
const body = await response.json();
|
|
expect(body.status).toBe('initializing');
|
|
expect(body.message).toBeDefined();
|
|
});
|
|
});
|
|
|
|
describe('version endpoint', () => {
|
|
it('should return 200 with version', async () => {
|
|
server = new Server(mockOptions);
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/version`);
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
const body = await response.json();
|
|
expect(body.version).toBeDefined();
|
|
expect(typeof body.version).toBe('string');
|
|
});
|
|
});
|
|
|
|
describe('404 handling', () => {
|
|
it('should return 404 for unknown routes after finalizeRoutes', async () => {
|
|
server = new Server(mockOptions);
|
|
server.finalizeRoutes();
|
|
|
|
const testPort = 40000 + Math.floor(Math.random() * 10000);
|
|
await server.listen(testPort, '127.0.0.1');
|
|
|
|
const response = await fetch(`http://127.0.0.1:${testPort}/api/nonexistent`);
|
|
|
|
expect(response.status).toBe(404);
|
|
|
|
const body = await response.json();
|
|
expect(body.error).toBe('NotFound');
|
|
});
|
|
});
|
|
});
|