@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.
@@ -0,0 +1,311 @@
1
+ import crypto from 'node:crypto';
2
+ import { parseBytes, parseDuration } from './utils.js';
3
+
4
+ const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
5
+
6
+ function encodeFrame(data, isBinary = false) {
7
+ const payload = isBinary
8
+ ? Buffer.from(data)
9
+ : Buffer.from(typeof data === 'string' ? data : JSON.stringify(data), 'utf8');
10
+
11
+ const opcode = isBinary ? 0x82 : 0x81;
12
+ const len = payload.length;
13
+
14
+ let header;
15
+ if (len < 126) {
16
+ header = Buffer.alloc(2);
17
+ header[0] = opcode;
18
+ header[1] = len;
19
+ } else if (len <= 0xffff) {
20
+ header = Buffer.alloc(4);
21
+ header[0] = opcode;
22
+ header[1] = 126;
23
+ header.writeUInt16BE(len, 2);
24
+ } else {
25
+ header = Buffer.alloc(10);
26
+ header[0] = opcode;
27
+ header[1] = 127;
28
+ header.writeBigUInt64BE(BigInt(len), 2);
29
+ }
30
+
31
+ return Buffer.concat([header, payload]);
32
+ }
33
+
34
+ function encodeControlFrame(opcode, payload = Buffer.alloc(0)) {
35
+ const header = Buffer.alloc(2);
36
+ header[0] = 0x80 | opcode;
37
+ header[1] = payload.length;
38
+ return Buffer.concat([header, payload]);
39
+ }
40
+
41
+ export class WebSocketBroker {
42
+ constructor() {
43
+ this.topics = new Map();
44
+ this.sessionSockets = new Map();
45
+ }
46
+
47
+ subscribe(topic, socket) {
48
+ if (!this.topics.has(topic)) this.topics.set(topic, new Set());
49
+ this.topics.get(topic).add(socket);
50
+ }
51
+
52
+ unsubscribe(topic, socket) {
53
+ const set = this.topics.get(topic);
54
+ if (set) {
55
+ set.delete(socket);
56
+ if (set.size === 0) this.topics.delete(topic);
57
+ }
58
+ }
59
+
60
+ publish(topic, data, excludeSocket = null) {
61
+ const set = this.topics.get(topic);
62
+ if (!set) return;
63
+ const isBinary = data instanceof Uint8Array;
64
+ const frame = encodeFrame(data, isBinary);
65
+ for (const client of set) {
66
+ if (client !== excludeSocket && client.isOpen) {
67
+ client.rawSocket.write(frame);
68
+ }
69
+ }
70
+ }
71
+
72
+ bindSession(sid, socket) {
73
+ if (!sid) return;
74
+ if (!this.sessionSockets.has(sid)) this.sessionSockets.set(sid, new Set());
75
+ this.sessionSockets.get(sid).add(socket);
76
+ }
77
+
78
+ unbindSession(sid, socket) {
79
+ if (!sid) return;
80
+ const set = this.sessionSockets.get(sid);
81
+ if (set) {
82
+ set.delete(socket);
83
+ if (set.size === 0) this.sessionSockets.delete(sid);
84
+ }
85
+ }
86
+
87
+ kickSession(sid) {
88
+ const set = this.sessionSockets.get(sid);
89
+ if (!set) return;
90
+ for (const client of [...set]) {
91
+ client.close(4001, 'Session revoked');
92
+ }
93
+ this.sessionSockets.delete(sid);
94
+ }
95
+ }
96
+
97
+ export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, sessionId = null) {
98
+ const maxPayload = parseBytes(config.maxPayload || '1mb', 1024 ** 2);
99
+ const heartbeatMs = config.heartbeat ? parseDuration(config.heartbeat, 0) : 0;
100
+ const binaryMode = Boolean(config.binary);
101
+
102
+ const joinedTopics = new Set();
103
+ const messageQueue = [];
104
+ let waitResolver = null;
105
+ let closed = false;
106
+ let alive = true;
107
+ let recvBuffer = headBuffer && headBuffer.length > 0 ? Buffer.from(headBuffer) : Buffer.alloc(0);
108
+ let fragmentedChunks = [];
109
+ let fragmentedOpcode = 0;
110
+
111
+ const wakeReader = () => {
112
+ if (waitResolver) {
113
+ const fn = waitResolver;
114
+ waitResolver = null;
115
+ fn();
116
+ }
117
+ };
118
+
119
+ const cleanup = () => {
120
+ if (closed) return;
121
+ closed = true;
122
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
123
+ for (const topic of joinedTopics) {
124
+ broker.unsubscribe(topic, sessionSocket);
125
+ }
126
+ joinedTopics.clear();
127
+ if (sessionId) broker.unbindSession(sessionId, sessionSocket);
128
+ wakeReader();
129
+ };
130
+
131
+ const sessionSocket = {
132
+ rawSocket: tcpSocket,
133
+ get isOpen() {
134
+ return !closed && !tcpSocket.destroyed;
135
+ },
136
+ get bufferedAmount() {
137
+ return tcpSocket.writableLength || 0;
138
+ },
139
+ join(topic) {
140
+ joinedTopics.add(topic);
141
+ broker.subscribe(topic, sessionSocket);
142
+ },
143
+ leave(topic) {
144
+ joinedTopics.delete(topic);
145
+ broker.unsubscribe(topic, sessionSocket);
146
+ },
147
+ broadcast(topic, data) {
148
+ broker.publish(topic, data, sessionSocket);
149
+ },
150
+ send(data) {
151
+ if (!sessionSocket.isOpen) return;
152
+ const isBin = data instanceof Uint8Array || binaryMode;
153
+ tcpSocket.write(encodeFrame(data, isBin));
154
+ },
155
+ close(code = 1000, reason = '') {
156
+ if (closed) return;
157
+ if (!tcpSocket.destroyed) {
158
+ const reasonBuf = Buffer.from(reason, 'utf8');
159
+ const payload = Buffer.alloc(2 + reasonBuf.length);
160
+ payload.writeUInt16BE(code, 0);
161
+ reasonBuf.copy(payload, 2);
162
+ tcpSocket.write(encodeControlFrame(0x8, payload));
163
+ tcpSocket.end();
164
+ }
165
+ cleanup();
166
+ },
167
+ async *[Symbol.asyncIterator]() {
168
+ while (!closed || messageQueue.length > 0) {
169
+ if (messageQueue.length > 0) {
170
+ yield messageQueue.shift();
171
+ } else {
172
+ await new Promise((resolve) => {
173
+ waitResolver = resolve;
174
+ });
175
+ }
176
+ }
177
+ }
178
+ };
179
+
180
+ if (sessionId) broker.bindSession(sessionId, sessionSocket);
181
+
182
+ let heartbeatTimer = null;
183
+ if (heartbeatMs > 0) {
184
+ heartbeatTimer = setInterval(() => {
185
+ if (!alive) {
186
+ sessionSocket.close(1001, 'Heartbeat timeout');
187
+ return;
188
+ }
189
+ alive = false;
190
+ if (sessionSocket.isOpen) {
191
+ tcpSocket.write(encodeControlFrame(0x9));
192
+ }
193
+ }, heartbeatMs);
194
+ }
195
+
196
+ const deliverMessage = (opcode, payload) => {
197
+ if (opcode === 0x2 || binaryMode) {
198
+ messageQueue.push(new Uint8Array(payload));
199
+ } else {
200
+ const text = payload.toString('utf8');
201
+ try {
202
+ messageQueue.push(JSON.parse(text));
203
+ } catch {
204
+ messageQueue.push(text);
205
+ }
206
+ }
207
+ wakeReader();
208
+ };
209
+
210
+ const processFrames = () => {
211
+ while (recvBuffer.length >= 2 && !closed) {
212
+ const b0 = recvBuffer[0];
213
+ const b1 = recvBuffer[1];
214
+ const fin = (b0 & 0x80) !== 0;
215
+ const opcode = b0 & 0x0f;
216
+ const masked = (b1 & 0x80) !== 0;
217
+ let payloadLen = b1 & 0x7f;
218
+ let offset = 2;
219
+
220
+ if (payloadLen === 126) {
221
+ if (recvBuffer.length < 4) return;
222
+ payloadLen = recvBuffer.readUInt16BE(2);
223
+ offset = 4;
224
+ } else if (payloadLen === 127) {
225
+ if (recvBuffer.length < 10) return;
226
+ payloadLen = Number(recvBuffer.readBigUInt64BE(2));
227
+ offset = 10;
228
+ }
229
+
230
+ if (payloadLen > maxPayload) {
231
+ sessionSocket.close(1009, 'Payload exceeds maxPayload');
232
+ return;
233
+ }
234
+
235
+ const maskLen = masked ? 4 : 0;
236
+ const totalFrameLen = offset + maskLen + payloadLen;
237
+ if (recvBuffer.length < totalFrameLen) return;
238
+
239
+ let payload = recvBuffer.subarray(offset + maskLen, totalFrameLen);
240
+ if (masked) {
241
+ const maskKey = recvBuffer.subarray(offset, offset + 4);
242
+ const unmasked = Buffer.allocUnsafe(payloadLen);
243
+ for (let i = 0; i < payloadLen; i++) {
244
+ unmasked[i] = payload[i] ^ maskKey[i & 3];
245
+ }
246
+ payload = unmasked;
247
+ }
248
+
249
+ recvBuffer = recvBuffer.subarray(totalFrameLen);
250
+ alive = true;
251
+
252
+ if (opcode === 0x8) {
253
+ sessionSocket.close(1000, 'Client closed');
254
+ return;
255
+ }
256
+ if (opcode === 0x9) {
257
+ if (sessionSocket.isOpen) tcpSocket.write(encodeControlFrame(0xa, payload));
258
+ continue;
259
+ }
260
+ if (opcode === 0xa) {
261
+ continue;
262
+ }
263
+
264
+ if (opcode === 0x0) {
265
+ fragmentedChunks.push(payload);
266
+ if (fin) {
267
+ const full = Buffer.concat(fragmentedChunks);
268
+ fragmentedChunks = [];
269
+ deliverMessage(fragmentedOpcode, full);
270
+ }
271
+ } else if (!fin) {
272
+ fragmentedOpcode = opcode;
273
+ fragmentedChunks = [payload];
274
+ } else {
275
+ deliverMessage(opcode, payload);
276
+ }
277
+ }
278
+ };
279
+
280
+ tcpSocket.on('data', (chunk) => {
281
+ recvBuffer = Buffer.concat([recvBuffer, chunk]);
282
+ processFrames();
283
+ });
284
+
285
+ tcpSocket.on('close', cleanup);
286
+ tcpSocket.on('error', cleanup);
287
+
288
+ processFrames();
289
+ return sessionSocket;
290
+ }
291
+
292
+ export function performWsHandshake(req, tcpSocket, extraHeaders = new Headers()) {
293
+ const key = req.headers['sec-websocket-key'];
294
+ if (!key) return false;
295
+
296
+ const accept = crypto.createHash('sha1').update(key + WS_GUID).digest('base64');
297
+ const lines = [
298
+ 'HTTP/1.1 101 Switching Protocols',
299
+ 'Upgrade: websocket',
300
+ 'Connection: Upgrade',
301
+ `Sec-WebSocket-Accept: ${accept}`
302
+ ];
303
+
304
+ extraHeaders.forEach((val, name) => {
305
+ lines.push(`${name}: ${val}`);
306
+ });
307
+
308
+ lines.push('', '');
309
+ tcpSocket.write(lines.join('\r\n'));
310
+ return true;
311
+ }
package/src/wire.js ADDED
@@ -0,0 +1,254 @@
1
+ import crypto from 'node:crypto';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import {
4
+ FileStreamResponse,
5
+ HtmlResponse,
6
+ escapeHtml,
7
+ parseMultipartStream
8
+ } from './utils.js';
9
+
10
+ export const wireStorage = new AsyncLocalStorage();
11
+
12
+ const reactionRegistry = new WeakMap();
13
+
14
+ export function reactTo(targetFn, observerFn) {
15
+ if (typeof targetFn !== 'function' || typeof observerFn !== 'function') {
16
+ throw new TypeError('reactTo(targetFn, observerFn) requires two functions');
17
+ }
18
+ const list = reactionRegistry.get(targetFn) || [];
19
+ list.push(observerFn);
20
+ reactionRegistry.set(targetFn, list);
21
+ return () => {
22
+ const idx = list.indexOf(observerFn);
23
+ if (idx !== -1) list.splice(idx, 1);
24
+ };
25
+ }
26
+
27
+ export function getReactions(targetFn) {
28
+ return reactionRegistry.get(targetFn) || [];
29
+ }
30
+
31
+ export class ServinAbortError extends Error {
32
+ constructor(status = 400, message = 'Request aborted') {
33
+ super(message);
34
+ this.name = 'ServinAbortError';
35
+ this.status = status;
36
+ }
37
+ }
38
+
39
+ function renderInterpolated(val) {
40
+ if (val instanceof HtmlResponse) return val.html;
41
+ if (Array.isArray(val)) return val.map(renderInterpolated).join('');
42
+ return escapeHtml(val);
43
+ }
44
+
45
+ export function createRequestContext({
46
+ req,
47
+ method,
48
+ url,
49
+ signal,
50
+ sessionManager,
51
+ broker,
52
+ deferTracker
53
+ }) {
54
+ const outgoingHeaders = new Headers();
55
+ const undoStack = [];
56
+ const debugLogs = [];
57
+ const timings = [];
58
+ const startTime = performance.now();
59
+ const requestId = crypto.randomUUID().slice(0, 8);
60
+
61
+ const headersProxy = new Proxy(outgoingHeaders, {
62
+ get(target, prop) {
63
+ if (prop === 'get') {
64
+ return (key) => target.get(key) ?? req?.headers?.get(key) ?? null;
65
+ }
66
+ if (prop === 'has') {
67
+ return (key) => target.has(key) || Boolean(req?.headers?.has(key));
68
+ }
69
+ const val = target[prop];
70
+ return typeof val === 'function' ? val.bind(target) : val;
71
+ }
72
+ });
73
+
74
+ const ctx = {
75
+ requestId,
76
+ startTime,
77
+ req,
78
+ method: (method || req?.method || 'GET').toUpperCase(),
79
+ url: url || (req ? new URL(req.url) : new URL('http://localhost/')),
80
+ signal: signal || req?.signal || new AbortController().signal,
81
+ headersProxy,
82
+ outgoingHeaders,
83
+ statusCode: 200,
84
+ statusExplicit: false,
85
+ headersSent: false,
86
+ undoStack,
87
+ debugLogs,
88
+ timings,
89
+ costPoints: 1,
90
+ costExplicit: false,
91
+ isSimulated: req?.headers?.get('x-simulate')?.toLowerCase() === 'true',
92
+ sessionHandle: null,
93
+ sessionManager,
94
+ broker,
95
+ deferTracker
96
+ };
97
+
98
+ if (sessionManager) {
99
+ ctx.sessionHandle = sessionManager.createHandle(ctx);
100
+ }
101
+
102
+ return ctx;
103
+ }
104
+
105
+ export async function runUndoStack(ctx) {
106
+ while (ctx.undoStack.length > 0) {
107
+ const fn = ctx.undoStack.pop();
108
+ try {
109
+ await fn();
110
+ } catch (err) {
111
+ console.error(`[servin][${ctx.requestId}] Undo compensation failed:`, err);
112
+ }
113
+ }
114
+ }
115
+
116
+ export function flushDebugLogs(ctx, err) {
117
+ if (ctx.debugLogs.length === 0) return;
118
+ console.error(`\n[servin][${ctx.requestId}] Error-Triggered Debug Trace (${ctx.method} ${ctx.url.pathname}):`);
119
+ for (const entry of ctx.debugLogs) {
120
+ console.error(` +${entry.offsetMs.toFixed(1)}ms [${entry.level}] ${entry.msg}`, entry.meta ?? '');
121
+ }
122
+ if (err) console.error(' Failure:', err.stack || err.message || err);
123
+ }
124
+
125
+ function getCtx() {
126
+ const ctx = wireStorage.getStore();
127
+ if (!ctx) {
128
+ throw new Error('`wire` accessed outside of an active servin execution context');
129
+ }
130
+ return ctx;
131
+ }
132
+
133
+ export const wire = {
134
+ get req() {
135
+ return getCtx().req;
136
+ },
137
+ get method() {
138
+ return getCtx().method;
139
+ },
140
+ get url() {
141
+ return getCtx().url;
142
+ },
143
+ get headers() {
144
+ return getCtx().headersProxy;
145
+ },
146
+ get stream() {
147
+ return getCtx().req?.body ?? null;
148
+ },
149
+ get signal() {
150
+ return getCtx().signal;
151
+ },
152
+ status(code) {
153
+ const ctx = getCtx();
154
+ ctx.statusCode = code;
155
+ ctx.statusExplicit = true;
156
+ },
157
+ abort(status = 400, message = 'Aborted') {
158
+ throw new ServinAbortError(status, message);
159
+ },
160
+ undo(fn) {
161
+ if (typeof fn === 'function') {
162
+ getCtx().undoStack.push(fn);
163
+ }
164
+ },
165
+ defer(fn) {
166
+ const ctx = getCtx();
167
+ if (typeof fn !== 'function') return;
168
+ const task = Promise.resolve().then(() => fn()).catch((err) => {
169
+ console.error(`[servin][${ctx.requestId}] Deferred task error:`, err);
170
+ });
171
+ if (ctx.deferTracker) ctx.deferTracker.track(task);
172
+ },
173
+ html(strings, ...values) {
174
+ if (Array.isArray(strings) && Array.isArray(strings.raw)) {
175
+ let out = strings[0];
176
+ for (let i = 0; i < values.length; i++) {
177
+ out += renderInterpolated(values[i]) + strings[i + 1];
178
+ }
179
+ return new HtmlResponse(out);
180
+ }
181
+ return new HtmlResponse(strings);
182
+ },
183
+ file(filePath) {
184
+ return new FileStreamResponse(filePath);
185
+ },
186
+ multipart(opts = {}) {
187
+ const ctx = getCtx();
188
+ const ct = ctx.req?.headers?.get('content-type') || '';
189
+ if (!ctx.req?.body) {
190
+ throw new ServinAbortError(400, 'Missing request body stream for multipart');
191
+ }
192
+ return parseMultipartStream(ctx.req.body, ct, opts);
193
+ },
194
+ get session() {
195
+ const ctx = getCtx();
196
+ if (!ctx.sessionHandle) {
197
+ throw new Error('Session is not configured in serve({ session: { secret } })');
198
+ }
199
+ return ctx.sessionHandle.proxy;
200
+ },
201
+ set session(val) {
202
+ const ctx = getCtx();
203
+ if (!ctx.sessionHandle) {
204
+ throw new Error('Session is not configured in serve({ session: { secret } })');
205
+ }
206
+ if (val === null) {
207
+ ctx.sessionHandle.destroy();
208
+ } else if (typeof val === 'object') {
209
+ ctx.sessionHandle.replace(val);
210
+ }
211
+ },
212
+ get sessions() {
213
+ const ctx = getCtx();
214
+ if (!ctx.sessionManager) {
215
+ throw new Error('Session is not configured in serve({ session: { secret } })');
216
+ }
217
+ return {
218
+ list: (userId) => ctx.sessionManager.listByUser(userId),
219
+ revokeOthers: (userId) => ctx.sessionManager.revokeOthers(userId, ctx.sessionHandle?.sid)
220
+ };
221
+ },
222
+ publish(topic, data) {
223
+ const ctx = getCtx();
224
+ ctx.broker?.publish(topic, data);
225
+ },
226
+ cost(points) {
227
+ const ctx = getCtx();
228
+ ctx.costPoints = Number(points) || 0;
229
+ ctx.costExplicit = true;
230
+ },
231
+ log: {
232
+ debug(msg, meta) {
233
+ const ctx = wireStorage.getStore();
234
+ if (!ctx) return;
235
+ ctx.debugLogs.push({
236
+ level: 'DEBUG',
237
+ offsetMs: performance.now() - ctx.startTime,
238
+ msg,
239
+ meta
240
+ });
241
+ },
242
+ info(msg, meta) {
243
+ const ctx = wireStorage.getStore();
244
+ console.log(`[servin][${ctx?.requestId ?? 'sys'}] ${msg}`, meta ?? '');
245
+ }
246
+ },
247
+ mark(label) {
248
+ const ctx = getCtx();
249
+ const t0 = performance.now();
250
+ return () => {
251
+ ctx.timings.push({ label, dur: performance.now() - t0 });
252
+ };
253
+ }
254
+ };
package/test.js ADDED
@@ -0,0 +1,45 @@
1
+ import fsp from 'node:fs/promises';
2
+ import { wireStorage, createRequestContext, runUndoStack } from './src/wire.js';
3
+
4
+ export async function replay(targetFn, snapshotPath) {
5
+ if (typeof targetFn !== 'function') {
6
+ throw new TypeError('replay(targetFn, snapshotPath) requires a target function');
7
+ }
8
+
9
+ const raw = await fsp.readFile(snapshotPath, 'utf8');
10
+ const snapshot = JSON.parse(raw);
11
+
12
+ const url = new URL(snapshot.url || 'http://localhost/');
13
+ const req = new Request(url, {
14
+ method: snapshot.method || 'GET',
15
+ headers: new Headers(snapshot.headers || {})
16
+ });
17
+
18
+ const ctx = createRequestContext({
19
+ req,
20
+ method: snapshot.method || 'GET',
21
+ url
22
+ });
23
+
24
+ let extractedArgs;
25
+ if (snapshot.params && typeof snapshot.params === 'object') {
26
+ extractedArgs = Object.values(snapshot.params);
27
+ } else {
28
+ const pathnameParts = url.pathname.replace(/^\/+|\/+$/g, '').split('/');
29
+ const dotParts = (snapshot.dotPath || '').split('.');
30
+ extractedArgs = [];
31
+ for (let i = 0; i < dotParts.length; i++) {
32
+ if (dotParts[i].startsWith('$') && pathnameParts[i] !== undefined) {
33
+ extractedArgs.push(decodeURIComponent(pathnameParts[i]));
34
+ }
35
+ }
36
+ }
37
+
38
+ return wireStorage.run(ctx, async () => {
39
+ try {
40
+ return await targetFn(...extractedArgs);
41
+ } finally {
42
+ await runUndoStack(ctx);
43
+ }
44
+ });
45
+ }