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