@dim24/servin 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.js ADDED
@@ -0,0 +1,1022 @@
1
+ import http from 'node:http';
2
+ import fsp from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { Readable } from 'node:stream';
6
+ import {
7
+ wire,
8
+ wireStorage,
9
+ createRequestContext,
10
+ runUndoStack,
11
+ flushDebugLogs,
12
+ getReactions,
13
+ ServinAbortError,
14
+ ServinRedirect
15
+ } from './wire.js';
16
+ import { SessionManager, MemorySessionStore } from './session.js';
17
+ import {
18
+ compileDomainTree,
19
+ matchDomainRoute,
20
+ generateVirtualClientModule
21
+ } from './tree.js';
22
+ import {
23
+ WebSocketBroker,
24
+ createLinearSocket,
25
+ performWsHandshake
26
+ } from './websocket.js';
27
+ import {
28
+ parseDuration,
29
+ applyFieldMask,
30
+ applyRedaction,
31
+ validateExpect,
32
+ FileStreamResponse,
33
+ HtmlResponse,
34
+ buildFileHttpResponse,
35
+ buildStaticHttpResponse,
36
+ createLagMonitor
37
+ } from './utils.js';
38
+
39
+ function toWebRequest(nodeReq, host, port, signal) {
40
+ const proto = nodeReq.socket?.encrypted ? 'https' : 'http';
41
+ const reqHost = nodeReq.headers.host || `${host}:${port}`;
42
+ const url = new URL(nodeReq.url || '/', `${proto}://${reqHost}`);
43
+
44
+ const headers = new Headers();
45
+ for (const [k, v] of Object.entries(nodeReq.headers)) {
46
+ if (Array.isArray(v)) {
47
+ for (const item of v) headers.append(k, item);
48
+ } else if (v !== undefined) {
49
+ headers.set(k, v);
50
+ }
51
+ }
52
+
53
+ const hasBody = nodeReq.method !== 'GET' && nodeReq.method !== 'HEAD';
54
+ return new Request(url, {
55
+ method: nodeReq.method,
56
+ headers,
57
+ body: hasBody ? Readable.toWeb(nodeReq) : null,
58
+ duplex: hasBody ? 'half' : undefined,
59
+ signal
60
+ });
61
+ }
62
+
63
+ async function parseBodyPayload(req, webhookConfig) {
64
+ const rawBuffer = Buffer.from(await req.arrayBuffer());
65
+
66
+ if (webhookConfig) {
67
+ const sigHeader = req.headers.get(webhookConfig.header);
68
+ if (!sigHeader) {
69
+ throw new ServinAbortError(401, 'Missing webhook signature header');
70
+ }
71
+ const algo = webhookConfig.algo || 'sha256';
72
+ const expected = crypto
73
+ .createHmac(algo, webhookConfig.secret)
74
+ .update(rawBuffer)
75
+ .digest('hex');
76
+
77
+ const cleanSig = sigHeader.replace(/^sha\d+=/i, '');
78
+ const bufA = Buffer.from(expected, 'utf8');
79
+ const bufB = Buffer.from(cleanSig, 'utf8');
80
+
81
+ if (bufA.length !== bufB.length || !crypto.timingSafeEqual(bufA, bufB)) {
82
+ throw new ServinAbortError(401, 'Invalid webhook HMAC signature');
83
+ }
84
+ }
85
+
86
+ if (rawBuffer.length === 0) return {};
87
+ const text = rawBuffer.toString('utf8');
88
+ const ct = req.headers.get('content-type') || '';
89
+
90
+ if (ct.includes('application/x-www-form-urlencoded')) {
91
+ return Object.fromEntries(new URLSearchParams(text).entries());
92
+ }
93
+ try {
94
+ return JSON.parse(text);
95
+ } catch {
96
+ return text;
97
+ }
98
+ }
99
+
100
+ export function serve(config = {}) {
101
+ const port = config.port ?? 3000;
102
+ const host = config.host ?? '127.0.0.1';
103
+ const silent = config.silent ?? false;
104
+ const routes = compileDomainTree(config.api || {}, config.types || {}, config.static || null);
105
+ const virtualClientCode = generateVirtualClientModule(routes);
106
+
107
+ const broker = new WebSocketBroker();
108
+ const sessionManager = config.session ? new SessionManager(config.session, broker) : null;
109
+ const lagMonitor = createLagMonitor(config.lagThresholdMs ?? 60);
110
+ const rateBuckets = new Map();
111
+ const activeDefers = new Set();
112
+ const recordedTests = new Map();
113
+
114
+ const deferTracker = {
115
+ track(promise) {
116
+ activeDefers.add(promise);
117
+ promise.finally(() => activeDefers.delete(promise));
118
+ }
119
+ };
120
+
121
+ function emitAccessLog(info) {
122
+ if (silent || config.accessLog === false) return;
123
+
124
+ if (typeof config.accessLog === 'function') {
125
+ const customLine = config.accessLog(info);
126
+ if (typeof customLine === 'string' && customLine.length > 0) {
127
+ console.log(customLine);
128
+ }
129
+ return;
130
+ }
131
+
132
+ const tags = [];
133
+ if (info.cached) tags.push('CACHE');
134
+ if (info.simulated) tags.push('SIMULATE');
135
+ const suffix = tags.length > 0 ? ` [${tags.join(',')}]` : '';
136
+
137
+ console.log(
138
+ `[servin] ${info.method} ${info.url.pathname}${info.url.search} ${info.status} ${info.durationMs.toFixed(1)}ms${suffix}`
139
+ );
140
+ }
141
+
142
+ function applyCorsHeaders(req, headers) {
143
+ if (!config.origins || config.origins.length === 0) return;
144
+ const origin = req.headers.get('origin');
145
+ if (!origin) return;
146
+ if (config.origins.includes('*') || config.origins.includes(origin)) {
147
+ headers.set('Access-Control-Allow-Origin', origin);
148
+ headers.set('Access-Control-Allow-Credentials', 'true');
149
+ headers.set('Vary', 'Origin');
150
+ }
151
+ }
152
+
153
+ function findErrorHandler(status) {
154
+ const errorsCfg = config.errors;
155
+ if (!errorsCfg || typeof errorsCfg !== 'object') return null;
156
+
157
+ if (Object.prototype.hasOwnProperty.call(errorsCfg, status)) {
158
+ return errorsCfg[status];
159
+ }
160
+ const statusStr = String(status);
161
+ if (Object.prototype.hasOwnProperty.call(errorsCfg, statusStr)) {
162
+ return errorsCfg[statusStr];
163
+ }
164
+ if (status >= 400 && status < 500 && errorsCfg['4xx']) {
165
+ return errorsCfg['4xx'];
166
+ }
167
+ if (status >= 500 && errorsCfg['5xx']) {
168
+ return errorsCfg['5xx'];
169
+ }
170
+ return errorsCfg.default ?? null;
171
+ }
172
+
173
+ async function buildErrorResponse({ webReq, status, defaultPayload, existingCtx = null, rawError = null, extraHeaders = null }) {
174
+ const handler = findErrorHandler(status);
175
+ const url = existingCtx?.url || new URL(webReq.url);
176
+ const method = existingCtx?.method || webReq.method.toUpperCase();
177
+
178
+ if (!handler) {
179
+ const headers = existingCtx?.outgoingHeaders || new Headers();
180
+ if (extraHeaders) {
181
+ for (const [k, v] of Object.entries(extraHeaders)) headers.set(k, v);
182
+ }
183
+ if (status === 405 && !defaultPayload) {
184
+ return new Response(null, { status: 405, headers });
185
+ }
186
+ return Response.json(defaultPayload || { error: 'Error' }, { status, headers });
187
+ }
188
+
189
+ const ctx = existingCtx || createRequestContext({
190
+ req: webReq,
191
+ method,
192
+ url,
193
+ signal: webReq.signal,
194
+ sessionManager,
195
+ broker,
196
+ deferTracker
197
+ });
198
+
199
+ if (!existingCtx) {
200
+ applyCorsHeaders(webReq, ctx.outgoingHeaders);
201
+ }
202
+ if (extraHeaders) {
203
+ for (const [k, v] of Object.entries(extraHeaders)) {
204
+ ctx.outgoingHeaders.set(k, v);
205
+ }
206
+ }
207
+
208
+ ctx.statusCode = status;
209
+ ctx.statusExplicit = false;
210
+
211
+ const runCustomizer = async () => {
212
+ try {
213
+ const result = typeof handler === 'function'
214
+ ? await handler({
215
+ status,
216
+ message: defaultPayload?.error || '',
217
+ details: defaultPayload?.details,
218
+ path: url.pathname,
219
+ method,
220
+ error: rawError,
221
+ wire
222
+ })
223
+ : handler;
224
+
225
+ if (!ctx.isSimulated) {
226
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders).catch(() => { });
227
+ }
228
+
229
+ if (result instanceof Response) return result;
230
+
231
+ if (result instanceof FileStreamResponse) {
232
+ const fileRes = await buildFileHttpResponse(result, webReq.headers, {
233
+ method,
234
+ statusOverride: ctx.statusCode
235
+ });
236
+ ctx.outgoingHeaders.forEach((v, k) => {
237
+ if (!fileRes.headers.has(k)) fileRes.headers.set(k, v);
238
+ });
239
+ return fileRes;
240
+ }
241
+
242
+ if (result instanceof HtmlResponse) {
243
+ if (!ctx.outgoingHeaders.has('content-type')) {
244
+ ctx.outgoingHeaders.set('Content-Type', 'text/html; charset=utf-8');
245
+ }
246
+ return new Response(result.html, {
247
+ status: ctx.statusCode,
248
+ headers: ctx.outgoingHeaders
249
+ });
250
+ }
251
+
252
+ if (typeof result === 'string') {
253
+ if (!ctx.outgoingHeaders.has('content-type')) {
254
+ ctx.outgoingHeaders.set('Content-Type', 'text/plain; charset=utf-8');
255
+ }
256
+ return new Response(result, {
257
+ status: ctx.statusCode,
258
+ headers: ctx.outgoingHeaders
259
+ });
260
+ }
261
+
262
+ if (result === null || result === undefined) {
263
+ return new Response(null, { status: ctx.statusCode, headers: ctx.outgoingHeaders });
264
+ }
265
+
266
+ return Response.json(result, {
267
+ status: ctx.statusCode,
268
+ headers: ctx.outgoingHeaders
269
+ });
270
+ } catch (err) {
271
+ if (err instanceof ServinRedirect) {
272
+ if (!ctx.isSimulated) {
273
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders).catch(() => { });
274
+ }
275
+ ctx.outgoingHeaders.set('Location', err.location);
276
+ return new Response(null, { status: err.status, headers: ctx.outgoingHeaders });
277
+ }
278
+ return Response.json(defaultPayload || { error: 'Internal Server Error' }, {
279
+ status,
280
+ headers: ctx.outgoingHeaders
281
+ });
282
+ }
283
+ };
284
+
285
+ return existingCtx ? runCustomizer() : wireStorage.run(ctx, runCustomizer);
286
+ }
287
+
288
+ async function writeSnapshot(ctx, route, err) {
289
+ if (!config.snapshotOnError) return;
290
+ try {
291
+ await fsp.mkdir(config.snapshotOnError, { recursive: true });
292
+ const fileName = `err-${new Date().toISOString().replace(/[:.]/g, '-')}-${ctx.requestId}.json`;
293
+ const snapshot = {
294
+ timestamp: new Date().toISOString(),
295
+ dotPath: route?.dotPath || null,
296
+ method: ctx.method,
297
+ url: ctx.url.toString(),
298
+ headers: Object.fromEntries(ctx.req.headers.entries()),
299
+ error: { message: err.message, stack: err.stack }
300
+ };
301
+ await fsp.writeFile(
302
+ path.join(config.snapshotOnError, fileName),
303
+ JSON.stringify(snapshot, null, 2),
304
+ 'utf8'
305
+ );
306
+ } catch (snapErr) {
307
+ console.error('[servin] Failed writing error snapshot:', snapErr);
308
+ }
309
+ }
310
+
311
+ async function recordSyntheticTest(route, args, result, status) {
312
+ if (!config.synthesizeTests || !route || status >= 500) return;
313
+ const key = `${route.dotPath}:${status}`;
314
+ if (recordedTests.has(key)) return;
315
+
316
+ const urlPath = '/' + route.segments
317
+ .map((s, idx) => (s.type === 'static' ? s.value : encodeURIComponent(String(args[idx] ?? '1'))))
318
+ .join('/');
319
+
320
+ recordedTests.set(key, {
321
+ dotPath: route.dotPath,
322
+ method: route.verbs[0],
323
+ urlPath,
324
+ status,
325
+ hasBody: ['POST', 'PUT', 'PATCH'].includes(route.verbs[0]),
326
+ bodyArg: ['POST', 'PUT', 'PATCH'].includes(route.verbs[0]) ? args[route.paramNames.length] : undefined,
327
+ expected: result
328
+ });
329
+
330
+ const lines = [
331
+ "import test from 'node:test';",
332
+ "import assert from 'node:assert/strict';",
333
+ '',
334
+ `const BASE_URL = process.env.TEST_BASE_URL || 'http://${host}:${port}';`,
335
+ ''
336
+ ];
337
+
338
+ for (const item of recordedTests.values()) {
339
+ lines.push(`test('${item.dotPath} (${item.method} ${item.urlPath}) -> ${item.status}', async () => {`);
340
+ const fetchOpts = [`method: '${item.method}'`];
341
+ if (item.hasBody && item.bodyArg !== undefined) {
342
+ fetchOpts.push(`headers: { 'Content-Type': 'application/json' }`);
343
+ fetchOpts.push(`body: JSON.stringify(${JSON.stringify(item.bodyArg)})`);
344
+ }
345
+ lines.push(` const res = await fetch(\`\${BASE_URL}${item.urlPath}\`, { ${fetchOpts.join(', ')} });`);
346
+ lines.push(` assert.equal(res.status, ${item.status});`);
347
+ if (item.expected !== null && item.expected !== undefined && typeof item.expected === 'object') {
348
+ lines.push(` const body = await res.json();`);
349
+ lines.push(` assert.deepEqual(body, ${JSON.stringify(item.expected)});`);
350
+ }
351
+ lines.push('});', '');
352
+ }
353
+
354
+ try {
355
+ await fsp.mkdir(path.dirname(path.resolve(config.synthesizeTests)), { recursive: true });
356
+ await fsp.writeFile(config.synthesizeTests, lines.join('\n'), 'utf8');
357
+ } catch (e) {
358
+ console.error('[servin] Failed writing synthesized test:', e);
359
+ }
360
+ }
361
+
362
+ async function executeHttp(webReq, reqMeta) {
363
+ const url = new URL(webReq.url);
364
+ const method = webReq.method.toUpperCase();
365
+
366
+ if (method === 'GET' && url.pathname === '/@client.js') {
367
+ const headers = new Headers({
368
+ 'Content-Type': 'application/javascript; charset=utf-8',
369
+ 'Cache-Control': 'no-cache'
370
+ });
371
+ applyCorsHeaders(webReq, headers);
372
+ return new Response(virtualClientCode, { status: 200, headers });
373
+ }
374
+
375
+ const match = matchDomainRoute(routes, method, url.pathname);
376
+
377
+ if (method === 'OPTIONS' && match.status === 405) {
378
+ const headers = new Headers({
379
+ Allow: match.allow,
380
+ 'Access-Control-Allow-Methods': `${match.allow}, OPTIONS`,
381
+ 'Access-Control-Allow-Headers': webReq.headers.get('access-control-request-headers') || 'Content-Type, Authorization, Idempotency-Key, X-Simulate'
382
+ });
383
+ applyCorsHeaders(webReq, headers);
384
+ return new Response(null, { status: 204, headers });
385
+ }
386
+
387
+ if (match.status === 404) {
388
+ return buildErrorResponse({
389
+ webReq,
390
+ status: 404,
391
+ defaultPayload: { error: 'Not Found' }
392
+ });
393
+ }
394
+ if (match.status === 405) {
395
+ return buildErrorResponse({
396
+ webReq,
397
+ status: 405,
398
+ defaultPayload: null,
399
+ extraHeaders: { Allow: match.allow }
400
+ });
401
+ }
402
+
403
+ const { route, params } = match;
404
+
405
+ if (route.meta.priority === 'low' && lagMonitor.isOverloaded()) {
406
+ return buildErrorResponse({
407
+ webReq,
408
+ status: 503,
409
+ defaultPayload: { error: 'Service temporarily overloaded' },
410
+ extraHeaders: { 'Retry-After': '2' }
411
+ });
412
+ }
413
+
414
+ const ctx = createRequestContext({
415
+ req: webReq,
416
+ method,
417
+ url,
418
+ signal: webReq.signal,
419
+ sessionManager,
420
+ broker,
421
+ deferTracker
422
+ });
423
+
424
+ reqMeta.requestId = ctx.requestId;
425
+ reqMeta.simulated = ctx.isSimulated;
426
+
427
+ applyCorsHeaders(webReq, ctx.outgoingHeaders);
428
+
429
+ if (route.meta.sunset) {
430
+ ctx.outgoingHeaders.set('Deprecation', 'true');
431
+ ctx.outgoingHeaders.set('Sunset', new Date(route.meta.sunset).toUTCString());
432
+ }
433
+
434
+ return wireStorage.run(ctx, async () => {
435
+ let activeLimiterBucket = null;
436
+ let limiterMax = 0;
437
+
438
+ try {
439
+ if (ctx.sessionHandle && !(sessionManager.store instanceof MemorySessionStore)) {
440
+ await ctx.sessionHandle.preload();
441
+ }
442
+
443
+ for (const guardFn of route.guards) {
444
+ await guardFn();
445
+ }
446
+
447
+ // Handle declarative RedirectDescriptor
448
+ if (route.redirectDescriptor) {
449
+ const paramValues = route.paramNames.map((name) => params[name]);
450
+ const queryObj = Object.fromEntries(url.searchParams.entries());
451
+ const targetUrl = typeof route.redirectDescriptor.target === 'function'
452
+ ? await route.redirectDescriptor.target(...paramValues, queryObj)
453
+ : route.redirectDescriptor.target;
454
+
455
+ if (!ctx.isSimulated) {
456
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
457
+ }
458
+ ctx.outgoingHeaders.set('Location', String(targetUrl));
459
+ return new Response(null, {
460
+ status: route.redirectDescriptor.status,
461
+ headers: ctx.outgoingHeaders
462
+ });
463
+ }
464
+
465
+ // Handle StaticRouteDescriptor (file or folder)
466
+ if (route.staticDescriptor) {
467
+ const staticRes = await buildStaticHttpResponse(
468
+ route.staticDescriptor,
469
+ params.subpath || '',
470
+ webReq.headers,
471
+ method
472
+ );
473
+
474
+ if (staticRes.errorStatus) {
475
+ return buildErrorResponse({
476
+ webReq,
477
+ status: staticRes.errorStatus,
478
+ defaultPayload: { error: staticRes.message },
479
+ existingCtx: ctx
480
+ });
481
+ }
482
+
483
+ if (!ctx.isSimulated) {
484
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
485
+ }
486
+ ctx.outgoingHeaders.forEach((v, k) => {
487
+ if (!staticRes.response.headers.has(k)) {
488
+ staticRes.response.headers.set(k, v);
489
+ }
490
+ });
491
+ return staticRes.response;
492
+ }
493
+
494
+ const paramValues = route.paramNames.map((name) => params[name]);
495
+ const queryObj = Object.fromEntries(url.searchParams.entries());
496
+ const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
497
+ const contentType = webReq.headers.get('content-type') || '';
498
+ const isMultipart = contentType.toLowerCase().startsWith('multipart/form-data');
499
+
500
+ let payload;
501
+ const shouldParseBody = hasBody && !route.meta.rawBody && (!isMultipart || Boolean(route.meta.webhook));
502
+
503
+ if (shouldParseBody) {
504
+ payload = await parseBodyPayload(webReq, route.meta.webhook);
505
+ if (route.meta.expect) {
506
+ const validationErrors = validateExpect(payload, route.meta.expect);
507
+ if (validationErrors.length > 0) {
508
+ if (!ctx.isSimulated) await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
509
+ return buildErrorResponse({
510
+ webReq,
511
+ status: 422,
512
+ defaultPayload: { error: 'Validation Failed', details: validationErrors },
513
+ existingCtx: ctx
514
+ });
515
+ }
516
+ }
517
+ }
518
+
519
+ if (route.meta.limit) {
520
+ const { max, window: winStr, key: keyFn } = route.meta.limit;
521
+ const windowMs = parseDuration(winStr, 60_000);
522
+ const customKey = typeof keyFn === 'function' ? keyFn(payload) : null;
523
+ const bucketKey = `${route.nodeId}:${customKey || webReq.headers.get('x-forwarded-for') || 'global'}`;
524
+ const now = Date.now();
525
+
526
+ let bucket = rateBuckets.get(bucketKey);
527
+ if (!bucket || bucket.resetAt <= now) {
528
+ bucket = { remaining: max, resetAt: now + windowMs };
529
+ rateBuckets.set(bucketKey, bucket);
530
+ }
531
+
532
+ if (bucket.remaining <= 0) {
533
+ const retrySec = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000));
534
+ return buildErrorResponse({
535
+ webReq,
536
+ status: 429,
537
+ defaultPayload: { error: 'Too Many Requests' },
538
+ existingCtx: ctx,
539
+ extraHeaders: { 'Retry-After': String(retrySec) }
540
+ });
541
+ }
542
+
543
+ activeLimiterBucket = bucket;
544
+ limiterMax = max;
545
+ }
546
+
547
+ const handlerArgs = shouldParseBody
548
+ ? [...paramValues, payload, queryObj]
549
+ : [...paramValues, queryObj];
550
+
551
+ // SSE Async Generator Streaming
552
+ if (route.isAsyncGen) {
553
+ if (!ctx.isSimulated) await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
554
+ ctx.outgoingHeaders.set('Content-Type', 'text/event-stream; charset=utf-8');
555
+ ctx.outgoingHeaders.set('Cache-Control', 'no-cache');
556
+ ctx.outgoingHeaders.set('Connection', 'keep-alive');
557
+ ctx.headersSent = true;
558
+
559
+ const iterator = route.handler(...handlerArgs);
560
+ const stream = new ReadableStream({
561
+ async pull(controller) {
562
+ try {
563
+ const { done, value } = await iterator.next();
564
+ if (done) {
565
+ controller.close();
566
+ return;
567
+ }
568
+ const frame = `data: ${JSON.stringify(value)}\n\n`;
569
+ controller.enqueue(new TextEncoder().encode(frame));
570
+ } catch (err) {
571
+ controller.error(err);
572
+ }
573
+ },
574
+ async cancel() {
575
+ await iterator.return?.();
576
+ await runUndoStack(ctx);
577
+ }
578
+ });
579
+
580
+ return new Response(stream, { status: ctx.statusCode, headers: ctx.outgoingHeaders });
581
+ }
582
+
583
+ // Idempotency Check for Mutations
584
+ const idemHeader = webReq.headers.get('idempotency-key');
585
+ const idemKey = route.nodeIdempotency && idemHeader ? `${route.nodeId}:${idemHeader}` : null;
586
+ if (idemKey && !ctx.isSimulated) {
587
+ const cachedIdem = route.nodeIdempotency.get(idemKey);
588
+ if (cachedIdem && cachedIdem.expiresAt > Date.now()) {
589
+ const stored = await cachedIdem.promise;
590
+ return Response.json(stored.body, {
591
+ status: stored.status,
592
+ headers: ctx.outgoingHeaders
593
+ });
594
+ }
595
+ }
596
+
597
+ // Self-Invalidating Cache Lookup for GET
598
+ const cacheKey = route.nodeCache && method === 'GET'
599
+ ? `${route.nodeId}:${JSON.stringify(params)}:${url.search}`
600
+ : null;
601
+
602
+ if (cacheKey) {
603
+ const cached = route.nodeCache.get(cacheKey);
604
+ if (cached && cached.expiresAt > Date.now()) {
605
+ reqMeta.cached = true;
606
+ if (!ctx.isSimulated) await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
607
+ return Response.json(cached.value, { status: 200, headers: ctx.outgoingHeaders });
608
+ }
609
+ }
610
+
611
+ const executeHandler = async () => {
612
+ const out = await route.handler(...handlerArgs);
613
+ if (ctx.isSimulated) {
614
+ await runUndoStack(ctx);
615
+ } else {
616
+ for (const observer of getReactions(route.handler)) {
617
+ const reactionTask = Promise.resolve().then(() =>
618
+ observer({ input: handlerArgs, output: out, wire })
619
+ );
620
+ deferTracker.track(reactionTask);
621
+ }
622
+ }
623
+ return out;
624
+ };
625
+
626
+ let rawResult;
627
+ if (route.nodeInFlight && method === 'GET') {
628
+ const coalKey = `${route.nodeId}:${JSON.stringify(params)}:${url.search}`;
629
+ let sharedPromise = route.nodeInFlight.get(coalKey);
630
+ if (!sharedPromise) {
631
+ sharedPromise = executeHandler().finally(() => route.nodeInFlight.delete(coalKey));
632
+ route.nodeInFlight.set(coalKey, sharedPromise);
633
+ }
634
+ rawResult = await sharedPromise;
635
+ } else if (idemKey && !ctx.isSimulated) {
636
+ const ttlMs = parseDuration(route.meta.idempotent, 600_000);
637
+ const workPromise = executeHandler().then((res) => ({
638
+ status: ctx.statusCode,
639
+ body: res
640
+ }));
641
+ route.nodeIdempotency.set(idemKey, {
642
+ expiresAt: Date.now() + ttlMs,
643
+ promise: workPromise
644
+ });
645
+ const settled = await workPromise;
646
+ rawResult = settled.body;
647
+ } else {
648
+ rawResult = await executeHandler();
649
+ }
650
+
651
+ // Invalidate node cache and ancestor caches on successful mutations
652
+ if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !ctx.isSimulated) {
653
+ if (route.nodeCache) {
654
+ const prefix = `${route.nodeId}:${JSON.stringify(params)}:`;
655
+ for (const k of route.nodeCache.keys()) {
656
+ if (k.startsWith(prefix) || Object.keys(params).length === 0) {
657
+ route.nodeCache.delete(k);
658
+ }
659
+ }
660
+ }
661
+ if (route.ancestorCaches && route.ancestorCaches.length > 0) {
662
+ for (const ancCache of route.ancestorCaches) {
663
+ ancCache.clear();
664
+ }
665
+ }
666
+ }
667
+
668
+ if (!ctx.isSimulated) {
669
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
670
+ }
671
+ ctx.headersSent = true;
672
+
673
+ if (ctx.timings.length > 0) {
674
+ const timingHeader = ctx.timings
675
+ .map((t) => `${t.label};dur=${t.dur.toFixed(2)}`)
676
+ .join(', ');
677
+ ctx.outgoingHeaders.set('Server-Timing', timingHeader);
678
+ }
679
+
680
+ if (rawResult instanceof Response) {
681
+ return rawResult;
682
+ }
683
+
684
+ if (rawResult instanceof FileStreamResponse) {
685
+ const fileRes = await buildFileHttpResponse(rawResult, webReq.headers, {
686
+ method,
687
+ returnMissing: true
688
+ });
689
+ if (!fileRes) {
690
+ return buildErrorResponse({
691
+ webReq,
692
+ status: 404,
693
+ defaultPayload: { error: 'File Not Found' },
694
+ existingCtx: ctx
695
+ });
696
+ }
697
+ return fileRes;
698
+ }
699
+
700
+ if (rawResult instanceof HtmlResponse) {
701
+ if (!ctx.outgoingHeaders.has('content-type')) {
702
+ ctx.outgoingHeaders.set('Content-Type', 'text/html; charset=utf-8');
703
+ }
704
+ await recordSyntheticTest(route, handlerArgs, rawResult.html, ctx.statusCode);
705
+ return new Response(rawResult.html, {
706
+ status: ctx.statusCode,
707
+ headers: ctx.outgoingHeaders
708
+ });
709
+ }
710
+
711
+ if (rawResult === null || rawResult === undefined) {
712
+ const status = ctx.statusExplicit ? ctx.statusCode : 204;
713
+ await recordSyntheticTest(route, handlerArgs, null, status);
714
+ return new Response(null, { status, headers: ctx.outgoingHeaders });
715
+ }
716
+
717
+ if (typeof rawResult === 'string') {
718
+ if (!ctx.outgoingHeaders.has('content-type')) {
719
+ ctx.outgoingHeaders.set('Content-Type', 'text/plain; charset=utf-8');
720
+ }
721
+ await recordSyntheticTest(route, handlerArgs, rawResult, ctx.statusCode);
722
+ return new Response(rawResult, { status: ctx.statusCode, headers: ctx.outgoingHeaders });
723
+ }
724
+
725
+ if (rawResult instanceof ReadableStream || rawResult instanceof Uint8Array) {
726
+ return new Response(rawResult, { status: ctx.statusCode, headers: ctx.outgoingHeaders });
727
+ }
728
+
729
+ let cleanOutput = applyRedaction(rawResult, config.redact);
730
+ if (method === 'GET' && url.searchParams.has('fields')) {
731
+ cleanOutput = applyFieldMask(cleanOutput, url.searchParams.get('fields'));
732
+ }
733
+
734
+ if (cacheKey && !ctx.isSimulated) {
735
+ const ttlMs = parseDuration(route.meta.cache, 60_000);
736
+ route.nodeCache.set(cacheKey, {
737
+ value: cleanOutput,
738
+ expiresAt: Date.now() + ttlMs
739
+ });
740
+ }
741
+
742
+ await recordSyntheticTest(route, handlerArgs, cleanOutput, ctx.statusCode);
743
+ return Response.json(cleanOutput, {
744
+ status: ctx.statusCode,
745
+ headers: ctx.outgoingHeaders
746
+ });
747
+ } catch (err) {
748
+ if (err instanceof ServinRedirect) {
749
+ if (ctx.isSimulated) {
750
+ await runUndoStack(ctx);
751
+ } else {
752
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
753
+ }
754
+ ctx.outgoingHeaders.set('Location', err.location);
755
+ return new Response(null, {
756
+ status: err.status,
757
+ headers: ctx.outgoingHeaders
758
+ });
759
+ }
760
+
761
+ await runUndoStack(ctx);
762
+ if (!ctx.isSimulated) {
763
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders).catch(() => { });
764
+ }
765
+
766
+ if (err instanceof ServinAbortError) {
767
+ return buildErrorResponse({
768
+ webReq,
769
+ status: err.status,
770
+ defaultPayload: { error: err.message },
771
+ existingCtx: ctx,
772
+ rawError: err
773
+ });
774
+ }
775
+
776
+ flushDebugLogs(ctx, err);
777
+ await writeSnapshot(ctx, route, err);
778
+
779
+ if (config.onError) {
780
+ const custom = await config.onError(err, { req: webReq });
781
+ if (custom instanceof Response) return custom;
782
+ return Response.json(custom, { status: 500, headers: ctx.outgoingHeaders });
783
+ }
784
+
785
+ return buildErrorResponse({
786
+ webReq,
787
+ status: 500,
788
+ defaultPayload: { error: 'Internal Server Error' },
789
+ existingCtx: ctx,
790
+ rawError: err
791
+ });
792
+ } finally {
793
+ if (activeLimiterBucket) {
794
+ const cost = ctx.costExplicit ? ctx.costPoints : 1;
795
+ activeLimiterBucket.remaining = Math.max(
796
+ 0,
797
+ Math.min(limiterMax, activeLimiterBucket.remaining - cost)
798
+ );
799
+ }
800
+ }
801
+ });
802
+ }
803
+
804
+ async function handleHttp(webReq, socketIp = null) {
805
+ const t0 = performance.now();
806
+ const url = new URL(webReq.url);
807
+ const reqMeta = { cached: false, simulated: false, requestId: null };
808
+ const res = await executeHttp(webReq, reqMeta);
809
+
810
+ emitAccessLog({
811
+ method: webReq.method.toUpperCase(),
812
+ url,
813
+ status: res.status,
814
+ durationMs: performance.now() - t0,
815
+ cached: reqMeta.cached,
816
+ simulated: reqMeta.simulated,
817
+ requestId: reqMeta.requestId,
818
+ ip: webReq.headers.get('x-forwarded-for') || socketIp || 'unknown',
819
+ userAgent: webReq.headers.get('user-agent') || ''
820
+ });
821
+
822
+ return res;
823
+ }
824
+
825
+ const httpServer = http.createServer(async (nodeReq, nodeRes) => {
826
+ const abortCtrl = new AbortController();
827
+ nodeReq.on('close', () => {
828
+ if (!nodeReq.complete) abortCtrl.abort();
829
+ });
830
+
831
+ try {
832
+ const webReq = toWebRequest(nodeReq, host, port, abortCtrl.signal);
833
+ const webRes = await handleHttp(webReq, nodeReq.socket?.remoteAddress || null);
834
+
835
+ nodeRes.statusCode = webRes.status;
836
+ webRes.headers.forEach((val, key) => {
837
+ nodeRes.appendHeader(key, val);
838
+ });
839
+
840
+ if (!webRes.body) {
841
+ nodeRes.end();
842
+ return;
843
+ }
844
+
845
+ const reader = webRes.body.getReader();
846
+ while (true) {
847
+ const { done, value } = await reader.read();
848
+ if (done) break;
849
+ nodeRes.write(value);
850
+ }
851
+ nodeRes.end();
852
+ } catch {
853
+ if (!nodeRes.headersSent) {
854
+ nodeRes.statusCode = 400;
855
+ nodeRes.end('Bad Request');
856
+ }
857
+ }
858
+ });
859
+
860
+ httpServer.on('upgrade', async (nodeReq, tcpSocket, head) => {
861
+ const t0 = performance.now();
862
+ const proto = nodeReq.socket?.encrypted ? 'https' : 'http';
863
+ const reqHost = nodeReq.headers.host || `${host}:${port}`;
864
+ const url = new URL(nodeReq.url || '/', `${proto}://${reqHost}`);
865
+ const clientIp = nodeReq.headers['x-forwarded-for'] || tcpSocket.remoteAddress || 'unknown';
866
+ const userAgent = nodeReq.headers['user-agent'] || '';
867
+
868
+ const match = matchDomainRoute(routes, 'WS', url.pathname);
869
+ if (match.status !== 200) {
870
+ tcpSocket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
871
+ tcpSocket.destroy();
872
+ emitAccessLog({
873
+ method: 'WS',
874
+ url,
875
+ status: 404,
876
+ durationMs: performance.now() - t0,
877
+ cached: false,
878
+ simulated: false,
879
+ requestId: null,
880
+ ip: clientIp,
881
+ userAgent
882
+ });
883
+ return;
884
+ }
885
+
886
+ const webHeaders = new Headers();
887
+ for (const [k, v] of Object.entries(nodeReq.headers)) {
888
+ if (typeof v === 'string') webHeaders.set(k, v);
889
+ }
890
+ const syntheticReq = new Request(url, { method: 'GET', headers: webHeaders });
891
+
892
+ const ctx = createRequestContext({
893
+ req: syntheticReq,
894
+ method: 'WS',
895
+ url,
896
+ sessionManager,
897
+ broker,
898
+ deferTracker
899
+ });
900
+
901
+ await wireStorage.run(ctx, async () => {
902
+ try {
903
+ if (ctx.sessionHandle && !(sessionManager.store instanceof MemorySessionStore)) {
904
+ await ctx.sessionHandle.preload();
905
+ }
906
+
907
+ for (const guardFn of match.route.guards) {
908
+ await guardFn();
909
+ }
910
+
911
+ await ctx.sessionHandle?.commit(ctx.outgoingHeaders);
912
+ ctx.headersSent = true;
913
+
914
+ const upgraded = performWsHandshake(nodeReq, tcpSocket, ctx.outgoingHeaders);
915
+ if (!upgraded) {
916
+ tcpSocket.destroy();
917
+ return;
918
+ }
919
+
920
+ emitAccessLog({
921
+ method: 'WS',
922
+ url,
923
+ status: 101,
924
+ durationMs: performance.now() - t0,
925
+ cached: false,
926
+ simulated: false,
927
+ requestId: ctx.requestId,
928
+ ip: clientIp,
929
+ userAgent
930
+ });
931
+
932
+ const sid = ctx.sessionHandle?.sid || null;
933
+ const linearSocket = createLinearSocket(
934
+ tcpSocket,
935
+ head,
936
+ broker,
937
+ match.route.meta.wsConfig,
938
+ sid
939
+ );
940
+
941
+ const paramValues = match.route.paramNames.map((n) => match.params[n]);
942
+ await match.route.handler(...paramValues, linearSocket);
943
+ linearSocket.close(1000, 'Session completed');
944
+ } catch (err) {
945
+ if (err instanceof ServinAbortError) {
946
+ tcpSocket.write(`HTTP/1.1 ${err.status} ${err.message}\r\nConnection: close\r\n\r\n`);
947
+ tcpSocket.destroy();
948
+ emitAccessLog({
949
+ method: 'WS',
950
+ url,
951
+ status: err.status,
952
+ durationMs: performance.now() - t0,
953
+ cached: false,
954
+ simulated: false,
955
+ requestId: ctx.requestId,
956
+ ip: clientIp,
957
+ userAgent
958
+ });
959
+ return;
960
+ }
961
+ flushDebugLogs(ctx, err);
962
+ tcpSocket.write('HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n');
963
+ tcpSocket.destroy();
964
+ emitAccessLog({
965
+ method: 'WS',
966
+ url,
967
+ status: 500,
968
+ durationMs: performance.now() - t0,
969
+ cached: false,
970
+ simulated: false,
971
+ requestId: ctx.requestId,
972
+ ip: clientIp,
973
+ userAgent
974
+ });
975
+ } finally {
976
+ await runUndoStack(ctx);
977
+ }
978
+ });
979
+ });
980
+
981
+ const shutdown = async () => {
982
+ lagMonitor.stop();
983
+ await new Promise((resolve) => httpServer.close(resolve));
984
+ if (activeDefers.size > 0) {
985
+ await Promise.allSettled([...activeDefers]);
986
+ }
987
+ };
988
+
989
+ process.once('SIGTERM', shutdown);
990
+ process.once('SIGINT', shutdown);
991
+
992
+ return new Promise((resolve) => {
993
+ httpServer.listen(port, host, async () => {
994
+ const addr = httpServer.address();
995
+ const actualPort = typeof addr === 'object' && addr ? addr.port : port;
996
+ const serverUrl = `http://${host}:${actualPort}`;
997
+ const listenInfo = { port: actualPort, host, url: serverUrl };
998
+
999
+ if (!silent && config.message !== false) {
1000
+ const startupText = typeof config.message === 'function'
1001
+ ? config.message(listenInfo)
1002
+ : (config.message ?? `[servin] listening on ${serverUrl}`);
1003
+
1004
+ if (startupText) {
1005
+ console.log(startupText);
1006
+ }
1007
+ }
1008
+
1009
+ if (typeof config.onListen === 'function') {
1010
+ await config.onListen(listenInfo);
1011
+ }
1012
+
1013
+ resolve({
1014
+ server: httpServer,
1015
+ port: actualPort,
1016
+ url: serverUrl,
1017
+ fetch: handleHttp,
1018
+ close: shutdown
1019
+ });
1020
+ });
1021
+ });
1022
+ }