Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).
On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:
- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
catch-all, not registration order), and 405 + Allow when a path exists
under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
`mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
147 lines
4.4 KiB
TypeScript
147 lines
4.4 KiB
TypeScript
import type { Bus } from '../bus';
|
|
import { HttpError } from '../signals';
|
|
import { encode, decode, type Manifest, type RequestEnvelope, type Frame } from './protocol';
|
|
|
|
let connSeq = 0; // module-level: deterministic unique connection-id prefix (no Date.now/Math.random)
|
|
|
|
/** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */
|
|
export interface Link {
|
|
manifest: Manifest;
|
|
rpc(kind: 'scope' | 'route', name: string, ctx: RequestEnvelope): Promise<unknown>;
|
|
close(): void;
|
|
}
|
|
|
|
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
|
|
type PendingEntry = {
|
|
resolve: (v: unknown) => void;
|
|
reject: (e: unknown) => void;
|
|
timer: ReturnType<typeof setTimeout>;
|
|
};
|
|
|
|
function loadWs(): any {
|
|
// lazy/optional, like streams; the ws CJS export is the WebSocket class
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
return require('ws');
|
|
}
|
|
|
|
/** Reject and clear every in-flight RPC — used when the link closes. */
|
|
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void {
|
|
for (const [, entry] of pending) {
|
|
clearTimeout(entry.timer);
|
|
entry.reject(new Error(reason));
|
|
}
|
|
|
|
pending.clear();
|
|
}
|
|
|
|
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
|
|
function sendRpc(
|
|
ws: any,
|
|
pending: Map<string, PendingEntry>,
|
|
id: string,
|
|
kind: 'scope' | 'route',
|
|
name: string,
|
|
ctx: RequestEnvelope,
|
|
timeoutMs: number,
|
|
): Promise<unknown> {
|
|
return new Promise((resolveCall, rejectCall) => {
|
|
const timer = setTimeout(() => {
|
|
pending.delete(id);
|
|
rejectCall(new Error(`mesh rpc timeout: ${name}`));
|
|
}, timeoutMs);
|
|
|
|
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
|
|
ws.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
|
});
|
|
}
|
|
|
|
/** Assemble the client-facing Link once the manifest arrives. */
|
|
function buildLink(
|
|
ws: any,
|
|
pending: Map<string, PendingEntry>,
|
|
manifest: Manifest,
|
|
connId: string,
|
|
timeoutMs: number,
|
|
): Link {
|
|
let counter = 0;
|
|
|
|
return {
|
|
manifest,
|
|
rpc(kind, name, ctx) {
|
|
const id = `${connId}:${counter++}`;
|
|
|
|
return sendRpc(ws, pending, id, kind, name, ctx, timeoutMs);
|
|
},
|
|
close() {
|
|
ws.close();
|
|
},
|
|
};
|
|
}
|
|
|
|
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
|
|
function settleRpcResponse(
|
|
pending: Map<string, PendingEntry>,
|
|
frame: Extract<Frame, { type: 'rpc-res' }>,
|
|
bus?: Bus,
|
|
): void {
|
|
const entry = pending.get(frame.id);
|
|
if (!entry) return;
|
|
pending.delete(frame.id);
|
|
clearTimeout(entry.timer);
|
|
|
|
if (frame.ok) {
|
|
entry.resolve(frame.result);
|
|
} else {
|
|
bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
|
|
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
|
}
|
|
}
|
|
|
|
/** Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest arrives. */
|
|
export function connectLink(args: { url: string; secret: string; timeoutMs?: number; bus?: Bus }): Promise<Link> {
|
|
const timeoutMs = args.timeoutMs ?? 30_000;
|
|
const WS = loadWs();
|
|
const ws = new WS(args.url);
|
|
const pending = new Map<string, PendingEntry>();
|
|
const connId = `c${connSeq++}`;
|
|
let manifest: Manifest | undefined;
|
|
|
|
return new Promise<Link>((resolve, reject) => {
|
|
const connectTimer = setTimeout(() => {
|
|
ws.close();
|
|
reject(new Error(`mesh connect timeout: ${args.url}`));
|
|
}, timeoutMs);
|
|
|
|
ws.on('open', () => ws.send(encode({ type: 'hello', secret: args.secret })));
|
|
ws.on('error', (error: unknown) => reject(error));
|
|
ws.on('close', () => {
|
|
clearTimeout(connectTimer);
|
|
args.bus?.emit('mesh:disconnect', { name: args.url });
|
|
rejectAllPending(pending, 'mesh link closed');
|
|
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
|
});
|
|
|
|
ws.on('message', (data: unknown) => {
|
|
let frame: Frame;
|
|
|
|
try {
|
|
frame = decode(String(data));
|
|
} catch {
|
|
return;
|
|
}
|
|
|
|
if (frame.type === 'manifest') {
|
|
manifest = { scopes: frame.scopes, routes: frame.routes };
|
|
clearTimeout(connectTimer);
|
|
args.bus?.emit('mesh:connect', { name: args.url });
|
|
resolve(buildLink(ws, pending, manifest, connId, timeoutMs));
|
|
return;
|
|
}
|
|
|
|
if (frame.type === 'rpc-res') {
|
|
settleRpcResponse(pending, frame, args.bus);
|
|
}
|
|
});
|
|
});
|
|
}
|