@juspay/neurolink
Version:
The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002
882 lines (881 loc) • 36.7 kB
JavaScript
/**
* Abstract Server Adapter
* Base class for all framework-specific server adapters
* Follows NeuroLink's composition and factory patterns
*/
import { EventEmitter } from "events";
import { getMetricsAggregator, SpanSerializer, SpanStatus, SpanType, } from "../../observability/index.js";
import { withTimeout } from "../../utils/errorHandling.js";
import { MAX_TIMER_MS } from "../../constants/timeouts.js";
import { logger } from "../../utils/logger.js";
import { markContextCarried } from "../utils/carriedContextMark.js";
import { isLoopbackAddress } from "../utils/clientAddress.js";
import { pathStartsWithSegment } from "../utils/pathMatch.js";
import { tryImport } from "../../utils/tryImport.js";
import { ConfigurationError, DrainTimeoutError, InvalidLifecycleStateError, MissingDependencyError, ServerAdapterError, ServerTimeoutError, ShutdownTimeoutError, } from "../errors.js";
/** The interface an adapter binds unless told otherwise: this host only. */
export const DEFAULT_SERVER_HOST = "127.0.0.1";
/**
* Abstract base class for server adapters
* Provides common functionality and defines the interface for framework-specific implementations
*/
export class BaseServerAdapter extends EventEmitter {
config;
redactionConfig;
neurolink;
toolRegistry;
externalServerManager;
routes = new Map();
middlewares = [];
isRunning = false;
startTime;
// Adapters build their framework app lazily in initialize(), so routes and
// middleware registered before that are queued here and replayed once the
// app exists — middleware first, so it still guards those routes.
frameworkReady = false;
pendingMiddlewares = [];
pendingRouteKeys = new Set();
// Lifecycle management properties
lifecycleState = "uninitialized";
activeConnections = new Map();
shutdownConfig;
// Set by enableMiddlewareStateCarry(); the carryMiddlewareState option is the
// other way in.
carryRequestedByRoutes = false;
// Set by noteSensitiveRoutes(); read when the server starts.
sensitiveRoutesRegistered = false;
sensitiveRoutesAllowedOpen = false;
constructor(neurolink, config = {}) {
super();
this.neurolink = neurolink;
this.toolRegistry = neurolink.getToolRegistry();
this.externalServerManager = neurolink.getExternalServerManager();
// Store redaction config (optional, disabled by default)
this.redactionConfig = config.redaction;
// Apply shutdown defaults
this.shutdownConfig = {
gracefulShutdownTimeoutMs: config.shutdown?.gracefulShutdownTimeoutMs ?? 30000,
drainTimeoutMs: config.shutdown?.drainTimeoutMs ?? 15000,
forceClose: config.shutdown?.forceClose ?? true,
};
// Apply defaults
this.config = {
port: config.port ?? 3000,
// Loopback unless the operator names an interface: the routes run tools
// and remove MCP servers, so reachability is opt-in.
host: config.host ?? DEFAULT_SERVER_HOST,
basePath: config.basePath ?? "/api",
cors: {
enabled: config.cors?.enabled ?? true,
// No origin by default: a browser page may call this server only
// from an origin the operator listed, or from any origin with an
// explicit ["*"]. The adapters honour the wildcard, so it is opt-in.
origins: config.cors?.origins ?? [],
methods: config.cors?.methods ?? [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"OPTIONS",
],
headers: config.cors?.headers ?? [
"Content-Type",
"Authorization",
"X-Request-ID",
// The session middleware's default header: without it a browser
// client on another origin could not send it.
"X-Session-Id",
],
credentials: config.cors?.credentials ?? false,
maxAge: config.cors?.maxAge ?? 86400,
},
rateLimit: {
enabled: config.rateLimit?.enabled ?? true,
windowMs: config.rateLimit?.windowMs ?? 15 * 60 * 1000, // 15 minutes
maxRequests: config.rateLimit?.maxRequests ?? 100,
message: config.rateLimit?.message ??
"Too many requests, please try again later",
skipPaths: config.rateLimit?.skipPaths,
keyGenerator: config.rateLimit?.keyGenerator,
trustProxy: config.rateLimit?.trustProxy ?? false,
trustedProxies: config.rateLimit?.trustedProxies ?? [],
},
bodyParser: {
enabled: config.bodyParser?.enabled ?? true,
maxSize: config.bodyParser?.maxSize ?? "10mb",
jsonLimit: config.bodyParser?.jsonLimit ?? "10mb",
// An operator's explicit maxSize also caps raw uploads.
rawMaxSize: config.bodyParser?.rawMaxSize ?? config.bodyParser?.maxSize ?? "64mb",
urlEncoded: config.bodyParser?.urlEncoded ?? true,
},
logging: {
enabled: config.logging?.enabled ?? true,
level: config.logging?.level ?? "info",
includeBody: config.logging?.includeBody ?? false,
includeResponse: config.logging?.includeResponse ?? false,
},
timeout: config.timeout ?? 30000,
enableMetrics: config.enableMetrics ?? true,
enableSwagger: config.enableSwagger ?? false,
disableBuiltInHealth: config.disableBuiltInHealth ?? false,
shutdown: this.shutdownConfig,
carryMiddlewareState: config.carryMiddlewareState ?? false,
};
// A wildcard origin with credentials is what the CORS specification
// forbids and what an adapter reflecting the request's Origin would grant:
// any page could make credentialed calls. Refuse it for every adapter.
if (this.config.cors.enabled &&
this.config.cors.credentials &&
this.config.cors.origins.includes("*")) {
throw new ConfigurationError('cors.credentials cannot be combined with the wildcard origin "*"; list the origins that may send credentials', { origins: this.config.cors.origins });
}
}
/**
* Whether middleware marked `authenticates: true` is registered (the
* built-in authentication middleware marks itself). The tool and MCP
* execution routes ask on every request; `registerAllRoutes()` wires them.
*/
hasAuthenticationMiddleware() {
return this.middlewares.some((middleware) => middleware.authenticates === true);
}
/**
* Called by `registerAllRoutes()`: routes that act on the host (tool and
* MCP execution) are mounted, so `start()` warns when no authentication
* middleware guards them. The check runs at start, when the middleware set
* is final, so registering authentication after the routes is fine.
*/
noteSensitiveRoutes(options) {
this.sensitiveRoutesRegistered = true;
if (options?.allowUnauthenticated) {
this.sensitiveRoutesAllowedOpen = true;
}
}
/**
* The warning promised by `noteSensitiveRoutes()`, always on stderr: a
* `logger.warn` is dropped unless debug logging is on, which would hide a
* notice meant for the operator who just started the server.
*/
warnIfSensitiveRoutesUnauthenticated() {
if (!this.sensitiveRoutesRegistered ||
this.sensitiveRoutesAllowedOpen ||
this.hasAuthenticationMiddleware()) {
return;
}
const where = isLoopbackAddress(this.config.host)
? `loopback only (${this.config.host})`
: `${this.config.host}, reachable from the network`;
logger.alwaysStderr(`[ServerAdapter] WARNING: no authentication middleware is registered and the server listens on ${where}. ` +
"The tool and MCP execution routes answer 403 until authentication middleware (marked authenticates: true) is registered, " +
"or allowUnauthenticated: true / NEUROLINK_SERVER_ALLOW_UNAUTHENTICATED=1 opts out of that gate.");
}
/**
* Give the handler a way to notice that the client is gone or the request
* is over time. The controller is this request's own unless middleware
* already attached one that the adapter carried; `applyTimeout` arms the
* configured request timeout, which the caller leaves off for a streaming
* route (a stream legitimately outlives it, as under Hono's own timeout
* middleware). `release()` disarms the timer once the response is written.
*/
attachRequestAbort(ctx, options) {
const controller = ctx.abortController ?? new AbortController();
ctx.abortController = controller;
ctx.abortSignal = controller.signal;
let timedOut = false;
let timer;
const timeoutMs = this.config.timeout;
// Node turns an over-range delay into 1 ms; keep long request budgets
// at the timer limit, as the readiness deadline does through withTimeout.
const delayMs = timeoutMs > MAX_TIMER_MS ? MAX_TIMER_MS : timeoutMs;
const deadline = options.applyTimeout && timeoutMs > 0
? new Promise((_, reject) => {
timer = setTimeout(() => {
timedOut = true;
const error = new ServerTimeoutError(timeoutMs, `${ctx.method} ${ctx.path}`, ctx.requestId);
controller.abort(error);
reject(error);
}, delayMs);
})
: undefined;
// A rejection nobody awaits (the handler won on the race) must not
// surface as unhandled.
deadline?.catch(() => undefined);
options.onClientClose(() => {
if (!controller.signal.aborted) {
controller.abort(new Error("Client disconnected"));
}
});
return {
controller,
deadline,
timedOut: () => timedOut,
release: () => {
if (timer) {
clearTimeout(timer);
timer = undefined;
}
},
};
}
/**
* The listening Node `http.Server`, once `start()` has run and the runtime
* is Node (Bun and Deno serve without one). A WebSocket upgrade handler
* such as `attachTranscribeWebSocket` attaches to it; `undefined` means
* there is nothing to attach to.
*/
getNativeServer() {
return undefined;
}
// ============================================
// Common Methods (Shared Implementation)
// ============================================
/**
* Import an optional framework dependency (express/fastify/koa and their
* plugins), converting a missing package into a {@link MissingDependencyError}
* instead of letting the framework's `Cannot find package` propagate raw.
*
* Delegates to {@link tryImport} for the actual resolution and message
* formatting, then re-wraps only the "package genuinely absent" case — the
* one `tryImport` signals by attaching the loader's own module-not-found
* error as `cause` — into the adapter-specific error type. Any other
* failure (installed but broken, non-package specifier) passes through
* unchanged, matching `tryImport`'s own contract.
*/
async importFrameworkDependency(pkg, framework) {
try {
return await tryImport(pkg, `${framework} server adapter`);
}
catch (error) {
if (error instanceof Error && isModuleNotFoundCause(error.cause)) {
throw new MissingDependencyError(pkg, framework, `pnpm add ${pkg}`);
}
throw error;
}
}
/**
* Initialize the server adapter
* Sets up routes, middleware, and framework
*/
async initialize() {
// Validate lifecycle state for initialization
if (this.lifecycleState !== "uninitialized" &&
this.lifecycleState !== "stopped") {
throw new InvalidLifecycleStateError("initialize", this.lifecycleState, [
"uninitialized",
"stopped",
]);
}
this.lifecycleState = "initializing";
logger.info("[ServerAdapter] Initializing server adapter", {
port: this.config.port,
host: this.config.host,
basePath: this.config.basePath,
});
const span = SpanSerializer.createSpan(SpanType.SERVER_REQUEST, "server.initialize", {
"server.operation": "initialize",
"server.port": this.config.port,
"server.host": this.config.host,
});
const startTime = Date.now();
try {
// Initialize framework-specific setup
await this.initializeFramework();
this.frameworkReady = true;
// Register built-in middleware
this.registerBuiltInMiddleware();
// Replay what callers registered before the framework app existed
this.flushPendingRegistrations();
// Register built-in routes
await this.registerBuiltInRoutes();
this.lifecycleState = "initialized";
this.emit("initialized", {
config: this.config,
routeCount: this.routes.size,
middlewareCount: this.middlewares.length,
});
logger.info("[ServerAdapter] Server adapter initialized", {
routes: this.routes.size,
middlewares: this.middlewares.length,
});
span.durationMs = Date.now() - startTime;
const endedSpan = SpanSerializer.endSpan(span, SpanStatus.OK);
getMetricsAggregator().recordSpan(endedSpan);
}
catch (error) {
this.lifecycleState = "error";
span.durationMs = Date.now() - startTime;
const endedSpan = SpanSerializer.endSpan(span, SpanStatus.ERROR);
endedSpan.statusMessage =
error instanceof Error ? error.message : String(error);
getMetricsAggregator().recordSpan(endedSpan);
throw error;
}
}
/**
* Register a custom route
*/
registerRoute(route) {
const routeKey = `${route.method.toUpperCase()}:${route.path}`;
if (this.routes.has(routeKey)) {
logger.warn(`[ServerAdapter] Route ${routeKey} already exists, replacing`);
}
this.routes.set(routeKey, route);
if (this.frameworkReady) {
this.registerFrameworkRoute(route);
}
else {
this.pendingRouteKeys.add(routeKey);
}
logger.debug(`[ServerAdapter] Registered route: ${routeKey}`, {
description: route.description,
streaming: route.streaming?.enabled,
auth: route.auth,
});
}
/**
* Register multiple routes from a route group
*/
registerRouteGroup(group) {
// Register group-specific middleware first
if (group.middleware) {
for (const middleware of group.middleware) {
this.registerMiddleware({
...middleware,
paths: middleware.paths ?? [group.prefix],
});
}
}
// Register all routes in the group with prefix applied
const prefix = this.normalizePath(group.prefix);
// The group's root segment ("/api" of "/api/health"): a route whose path
// already lives under it is a full path, as every built-in route is.
// Testing only the whole prefix put `/api/version`, declared in the health
// group, at `/api/health/api/version`.
const root = `/${prefix.split("/").filter(Boolean)[0] ?? ""}`;
for (const route of group.routes) {
const needsPrefix = prefix !== "/" &&
!pathStartsWithSegment(route.path, prefix) &&
!pathStartsWithSegment(route.path, root);
const prefixedPath = this.normalizePath(needsPrefix ? `${prefix}${route.path}` : route.path);
const prefixedRoute = {
...route,
path: prefixedPath,
};
this.registerRoute(prefixedRoute);
}
logger.debug(`[ServerAdapter] Registered route group: ${group.prefix}`, {
routes: group.routes.length,
middleware: group.middleware?.length ?? 0,
});
}
/**
* Normalize a path by removing duplicate slashes and ensuring leading slash
*/
normalizePath(path) {
return "/" + path.split("/").filter(Boolean).join("/");
}
/**
* Register custom middleware
*/
registerMiddleware(middleware) {
this.middlewares.push(middleware);
if (this.frameworkReady) {
this.registerFrameworkMiddleware(middleware);
}
else {
this.pendingMiddlewares.push(middleware);
}
logger.debug(`[ServerAdapter] Registered middleware: ${middleware.name}`, {
order: middleware.order,
paths: middleware.paths,
});
}
/**
* Log a failed request. A client error (a rejected API key, a failed
* validation) is routine traffic, so it is a one-line warning rather than
* an error with a stack trace that anyone could flood the logs with.
*/
logRequestError(source, requestId, error) {
if (error instanceof ServerAdapterError && error.getHttpStatus() < 500) {
logger.warn(`[${source}] Request rejected`, {
requestId,
code: error.code,
error: error.message,
});
return;
}
logger.error(`[${source}] Request error`, {
requestId,
error: error.message,
stack: error.stack,
});
}
/**
* Notify "error" listeners about a failed request. EventEmitter throws when
* "error" has no listener, which inside a framework's error handler turns
* every failure into an empty 500, so emit only when someone is listening.
*/
emitRequestError(payload) {
if (this.listenerCount("error") > 0) {
this.emit("error", payload);
}
}
/**
* Hand queued registrations to the framework. A route re-registered under
* the same key before initialize() is replayed once, in its final form.
*/
flushPendingRegistrations() {
const middlewares = this.pendingMiddlewares;
const routeKeys = this.pendingRouteKeys;
this.pendingMiddlewares = [];
this.pendingRouteKeys = new Set();
for (const middleware of middlewares) {
this.registerFrameworkMiddleware(middleware);
}
for (const routeKey of routeKeys) {
const route = this.routes.get(routeKey);
if (route) {
this.registerFrameworkRoute(route);
}
}
}
/**
* Create request context from incoming request
*/
createContext(options) {
return {
requestId: options.requestId,
method: options.method,
path: options.path,
headers: options.headers,
query: options.query ?? {},
params: options.params ?? {},
body: options.body,
remoteAddress: options.remoteAddress,
neurolink: this.neurolink,
toolRegistry: this.toolRegistry,
externalServerManager: this.externalServerManager,
timestamp: Date.now(),
metadata: {},
redaction: this.redactionConfig,
};
}
/**
* Register built-in middleware
*/
registerBuiltInMiddleware() {
// Request ID middleware
this.registerMiddleware({
name: "requestId",
order: 0,
handler: async (ctx, next) => {
ctx.requestId = ctx.requestId || this.generateRequestId();
return next();
},
});
// Logging middleware
if (this.config.logging.enabled) {
this.registerMiddleware({
name: "logging",
order: 1,
handler: async (ctx, next) => {
const start = Date.now();
logger.info(`[ServerAdapter] ${ctx.method} ${ctx.path}`, {
requestId: ctx.requestId,
});
const result = await next();
logger.info(`[ServerAdapter] ${ctx.method} ${ctx.path} completed`, {
requestId: ctx.requestId,
duration: Date.now() - start,
});
return result;
},
});
}
}
/**
* Register built-in routes
* Only registers health routes if disableBuiltInHealth is false (default)
*/
async registerBuiltInRoutes() {
// Skip built-in health routes if disabled (to avoid duplication with healthRoutes)
if (!this.config.disableBuiltInHealth) {
// Health check
this.registerRoute({
method: "GET",
path: `${this.config.basePath}/health`,
handler: async () => ({
status: "ok",
timestamp: new Date().toISOString(),
uptime: this.startTime ? Date.now() - this.startTime.getTime() : 0,
version: process.env.npm_package_version || "unknown",
}),
description: "Health check endpoint",
tags: ["system"],
});
// Ready check
this.registerRoute({
method: "GET",
path: `${this.config.basePath}/ready`,
handler: async (ctx) => {
const toolRegistry = ctx.toolRegistry;
const readinessTimeout = this.config.timeout || 5000;
let tools;
let toolsAvailable;
try {
tools = await withTimeout(toolRegistry.listTools(), readinessTimeout, new Error(`toolRegistry.listTools timed out after ${readinessTimeout}ms`));
toolsAvailable = tools.length > 0;
}
catch (error) {
logger.warn("[ServerAdapter] Tool registry check timed out", {
timeout: readinessTimeout,
error: error instanceof Error ? error.message : String(error),
});
// Return degraded status but don't fail the readiness check
toolsAvailable = false;
}
return {
ready: true,
timestamp: new Date().toISOString(),
services: {
neurolink: true,
tools: toolsAvailable,
externalServers: !!ctx.externalServerManager,
},
};
},
description: "Readiness check endpoint",
tags: ["system"],
});
}
// Metrics endpoint (if enabled)
if (this.config.enableMetrics) {
this.registerRoute({
method: "GET",
path: `${this.config.basePath}/metrics`,
handler: async () => {
const status = this.getStatus();
return {
server: {
running: status.running,
uptime: status.uptime,
routes: status.routes,
middlewares: status.middlewares,
},
process: {
memoryUsage: process.memoryUsage(),
cpuUsage: process.cpuUsage(),
pid: process.pid,
},
timestamp: new Date().toISOString(),
};
},
description: "Server metrics endpoint",
tags: ["system"],
});
}
}
/**
* Ask the adapter to carry middleware state (`ctx.user` and the rest) to later
* middleware and the route handler, as the `carryMiddlewareState` option does.
* `registerAllRoutes()` calls it when given `perUserAuth`, which cannot work
* without the user in the handler. It takes effect for requests that start
* after the call, so call it before the server starts, as registering routes
* is.
*/
enableMiddlewareStateCarry() {
this.carryRequestedByRoutes = true;
}
/** Whether this adapter carries middleware state to the handler. */
carriesMiddlewareState() {
return this.config.carryMiddlewareState || this.carryRequestedByRoutes;
}
/**
* What middleware has set on its context that later middleware and the route
* handler must see. Each step gets a freshly built context, so unless this is
* parked in the framework's per-request storage an authenticated `ctx.user`
* set by middleware is gone before the handler runs. `undefined` when the
* adapter does not carry middleware state, so nothing is parked.
*/
captureCarriedContext(ctx) {
if (!this.carriesMiddlewareState()) {
return undefined;
}
return {
user: ctx.user,
session: ctx.session,
metadata: ctx.metadata,
abortSignal: ctx.abortSignal,
abortController: ctx.abortController,
};
}
/**
* Put what `captureCarriedContext` saved onto a freshly built context, and
* mark the context as one that received the carry. The agent routes read the
* mark: a request that never used to reach its handler with `ctx.user` must
* not start being identified by it unless the server opts in. Does nothing
* when the adapter does not carry middleware state: the context stays the
* fresh one it always was, and unmarked.
*/
restoreCarriedContext(ctx, carried) {
if (!this.carriesMiddlewareState()) {
return;
}
markContextCarried(ctx);
if (!carried) {
return;
}
if (carried.user) {
ctx.user = carried.user;
}
if (carried.session) {
ctx.session = carried.session;
}
if (carried.metadata) {
ctx.metadata = { ...ctx.metadata, ...carried.metadata };
}
if (carried.abortSignal) {
ctx.abortSignal = carried.abortSignal;
}
if (carried.abortController) {
ctx.abortController = carried.abortController;
}
}
/**
* Generate unique request ID
*/
generateRequestId() {
return `req-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
}
// ============================================
// Lifecycle Management Methods
// ============================================
/**
* Get the current lifecycle state
*/
getLifecycleState() {
return this.lifecycleState;
}
/**
* Track a new connection
* @param id Unique connection identifier
* @param socket Optional underlying socket object
* @param requestId Optional associated request ID
*/
trackConnection(id, socket, requestId) {
this.activeConnections.set(id, {
id,
createdAt: Date.now(),
socket,
requestId,
isActive: true,
});
logger.debug("[ServerAdapter] Connection tracked", {
connectionId: id,
activeConnections: this.activeConnections.size,
});
}
/**
* Untrack a connection (when it's completed)
* @param id Connection identifier to remove
*/
untrackConnection(id) {
const removed = this.activeConnections.delete(id);
if (removed) {
logger.debug("[ServerAdapter] Connection untracked", {
connectionId: id,
activeConnections: this.activeConnections.size,
});
}
}
/**
* Get the number of active connections
*/
getActiveConnectionCount() {
return this.activeConnections.size;
}
/**
* Perform graceful shutdown with connection draining
* This method handles the complete shutdown lifecycle
*/
async gracefulShutdown() {
const { gracefulShutdownTimeoutMs, drainTimeoutMs, forceClose } = this.shutdownConfig;
logger.info("[ServerAdapter] Starting graceful shutdown", {
activeConnections: this.activeConnections.size,
gracefulShutdownTimeoutMs,
drainTimeoutMs,
});
const shutdownSpan = SpanSerializer.createSpan(SpanType.SERVER_REQUEST, "server.shutdown", {
"server.operation": "gracefulShutdown",
"server.activeConnections": this.activeConnections.size,
});
const shutdownStartTime = Date.now();
// Timer references for cleanup
let shutdownTimer;
let drainTimer;
try {
// Set draining state
this.lifecycleState = "draining";
// Stop accepting new connections (covered by shutdown span)
await this.stopAcceptingConnections();
logger.info("[ServerAdapter] Stopped accepting new connections");
// Create drain promise that resolves when all connections are closed
const drainPromise = this.drainConnections();
// Create timeout promise for overall shutdown
const shutdownTimeoutPromise = new Promise((_, reject) => {
shutdownTimer = setTimeout(() => {
reject(new ShutdownTimeoutError(gracefulShutdownTimeoutMs, this.activeConnections.size));
}, gracefulShutdownTimeoutMs);
});
// Create timeout promise for drain phase
const drainTimeoutPromise = new Promise((resolve) => {
drainTimer = setTimeout(() => {
resolve("drain_timeout");
}, drainTimeoutMs);
});
// Race drain against drain timeout
const drainResult = await Promise.race([
drainPromise,
drainTimeoutPromise,
]);
if (drainResult === "drain_timeout" && this.activeConnections.size > 0) {
logger.warn("[ServerAdapter] Drain timeout reached", {
remainingConnections: this.activeConnections.size,
});
if (forceClose) {
logger.info("[ServerAdapter] Force closing remaining connections");
await this.forceCloseConnections();
}
else {
throw new DrainTimeoutError(drainTimeoutMs, this.activeConnections.size);
}
}
// Set stopping state
this.lifecycleState = "stopping";
// Close the server with shutdown timeout
await Promise.race([this.closeServer(), shutdownTimeoutPromise]);
logger.info("[ServerAdapter] Server closed successfully");
shutdownSpan.durationMs = Date.now() - shutdownStartTime;
const endedShutdownSpan = SpanSerializer.endSpan(shutdownSpan, SpanStatus.OK);
getMetricsAggregator().recordSpan(endedShutdownSpan);
}
catch (error) {
// If force close is enabled and we hit a timeout, try to force close
if (forceClose &&
(error instanceof ShutdownTimeoutError ||
error instanceof DrainTimeoutError)) {
logger.warn("[ServerAdapter] Timeout during shutdown, forcing close", {
error: error.message,
});
await this.forceCloseConnections();
await this.closeServer();
shutdownSpan.durationMs = Date.now() - shutdownStartTime;
const endedShutdownSpan = SpanSerializer.endSpan(shutdownSpan, SpanStatus.OK);
getMetricsAggregator().recordSpan(endedShutdownSpan);
}
else {
this.lifecycleState = "error";
shutdownSpan.durationMs = Date.now() - shutdownStartTime;
const endedShutdownSpan = SpanSerializer.endSpan(shutdownSpan, SpanStatus.ERROR);
endedShutdownSpan.statusMessage =
error instanceof Error ? error.message : String(error);
getMetricsAggregator().recordSpan(endedShutdownSpan);
throw error;
}
}
finally {
// Clean up timers to prevent memory leaks and unhandled rejections
if (shutdownTimer) {
clearTimeout(shutdownTimer);
}
if (drainTimer) {
clearTimeout(drainTimer);
}
}
}
/**
* Wait for all active connections to drain
* Resolves when activeConnections is empty
*/
async drainConnections() {
if (this.activeConnections.size === 0) {
logger.debug("[ServerAdapter] No active connections to drain");
return;
}
logger.info("[ServerAdapter] Draining connections", {
count: this.activeConnections.size,
});
return new Promise((resolve) => {
// Check periodically if all connections are drained
const checkInterval = setInterval(() => {
if (this.activeConnections.size === 0) {
clearInterval(checkInterval);
logger.info("[ServerAdapter] All connections drained");
resolve();
}
}, 100);
});
}
/**
* Reset server state for restart capability
* Call this after stop() completes to allow restart
*/
resetServerState() {
this.isRunning = false;
this.startTime = undefined;
this.activeConnections.clear();
this.lifecycleState = "stopped";
logger.debug("[ServerAdapter] Server state reset for restart capability");
}
/**
* Validate lifecycle state transition
* @param operation The operation being performed
* @param allowedStates States that allow the operation
*/
validateLifecycleState(operation, allowedStates) {
if (!allowedStates.includes(this.lifecycleState)) {
throw new InvalidLifecycleStateError(operation, this.lifecycleState, allowedStates);
}
}
/**
* Get server status
*/
getStatus() {
return {
running: this.isRunning,
port: this.config.port,
host: this.config.host,
uptime: this.startTime ? Date.now() - this.startTime.getTime() : 0,
routes: this.routes.size,
middlewares: this.middlewares.length,
lifecycleState: this.lifecycleState,
activeConnections: this.activeConnections.size,
};
}
/**
* List all registered routes
*/
listRoutes() {
return Array.from(this.routes.values());
}
/**
* Get configuration
*/
getConfig() {
return { ...this.config };
}
}
/**
* True when `cause` is the module loader's own "package not found" error —
* the shape `tryImport` attaches as `cause` exactly when it decides the
* package is genuinely missing (see `isMissingModule` in `tryImport.ts`).
* Anything else (installed-but-broken, no cause at all) is not our case to
* convert into a {@link MissingDependencyError}.
*/
function isModuleNotFoundCause(cause) {
if (!(cause instanceof Error)) {
return false;
}
const code = cause.code;
return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
}