@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
637 lines (636 loc) • 27.3 kB
JavaScript
/**
* Fastify Server Adapter
* Server adapter implementation using Fastify framework
* Fastify is known for its high performance and low overhead
*/
import { logger } from "../../utils/logger.js";
import { AlreadyRunningError, ServerAdapterError, ServerStartError, ServerStopError, wrapError, } from "../errors.js";
import { withTimeout } from "../../utils/errorHandling.js";
import { BaseServerAdapter } from "../abstract/baseServerAdapter.js";
import { resolveClientAddress } from "../utils/clientAddress.js";
import { shapeRouteError } from "../utils/clientError.js";
import { pathMatchesAny, stripQuery } from "../utils/pathMatch.js";
import { isErrorResponse } from "../utils/validation.js";
import { isRawBodyContentType, isWebResponse, readWebResponse, } from "../utils/rawBody.js";
/** How long `listen()` may take; `config.timeout` is the per-request budget. */
const STARTUP_TIMEOUT_MS = 30_000;
/**
* Fastify-specific server adapter
* Provides high-performance HTTP server with schema validation
*/
export class FastifyServerAdapter extends BaseServerAdapter {
app = null;
frameworkInitialized = false;
// The rate limiter counts nothing it cannot attribute, and says so once.
warnedNoClientAddress = false;
// The shutdown drain's record for each in-flight request. Fastify takes
// `request.id` from the caller's X-Request-ID, so that id can repeat across
// overlapping requests: a record named after it would be shared, and the
// first request to finish would untrack the other.
connectionIds = new WeakMap();
constructor(neurolink, config = {}) {
super(neurolink, config);
}
/**
* Initialize Fastify framework
* Called by base class but actual initialization happens in initializeFrameworkAsync
*/
initializeFramework() {
// Framework will be initialized asynchronously in initializeFrameworkAsync
// This is called by the base class constructor, but we need async imports
}
/**
* Initialize Fastify framework with async imports
*/
async initializeFrameworkAsync() {
if (this.frameworkInitialized) {
return;
}
// Dynamic import to avoid loading if not used
const fastifyModule = await this.importFrameworkDependency("fastify", "Fastify");
const Fastify = fastifyModule.default;
this.app = Fastify({
logger: this.config.logging.enabled
? {
level: this.config.logging.level,
}
: false,
requestIdHeader: "x-request-id",
genReqId: () => this.generateRequestId(),
bodyLimit: this.parseBodyLimit(this.config.bodyParser.maxSize),
});
// Uploads (multipart, octet-stream, audio/*) reach the route as bytes;
// without a parser Fastify refuses these content types with a 415.
if (this.config.bodyParser.enabled) {
this.app.addContentTypeParser(/^\s*(multipart\/form-data|application\/octet-stream|audio\/)/i, {
parseAs: "buffer",
bodyLimit: this.parseBodyLimit(this.config.bodyParser.rawMaxSize),
}, (request, body, done) => {
done(null, isRawBodyContentType(request.headers["content-type"])
? body
: undefined);
});
}
// Register CORS plugin if enabled
if (this.config.cors.enabled) {
const corsModule = await this.importFrameworkDependency("@fastify/cors", "Fastify");
await this.app.register(corsModule.default, {
// A list is matched literally, so the default `["*"]` would match
// nothing; the wildcard has to be the string "*" (Koa handles it in
// its origin callback).
origin: this.config.cors.origins.includes("*")
? "*"
: this.config.cors.origins,
methods: this.config.cors.methods,
allowedHeaders: this.config.cors.headers,
credentials: this.config.cors.credentials,
maxAge: this.config.cors.maxAge,
});
}
// Register rate limiting plugin if enabled
if (this.config.rateLimit.enabled) {
const rateLimitModule = await this.importFrameworkDependency("@fastify/rate-limit", "Fastify");
const windowMs = this.config.rateLimit.windowMs;
await this.app.register(rateLimitModule.default, {
max: this.config.rateLimit.maxRequests,
timeWindow: windowMs,
// The key is resolved here, from the TCP peer or, behind a declared
// proxy, the client it reports. A request with no attributable
// address passes rather than share a bucket.
keyGenerator: (request) => this.clientKeyFor(request) ?? "",
allowList: (request) => this.clientKeyFor(request) === undefined,
// The plugin throws what this builds, so the error handler below
// needs `statusCode` to answer 429; without it every exceeded limit
// was a 500.
errorResponseBuilder: (_request, context) => ({
statusCode: 429,
code: "RATE_LIMIT_EXCEEDED",
message: this.config.rateLimit.message,
retryAfter: Math.ceil(context.ttl / 1000),
}),
});
// Add hook to set Retry-After header for 429 responses
this.app.addHook("onSend", async (_request, reply, payload) => {
if (reply.statusCode === 429) {
const retryAfter = Math.ceil(windowMs / 1000);
reply.header("Retry-After", String(retryAfter));
}
return payload;
});
}
// Add request ID to response headers
this.app.addHook("onRequest", async (request, reply) => {
reply.header("X-Request-ID", request.id);
});
// Global error handler
this.app.setErrorHandler((error, request, reply) => {
const requestId = request.id;
this.logRequestError("FastifyAdapter", requestId, error);
this.emitRequestError({
requestId,
error,
timestamp: new Date(),
});
// Handle different error types
if (error instanceof ServerAdapterError) {
reply.status(error.getHttpStatus()).send({
error: { code: error.code, message: error.message },
metadata: {
requestId,
timestamp: new Date().toISOString(),
},
});
return;
}
// An exceeded rate limit, thrown by @fastify/rate-limit as the object
// errorResponseBuilder built.
if (error.statusCode === 429) {
reply.status(429).send({
error: {
code: "RATE_LIMIT_EXCEEDED",
message: this.config.rateLimit.message,
},
metadata: {
requestId,
timestamp: new Date().toISOString(),
retryAfter: error.retryAfter,
},
});
return;
}
// Fastify's own client errors (an unparsable body, an unsupported
// media type) carry a message the client may see; a 5xx's does not.
if (error.statusCode && error.statusCode < 500) {
reply.status(error.statusCode).send({
error: {
code: `HTTP_${error.statusCode}`,
message: error.message,
},
metadata: {
requestId,
timestamp: new Date().toISOString(),
},
});
return;
}
reply.status(500).send({
error: {
code: "INTERNAL_ERROR",
message: "An internal error occurred",
},
metadata: {
requestId,
timestamp: new Date().toISOString(),
},
});
});
// 404 handler
this.app.setNotFoundHandler((request, reply) => {
reply.status(404).send({
error: {
code: "NOT_FOUND",
message: `Route ${request.method} ${request.url} not found`,
},
metadata: {
requestId: request.id,
timestamp: new Date().toISOString(),
},
});
});
this.frameworkInitialized = true;
}
/** The address a request is counted against; `undefined` when there is none. */
clientKeyFor(request) {
const forwarded = request.headers["x-forwarded-for"];
const key = resolveClientAddress({
remoteAddress: request.socket?.remoteAddress ?? request.ip,
forwardedFor: Array.isArray(forwarded) ? forwarded.join(",") : forwarded,
trustProxy: this.config.rateLimit.trustProxy,
trustedProxies: this.config.rateLimit.trustedProxies,
});
if (key === undefined && !this.warnedNoClientAddress) {
this.warnedNoClientAddress = true;
logger.alwaysStderr("[FastifyAdapter] A request arrived with no peer address, so the rate limiter cannot count it; configure rateLimit.keyGenerator to limit by another key.");
}
return key;
}
/**
* Parse body limit string to number (bytes)
*/
parseBodyLimit(limit) {
const match = limit.match(/^(\d+)(mb|kb|gb)?$/i);
if (!match) {
return 10 * 1024 * 1024; // Default 10MB
}
const value = parseInt(match[1], 10);
const unit = (match[2] || "b").toLowerCase();
switch (unit) {
case "gb":
return value * 1024 * 1024 * 1024;
case "mb":
return value * 1024 * 1024;
case "kb":
return value * 1024;
default:
return value;
}
}
/**
* Override initialize to ensure async framework setup
*/
async initialize() {
// Initialize Fastify asynchronously first. This runs before
// super.initialize()'s try/catch even starts, so a failure here (e.g. the
// "fastify" package is not installed) must be caught here too — otherwise
// it propagates with lifecycleState left at "uninitialized" instead of
// "error".
try {
await this.initializeFrameworkAsync();
}
catch (error) {
this.lifecycleState = "error";
throw error;
}
// Then call base class initialize
await super.initialize();
}
/**
* Register route with Fastify
*/
registerFrameworkRoute(route) {
if (!this.app) {
throw new Error("Fastify app not initialized. Call initialize() before registering routes.");
}
const method = route.method.toUpperCase();
// Fastify does not allow duplicate method+path registrations.
// Skip if route already exists (e.g., built-in health routes).
if (this.app.hasRoute({ method, url: route.path })) {
return;
}
this.app.route({
method,
url: route.path,
handler: async (request, reply) => {
const requestId = request.id;
const startTime = Date.now();
// Create server context
const ctx = this.createContext({
requestId,
method: request.method,
path: stripQuery(request.url),
headers: request.headers,
query: request.query,
params: request.params,
body: request.body,
remoteAddress: request.socket?.remoteAddress ?? request.ip,
});
// Copy response headers from middleware (stored in request by middleware)
const reqWithHeaders = request;
if (reqWithHeaders.responseHeaders) {
ctx.responseHeaders = { ...reqWithHeaders.responseHeaders };
}
this.restoreCarriedContext(ctx, reqWithHeaders.carriedContext);
// The handler learns of a client that went away, and a request over
// `config.timeout` is answered 504 and its work aborted. Fastify used
// to apply that timeout only to its own listen().
const abort = this.attachRequestAbort(ctx, {
onClientClose: (listener) => request.raw.on("close", () => {
if (!reply.raw.writableFinished) {
listener();
}
}),
applyTimeout: !route.streaming?.enabled,
});
// Emit request event
this.emit("request", {
requestId,
method: ctx.method,
path: ctx.path,
timestamp: new Date(),
});
try {
// Handle streaming if configured
if (route.streaming?.enabled) {
return await this.handleStreamingResponse(reply, ctx, route);
}
// Execute handler
const result = abort.deadline
? await Promise.race([route.handler(ctx), abort.deadline])
: await route.handler(ctx);
const duration = Date.now() - startTime;
// A route that answers in its own wire format returns a web Response.
if (isWebResponse(result)) {
const raw = await readWebResponse(result);
this.emit("response", {
requestId,
statusCode: raw.status,
duration,
timestamp: new Date(),
});
for (const [key, value] of Object.entries({
...ctx.responseHeaders,
...raw.headers,
})) {
reply.header(key, value);
}
reply.status(raw.status);
return reply.send(raw.body);
}
// Check if result is an error response
if (isErrorResponse(result)) {
const statusCode = result.httpStatus ?? 500;
// Emit response event with error status
this.emit("response", {
requestId,
statusCode,
duration,
timestamp: new Date(),
});
// Apply response headers from middleware and handler
if (ctx.responseHeaders) {
for (const [key, value] of Object.entries(ctx.responseHeaders)) {
reply.header(key, value);
}
}
// Return error response with proper status code
reply.status(statusCode);
return {
error: result.error,
metadata: {
...result.metadata,
requestId,
timestamp: new Date().toISOString(),
duration,
},
};
}
// Emit response event
this.emit("response", {
requestId,
statusCode: 200,
duration,
timestamp: new Date(),
});
// Apply response headers from middleware and handler
if (ctx.responseHeaders) {
for (const [key, value] of Object.entries(ctx.responseHeaders)) {
reply.header(key, value);
}
}
// Return formatted response
return {
data: result,
metadata: {
requestId,
timestamp: new Date().toISOString(),
duration,
},
};
}
catch (error) {
// The exception's text stays in the log under this request id; the
// client gets a fixed message for its category.
const shaped = shapeRouteError("FastifyAdapter", requestId, error);
this.emitRequestError({
requestId,
error: error instanceof Error ? error : new Error(String(error)),
timestamp: new Date(),
});
this.emit("response", {
requestId,
statusCode: shaped.status,
duration: Date.now() - startTime,
timestamp: new Date(),
});
if (reply.sent || reply.raw.headersSent) {
return;
}
reply.status(shaped.status);
return {
error: { code: shaped.code, message: shaped.message },
metadata: { requestId, timestamp: new Date().toISOString() },
};
}
finally {
abort.release();
}
},
});
}
/**
* Handle streaming response using Server-Sent Events
*/
async handleStreamingResponse(reply, ctx, route) {
// Set SSE headers
reply.raw.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"X-Accel-Buffering": "no", // Disable nginx buffering
});
try {
const result = await route.handler(ctx);
// Check if result is an async iterable
if (result &&
typeof result === "object" &&
Symbol.asyncIterator in result) {
for await (const chunk of result) {
reply.raw.write(`event: message\n`);
reply.raw.write(`data: ${JSON.stringify(chunk)}\n\n`);
}
}
else {
// Single result, send as complete event
reply.raw.write(`event: complete\n`);
reply.raw.write(`data: ${JSON.stringify(result)}\n\n`);
}
// Send done event
reply.raw.write(`event: done\n`);
reply.raw.write(`data: \n\n`);
reply.raw.end();
}
catch (error) {
const shaped = shapeRouteError("FastifyAdapter", ctx.requestId, error);
reply.raw.write(`event: error\n`);
reply.raw.write(`data: ${JSON.stringify({
error: shaped.message,
code: shaped.code,
status: shaped.status,
requestId: ctx.requestId,
})}\n\n`);
reply.raw.end();
}
}
/**
* Register middleware with Fastify
*/
registerFrameworkMiddleware(middleware) {
if (!this.app) {
throw new Error("Fastify app not initialized. Call initialize() before registering middleware.");
}
this.app.addHook("preHandler", async (request, _reply) => {
// Matched on the path alone, at segment boundaries: `request.url`
// carries the query string, so `/api/health?x` used to miss an
// exemption for `/api/health` and `/api/healthz` used to take it.
const requestPath = stripQuery(request.url);
// Skip excluded paths
if (pathMatchesAny(requestPath, middleware.excludePaths)) {
return;
}
// Check if path matches
if (!pathMatchesAny(requestPath, middleware.paths || ["/"])) {
return;
}
// Initialize response headers storage if not present
const reqWithHeaders = request;
if (!reqWithHeaders.responseHeaders) {
reqWithHeaders.responseHeaders = {};
}
// Create context with existing response headers from previous middleware
const ctx = this.createContext({
requestId: request.id,
method: request.method,
path: requestPath,
headers: request.headers,
query: request.query,
params: request.params,
body: request.body,
remoteAddress: request.socket?.remoteAddress ?? request.ip,
});
// Copy existing response headers to context
ctx.responseHeaders = { ...reqWithHeaders.responseHeaders };
this.restoreCarriedContext(ctx, reqWithHeaders.carriedContext);
// Execute middleware
await middleware.handler(ctx, async () => {
// What this middleware set (ctx.user included) is for the next
// middleware and the route handler, which build their own contexts.
reqWithHeaders.carriedContext = this.captureCarriedContext(ctx);
// After middleware execution, merge response headers back to request
if (ctx.responseHeaders) {
Object.assign(reqWithHeaders.responseHeaders, ctx.responseHeaders);
}
});
// Also merge headers after handler returns (for middleware that set headers after next())
if (ctx.responseHeaders) {
Object.assign(reqWithHeaders.responseHeaders, ctx.responseHeaders);
}
});
}
/**
* Start the Fastify server
*/
async start() {
// Validate lifecycle state
this.validateLifecycleState("start", ["initialized", "stopped"]);
if (this.isRunning) {
throw new AlreadyRunningError(this.config.port, this.config.host);
}
if (!this.app) {
throw new Error("Fastify app not initialized. Call initialize() before starting.");
}
// Capture non-null reference for use in closures below
const app = this.app;
this.lifecycleState = "starting";
const { port, host } = this.config;
const startupTimeout = STARTUP_TIMEOUT_MS;
// Track connections via Fastify hooks (must be registered before listen)
app.addHook("onRequest", async (request) => {
const connectionId = `conn-${this.generateRequestId()}`;
this.connectionIds.set(request, connectionId);
this.trackConnection(connectionId, request.raw.socket, request.id);
});
app.addHook("onResponse", async (request) => {
const connectionId = this.connectionIds.get(request);
if (connectionId) {
this.untrackConnection(connectionId);
}
});
try {
await withTimeout(app.listen({ port, host }), startupTimeout, new ServerStartError(`Fastify server startup timed out after ${startupTimeout}ms`, undefined, port, host));
this.isRunning = true;
this.startTime = new Date();
this.lifecycleState = "running";
logger.info(`[FastifyAdapter] Server started on ${host}:${port}`);
this.warnIfSensitiveRoutesUnauthenticated();
this.emit("started", {
port,
host,
timestamp: this.startTime,
});
}
catch (error) {
this.lifecycleState = "error";
throw error;
}
}
/**
* Stop the Fastify server with graceful shutdown
*/
async stop() {
if (!this.isRunning) {
return; // Already stopped, return gracefully (idempotent)
}
const uptime = this.startTime ? Date.now() - this.startTime.getTime() : 0;
try {
// Use graceful shutdown from base class
await this.gracefulShutdown();
logger.info("[FastifyAdapter] Server stopped", { uptime });
this.emit("stopped", {
uptime,
timestamp: new Date(),
});
// Reset state for restart capability
this.resetServerState();
this.frameworkInitialized = false;
this.app = null;
}
catch (error) {
const wrappedError = wrapError(error);
throw new ServerStopError(wrappedError.message, wrappedError);
}
}
// ============================================
// Lifecycle Methods (Framework-Specific)
// ============================================
/**
* Stop accepting new connections
*/
async stopAcceptingConnections() {
// Fastify's close() handles this internally
logger.debug("[FastifyAdapter] Stopping acceptance of new connections");
}
/**
* Close the underlying server
*/
async closeServer() {
if (this.app) {
const closeTimeout = this.shutdownConfig.gracefulShutdownTimeoutMs;
await withTimeout(this.app.close(), closeTimeout, new Error(`Fastify server close timed out after ${closeTimeout}ms`));
}
}
/**
* Force close all active connections
*/
async forceCloseConnections() {
logger.info("[FastifyAdapter] Force closing connections", {
count: this.activeConnections.size,
});
// Get the underlying server and destroy all sockets
const server = this.app?.server;
if (server) {
// Force close by destroying the server
server.closeAllConnections?.();
}
this.activeConnections.clear();
}
/**
* Get the Fastify instance
*/
getFrameworkInstance() {
return this.app;
}
getNativeServer() {
// Fastify owns its http.Server and exposes it as `app.server`.
return this.app?.server;
}
}