@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
850 lines (849 loc) • 35.5 kB
JavaScript
/**
* Hono Server Adapter
* Primary server adapter implementation using Hono framework
* Hono is chosen for its performance, TypeScript-first design, and edge compatibility
*/
import { logger } from "../../utils/logger.js";
import { AlreadyRunningError, ServerAdapterError, ServerStopError, wrapError, } from "../errors.js";
import { BaseServerAdapter } from "../abstract/baseServerAdapter.js";
import { markContextCarried } from "../utils/carriedContextMark.js";
import { resolveClientAddress } from "../utils/clientAddress.js";
import { shapeRouteError } from "../utils/clientError.js";
import { pathMatchesAny } from "../utils/pathMatch.js";
import { isErrorResponse } from "../utils/validation.js";
import { isRawBodyContentType, isWebResponse, parseByteLimit, RawBodyTooLargeError, readBoundedRequestBody, } from "../utils/rawBody.js";
/**
* Hono-specific server adapter
* Supports multiple runtimes: Bun, Deno, Node.js
*/
export class HonoServerAdapter extends BaseServerAdapter {
app;
server;
rateLimitStore = new Map();
rateLimitCleanupInterval;
// Context shared between middleware and the route handler. Keyed by the request
// object, never by the request id: the id can be the
// caller's own X-Request-ID, so two overlapping requests that send the same one
// would share a context, and the second would run with the first one's
// identity, headers and body. A WeakMap also frees an entry whose handler
// never ran.
requestContextStore = new WeakMap();
// One id per request, for logs and events: the caller's X-Request-ID when sent,
// otherwise generated once, so every step reports the same id. With no header
// every step used to invent its own.
requestIds = new WeakMap();
// Populated by initializeFramework's dynamic imports; used by methods that
// run after initialization (route registration, streaming) and so cannot
// rely on initializeFramework's own local closure variables.
streamSSEFn;
parseFormBody;
// The runtime's view of the TCP peer (Node, Bun or Deno); undefined where the
// runtime offers none, and then requests carry no address.
getConnInfoFn;
// The rate limiter counts nothing it cannot attribute, and says so once.
warnedNoClientAddress = false;
constructor(neurolink, config = {}) {
super(neurolink, config);
}
/**
* Create rate limiter middleware for Hono
*/
createRateLimiter() {
return async (c, next) => {
// Skip rate limiting for excluded paths
if (pathMatchesAny(c.req.path, this.config.rateLimit.skipPaths)) {
return next();
}
// Use custom keyGenerator if provided, otherwise default to IP-based key
let key;
if (this.config.rateLimit.keyGenerator) {
// Build minimal context for keyGenerator
const headers = {};
c.req.raw.headers.forEach((value, name) => {
headers[name] = value;
});
const minCtx = {
requestId: this.requestIdFor(c),
method: c.req.method,
path: c.req.path,
headers,
query: this.extractQuery(c),
params: c.req.param(),
neurolink: this.neurolink,
toolRegistry: this.toolRegistry,
externalServerManager: this.externalServerManager,
timestamp: Date.now(),
metadata: {},
remoteAddress: this.remoteAddressFor(c),
};
key = this.config.rateLimit.keyGenerator(minCtx);
}
else {
// The TCP peer, or behind a declared proxy the client it reports. A
// header alone used to be the key, so one shared "unknown" bucket
// served every direct client and a rotating X-Forwarded-For escaped
// the limit; a request with no attributable address is now let
// through rather than pooled with every other such request.
key = resolveClientAddress({
remoteAddress: this.remoteAddressFor(c),
forwardedFor: c.req.header("x-forwarded-for"),
trustProxy: this.config.rateLimit.trustProxy,
trustedProxies: this.config.rateLimit.trustedProxies,
});
if (key === undefined) {
if (!this.warnedNoClientAddress) {
this.warnedNoClientAddress = true;
logger.alwaysStderr("[HonoAdapter] The runtime reports no peer address for requests, so the rate limiter cannot count them; configure rateLimit.keyGenerator to limit by another key.");
}
return next();
}
}
const now = Date.now();
const windowMs = this.config.rateLimit.windowMs;
const maxRequests = this.config.rateLimit.maxRequests;
let record = this.rateLimitStore.get(key);
if (!record || now > record.resetAt) {
record = { count: 0, resetAt: now + windowMs };
this.rateLimitStore.set(key, record);
}
record.count++;
// Set rate limit headers
c.header("X-RateLimit-Limit", String(maxRequests));
c.header("X-RateLimit-Remaining", String(Math.max(0, maxRequests - record.count)));
c.header("X-RateLimit-Reset", String(Math.ceil(record.resetAt / 1000)));
if (record.count > maxRequests) {
const retryAfter = Math.ceil((record.resetAt - now) / 1000);
c.header("Retry-After", String(retryAfter));
return c.json({
error: {
code: "RATE_LIMIT_EXCEEDED",
message: this.config.rateLimit.message,
},
metadata: {
timestamp: new Date().toISOString(),
retryAfter,
},
}, 429);
}
return next();
};
}
/**
* Periodically clean up expired rate limit entries
*/
cleanupRateLimitStore() {
const now = Date.now();
for (const [key, entry] of this.rateLimitStore.entries()) {
if (now > entry.resetAt) {
this.rateLimitStore.delete(key);
}
}
}
/**
* Initialize Hono framework
* Dynamically imports Hono and its middleware so requiring only another
* adapter (Express/Fastify/Koa) never pulls Hono's import graph in.
*/
async initializeFramework() {
const [{ Hono }, { cors }, { HTTPException }, { logger: honoLogger }, { secureHeaders }, { streamSSE }, { timeout }, { parseBody },] = await Promise.all([
this.importFrameworkDependency("hono", "hono"),
this.importFrameworkDependency("hono/cors", "hono"),
this.importFrameworkDependency("hono/http-exception", "hono"),
this.importFrameworkDependency("hono/logger", "hono"),
this.importFrameworkDependency("hono/secure-headers", "hono"),
this.importFrameworkDependency("hono/streaming", "hono"),
this.importFrameworkDependency("hono/timeout", "hono"),
this.importFrameworkDependency("hono/utils/body", "hono"),
]);
this.streamSSEFn = streamSSE;
this.parseFormBody = parseBody;
this.getConnInfoFn = await this.loadConnInfo();
this.app = new Hono();
// Add secure headers
this.app.use("*", secureHeaders());
// Add CORS if enabled
if (this.config.cors.enabled) {
this.app.use("*", cors({
// Hono matches a list of origins literally, so `["*"]` (the default)
// matches nothing and no CORS header is sent; the string "*" is the
// wildcard. Pass it as such when the list contains it.
origin: this.config.cors.origins.includes("*")
? "*"
: this.config.cors.origins,
allowMethods: this.config.cors.methods,
allowHeaders: this.config.cors.headers,
credentials: this.config.cors.credentials,
maxAge: this.config.cors.maxAge,
}));
}
// Add timeout middleware
this.app.use("*", timeout(this.config.timeout));
// Add logging if enabled
if (this.config.logging.enabled) {
this.app.use("*", honoLogger());
}
// Add rate limiting if enabled
if (this.config.rateLimit.enabled) {
this.app.use("*", this.createRateLimiter());
// Schedule periodic cleanup of expired rate limit entries (every minute)
this.rateLimitCleanupInterval = setInterval(() => this.cleanupRateLimitStore(), 60000);
}
// Global error handler
this.app.onError((error, c) => {
const requestId = this.requestIdFor(c);
this.logRequestError("HonoAdapter", requestId, error);
this.emitRequestError({
requestId,
error,
timestamp: new Date(),
});
if (error instanceof ServerAdapterError) {
return c.json({
error: { code: error.code, message: error.message },
metadata: {
requestId,
timestamp: new Date().toISOString(),
},
}, error.getHttpStatus());
}
if (error instanceof HTTPException) {
return c.json({
error: {
code: `HTTP_${error.status}`,
message: error.message,
},
metadata: {
requestId,
timestamp: new Date().toISOString(),
},
}, error.status);
}
return c.json({
error: {
code: "INTERNAL_ERROR",
message: "An internal error occurred",
},
metadata: {
requestId,
timestamp: new Date().toISOString(),
},
}, 500);
});
// 404 handler
this.app.notFound((c) => {
return c.json({
error: {
code: "NOT_FOUND",
message: `Route ${c.req.method} ${c.req.path} not found`,
},
}, 404);
});
}
/**
* Register route with Hono
*/
registerFrameworkRoute(route) {
const method = route.method.toLowerCase();
this.app[method](route.path, async (c) => {
const requestId = this.requestIdFor(c);
// Not derived from the request id, which a caller may repeat: two
// overlapping requests would then share one record and the first to
// finish would untrack the other.
const connectionId = `conn-${this.generateRequestId()}`;
const startTime = Date.now();
// Track connection for graceful shutdown
this.trackConnection(connectionId, undefined, requestId);
let abort;
try {
// Extract path parameters
const params = c.req.param();
// Reuse existing context from middleware if available, otherwise create new one
const existingCtx = this.requestContextStore.get(c.req.raw);
// Middleware ran before the router matched this route, so the shared
// context carries no path parameters yet.
if (existingCtx) {
existingCtx.params = params;
// The one request the handler already got the middleware's context
// for before this adapter carried it on every request: the caller
// sent its own X-Request-ID, which the old store was keyed by. That
// context stays unmarked, so the agent routes keep trusting its
// ctx.user there. A context found for any other request exists only
// because the server carries middleware state, is new to the
// handler, and is marked.
if (!c.req.header("X-Request-ID")) {
markContextCarried(existingCtx);
}
}
let ctx = existingCtx;
if (!ctx) {
const created = await this.createRequestContext(c, requestId, params);
if (isWebResponse(created)) {
return created;
}
ctx = created;
}
// The handler learns of a client that went away through the request's
// own signal, and of the request timeout through the same controller
// (Hono's timeout middleware answers 504; this stops the work).
abort = this.attachRequestAbort(ctx, {
onClientClose: (listener) => c.req.raw.signal.addEventListener("abort", listener, {
once: true,
}),
applyTimeout: !route.streaming?.enabled,
});
// Emit request event
this.emit("request", {
requestId,
method: ctx.method,
path: ctx.path,
timestamp: new Date(),
});
// Handle streaming if configured
if (route.streaming?.enabled) {
return await this.handleStreamingResponse(c, ctx, route);
}
// Execute handler
const result = 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)) {
this.emit("response", {
requestId,
statusCode: result.status,
duration,
timestamp: new Date(),
});
for (const [key, value] of Object.entries(ctx.responseHeaders ?? {})) {
if (!result.headers.has(key)) {
result.headers.set(key, value);
}
}
return result;
}
// 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
if (ctx.responseHeaders) {
for (const [key, value] of Object.entries(ctx.responseHeaders)) {
c.header(key, value);
}
}
// Return error response with proper status code
// Cast to ContentfulStatusCode since we know error codes are valid HTTP status codes
return c.json({
error: result.error,
metadata: {
...result.metadata,
requestId,
timestamp: new Date().toISOString(),
duration,
},
}, statusCode);
}
// Emit response event
this.emit("response", {
requestId,
statusCode: 200,
duration,
timestamp: new Date(),
});
// Apply response headers from middleware
if (ctx.responseHeaders) {
for (const [key, value] of Object.entries(ctx.responseHeaders)) {
c.header(key, value);
}
}
// Return formatted response
return c.json({
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. It used to get the
// text itself, environment variable names and upstream bodies included.
const shaped = shapeRouteError("HonoAdapter", requestId, error);
this.emit("response", {
requestId,
statusCode: shaped.status,
duration: Date.now() - startTime,
timestamp: new Date(),
});
return c.json({
error: { code: shaped.code, message: shaped.message },
metadata: { requestId, timestamp: new Date().toISOString() },
}, shaped.status);
}
finally {
abort?.release();
// Untrack connection when request completes
this.untrackConnection(connectionId);
// Clean up context store to prevent memory leaks
this.requestContextStore.delete(c.req.raw);
}
});
}
/**
* Handle streaming response using SSE
*/
async handleStreamingResponse(c, ctx, route) {
// Apply middleware response headers to streaming response before starting the stream
if (ctx.responseHeaders) {
for (const [key, value] of Object.entries(ctx.responseHeaders)) {
c.header(key, value);
}
}
return this.streamSSEFn(c, async (stream) => {
try {
// Get streaming result from handler
const result = await route.handler(ctx);
// If result is an async iterable, stream it
if (result &&
typeof result === "object" &&
Symbol.asyncIterator in result) {
for await (const chunk of result) {
// Transform raw provider chunks into StreamEvent format
// The client SDK expects { type, content, timestamp, ... } objects
const streamEvent = this.toStreamEvent(chunk);
await stream.writeSSE({
data: JSON.stringify(streamEvent),
});
}
}
else if (result && isErrorResponse(result)) {
// Error result, send as error event
const errorResult = result;
const statusCode = errorResult.httpStatus ?? 500;
await stream.writeSSE({
data: JSON.stringify({
type: "error",
error: {
code: errorResult.error?.code ?? "STREAM_ERROR",
message: errorResult.error?.message ?? "Stream error",
status: statusCode,
},
timestamp: Date.now(),
}),
});
}
else {
// Single result, normalize into a StreamEvent so the client can
// match on the `type` field via handleEvent()
const streamEvent = this.toStreamEvent(result);
await stream.writeSSE({
data: JSON.stringify(streamEvent),
});
}
// Send [DONE] signal that the client SDK expects
await stream.writeSSE({
data: "[DONE]",
});
}
catch (error) {
const shaped = shapeRouteError("HonoAdapter", ctx.requestId, error);
await stream.writeSSE({
data: JSON.stringify({
type: "error",
error: {
code: shaped.code,
message: shaped.message,
status: shaped.status,
},
timestamp: Date.now(),
}),
});
// Still send [DONE] after error so the client terminates cleanly
await stream.writeSSE({
data: "[DONE]",
});
}
});
}
/**
* Transform a raw provider chunk into a StreamEvent
* Provider chunks are typically { content: string } objects;
* the client SDK expects { type: "text", content: string, timestamp: number }
*/
toStreamEvent(chunk) {
// Already a StreamEvent (has a type field)
if (chunk &&
typeof chunk === "object" &&
"type" in chunk &&
typeof chunk.type === "string") {
return {
...chunk,
timestamp: chunk.timestamp ?? Date.now(),
};
}
// Raw text chunk from provider: { content: string }
if (chunk && typeof chunk === "object" && "content" in chunk) {
return {
type: "text",
content: String(chunk.content),
timestamp: Date.now(),
};
}
// String chunk
if (typeof chunk === "string") {
return {
type: "text",
content: chunk,
timestamp: Date.now(),
};
}
// Unknown shape — wrap as metadata event (StreamEventType has no "data" variant)
return {
type: "metadata",
metadata: chunk,
timestamp: Date.now(),
};
}
/**
* Register middleware with Hono
*/
registerFrameworkMiddleware(middleware) {
const paths = middleware.paths || ["*"];
for (const path of paths) {
this.app.use(path, async (c, next) => {
// Skip excluded paths
if (pathMatchesAny(c.req.path, middleware.excludePaths)) {
return next();
}
// Extract path parameters
const params = c.req.param();
// Get or generate request ID for context lookup
const requestId = this.requestIdFor(c);
// Reuse existing context from previous middleware if available
let ctx = this.requestContextStore.get(c.req.raw);
if (!ctx) {
// Create new context for the first middleware
const created = await this.createRequestContext(c, requestId, params);
if (isWebResponse(created)) {
return created;
}
ctx = created;
// Share the context between the middleware steps and the route
// handler when the server carries middleware state, or when the
// caller sent its own X-Request-ID: the one case the old store, keyed
// by that header, ever found a context again. Otherwise every step
// and the handler build their own, and storing this one would only
// leave it behind.
if (this.carriesMiddlewareState() || c.req.header("X-Request-ID")) {
this.requestContextStore.set(c.req.raw, ctx);
}
}
// Execute middleware
return middleware.handler(ctx, next);
});
}
}
/**
* The id of this request: the caller's `X-Request-ID` when sent, otherwise
* one generated on first use, and the same one on every later use.
*/
requestIdFor(c) {
const known = this.requestIds.get(c.req.raw);
if (known) {
return known;
}
const id = c.req.header("X-Request-ID") || this.generateRequestId();
this.requestIds.set(c.req.raw, id);
return id;
}
/**
* Start the Hono server
*/
async start() {
// Validate lifecycle state
this.validateLifecycleState("start", ["initialized", "stopped"]);
if (this.isRunning) {
throw new AlreadyRunningError(this.config.port, this.config.host);
}
this.lifecycleState = "starting";
const { port, host } = this.config;
try {
// Check if running in Bun environment
if (typeof Bun !== "undefined") {
this.server = Bun.serve({
port,
hostname: host,
fetch: this.app.fetch,
});
}
else if (typeof Deno !== "undefined") {
// Deno runtime
this.server = Deno.serve({
port,
hostname: host,
}, this.app.fetch);
}
else {
// Fallback to Node.js http module via @hono/node-server
const { serve } = await import("@hono/node-server");
this.server = serve({
fetch: this.app.fetch,
port,
hostname: host,
});
}
this.isRunning = true;
this.startTime = new Date();
this.lifecycleState = "running";
logger.info(`[HonoAdapter] Server started on ${host}:${port}`);
this.warnIfSensitiveRoutesUnauthenticated();
this.emit("started", {
port,
host,
timestamp: this.startTime,
});
}
catch (error) {
this.lifecycleState = "error";
throw error;
}
}
/**
* Stop the Hono 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();
// Clean up rate limit cleanup interval
if (this.rateLimitCleanupInterval) {
clearInterval(this.rateLimitCleanupInterval);
this.rateLimitCleanupInterval = undefined;
}
logger.info("[HonoAdapter] Server stopped", { uptime });
this.emit("stopped", {
uptime,
timestamp: new Date(),
});
// Reset state for restart capability
this.resetServerState();
this.server = undefined;
this.rateLimitStore.clear();
}
catch (error) {
const wrappedError = wrapError(error);
throw new ServerStopError(wrappedError.message, wrappedError);
}
}
// ============================================
// Lifecycle Methods (Framework-Specific)
// ============================================
/**
* Stop accepting new connections
*/
async stopAcceptingConnections() {
// For Hono, this is handled by the underlying server
logger.debug("[HonoAdapter] Stopping acceptance of new connections");
}
/**
* Close the underlying server
*/
async closeServer() {
if (!this.server) {
return;
}
// Handle different server types (Bun, Deno, Node.js)
const serverObj = this.server;
if (typeof serverObj.stop === "function") {
// Bun server
serverObj.stop();
}
else if (typeof serverObj.shutdown === "function") {
// Deno server
await serverObj.shutdown();
}
else if (typeof serverObj.close === "function") {
// Node.js http server
await new Promise((resolve, reject) => {
serverObj.close?.((err) => {
if (err) {
reject(err);
}
else {
resolve();
}
});
});
}
}
/**
* Force close all active connections
*/
async forceCloseConnections() {
logger.info("[HonoAdapter] Force closing connections", {
count: this.activeConnections.size,
});
if (this.server) {
const serverObj = this.server;
if (typeof serverObj.closeAllConnections === "function") {
serverObj.closeAllConnections();
}
}
this.activeConnections.clear();
}
/**
* Get the Hono app instance
*/
getFrameworkInstance() {
return this.app;
}
getNativeServer() {
// @hono/node-server's serve() returns the http.Server; Bun/Deno do not.
return this.server;
}
// ============================================
// Helper Methods
// ============================================
extractHeaders(c) {
const headers = {};
c.req.raw.headers.forEach((value, key) => {
headers[key] = value;
});
return headers;
}
/**
* The runtime's connection-info helper: `@hono/node-server`'s on Node, the
* Bun or Deno adapter's there. Absent on a runtime that offers none.
*/
async loadConnInfo() {
try {
if (typeof Bun !== "undefined") {
const bun = await import("hono/bun");
return bun.getConnInfo;
}
if (typeof Deno !== "undefined") {
const deno = await import("hono/deno");
return deno.getConnInfo;
}
const node = await import("@hono/node-server/conninfo");
return node.getConnInfo;
}
catch (error) {
logger.debug("[HonoAdapter] No connection-info helper for this runtime", {
error: error instanceof Error ? error.message : String(error),
});
return undefined;
}
}
/** The TCP peer of this request, when the runtime reports one. */
remoteAddressFor(c) {
if (!this.getConnInfoFn) {
return undefined;
}
try {
const address = this.getConnInfoFn(c).remote.address;
return typeof address === "string" && address.length > 0
? address
: undefined;
}
catch {
return undefined;
}
}
extractQuery(c) {
const query = {};
const url = new URL(c.req.url);
url.searchParams.forEach((value, key) => {
query[key] = value;
});
return query;
}
/**
* A request's context, or the 413 that answers a JSON or form body over its
* limit. That answer is built here, before the context exists, so no
* middleware (an auth check included) and no route runs for the request.
* An upload over the limit still reaches its route as the error itself,
* which answers in its own wire format.
*/
async createRequestContext(c, requestId, params) {
const body = await this.extractBody(c);
if (body instanceof RawBodyTooLargeError &&
!isRawBodyContentType(c.req.header("Content-Type"))) {
logger.warn("[HonoAdapter] Request rejected", {
requestId,
code: "PAYLOAD_TOO_LARGE",
error: body.message,
});
this.emitRequestError({
requestId,
error: body,
timestamp: new Date(),
});
return c.json({
error: { code: "PAYLOAD_TOO_LARGE", message: body.message },
metadata: { requestId, timestamp: new Date().toISOString() },
}, 413);
}
return this.createContext({
requestId,
method: c.req.method,
path: c.req.path,
headers: this.extractHeaders(c),
query: this.extractQuery(c),
params,
body,
remoteAddress: this.remoteAddressFor(c),
});
}
async extractBody(c) {
if (!this.config.bodyParser.enabled) {
return undefined;
}
const contentType = c.req.header("Content-Type") || "";
// JSON and url-encoded forms are read through the same bounded read as
// uploads, with the limits the other adapters apply: `jsonLimit` for JSON,
// `maxSize` for forms. The bytes are then parsed the way Hono parses a
// body it has already buffered. A body that cannot be read or parsed is
// `undefined`, as it was when Hono did the reading.
const isJson = contentType.includes("application/json");
if (isJson || contentType.includes("application/x-www-form-urlencoded")) {
try {
const bytes = await readBoundedRequestBody(c.req.raw, parseByteLimit(isJson
? this.config.bodyParser.jsonLimit
: this.config.bodyParser.maxSize));
if (bytes instanceof RawBodyTooLargeError) {
return bytes;
}
return isJson
? JSON.parse(new TextDecoder().decode(bytes))
: await this.parseFormBody(new Request(c.req.url, {
method: "POST",
headers: { "Content-Type": contentType },
body: new Uint8Array(bytes),
}));
}
catch {
return undefined;
}
}
// Uploads (multipart, octet-stream, audio/*) reach the route as bytes.
// Over the size limit the body is the error itself rather than a throw:
// a throw from the middleware path would land in onError, which answers
// 500. The route answers 413 (or a validation error) from it.
if (isRawBodyContentType(contentType)) {
return readBoundedRequestBody(c.req.raw, parseByteLimit(this.config.bodyParser.rawMaxSize));
}
return undefined;
}
}