-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathadapter.ts
More file actions
411 lines (377 loc) · 16.6 KB
/
Copy pathadapter.ts
File metadata and controls
411 lines (377 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
// Export IHttpServer from core
export * from '@objectstack/core';
import {
IHttpServer,
RouteHandler,
Middleware
} from '@objectstack/core';
import { currentPerfTiming } from '@objectstack/observability';
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { matchesRoutePattern } from './route-pattern';
/**
* Request headers allowed on preflight, by default.
*
* **The** default — three Hono-based CORS sites apply it (this package's
* `hono-plugin.ts` and the `@objectstack/hono` adapter, which depends on this
* package), and they used to each carry their own copy under "keep in sync"
* comments. The copies happened to agree; the TSDoc on {@link
* HonoCorsOptions.allowHeaders} did not — it had been three headers behind for
* long enough to predate multi-tenant routing, so the one description a caller
* actually reads was the one that drifted (#3786).
*
* `X-Tenant-ID` / `X-Environment-Id` route a request to its environment.
* `If-Match` carries the OCC token on record PATCHes (objectui's inline edit,
* REST `update` with `ifMatch`) — without it in the preflight allow-list every
* cross-origin save fails in the browser with "Failed to fetch" (objectui#2572).
*/
export const DEFAULT_CORS_ALLOW_HEADERS: readonly string[] = Object.freeze([
'Content-Type',
'Authorization',
'X-Requested-With',
'X-Tenant-ID',
'X-Environment-Id',
'If-Match',
]);
/**
* Response headers exposed to cross-origin JS, by default. Same three sites,
* same reason as {@link DEFAULT_CORS_ALLOW_HEADERS}.
*
* `set-auth-token` lets better-auth's `bearer()` plugin hand rotated session
* tokens to cross-origin clients (see plugin-auth). `x-objectstack-dropped-fields`
* (#3455) exposes the single-write drop warning (#3431); the body `droppedFields`
* channel remains the primary, cross-origin-safe surface.
*/
export const DEFAULT_CORS_EXPOSE_HEADERS: readonly string[] = Object.freeze([
'set-auth-token',
'x-objectstack-dropped-fields',
]);
export interface HonoCorsOptions {
enabled?: boolean;
origins?: string | string[];
methods?: string[];
/**
* Request headers allowed on preflight (`Access-Control-Allow-Headers`).
*
* Defaults to {@link DEFAULT_CORS_ALLOW_HEADERS} — deliberately a link and
* not a restatement. Supplying this REPLACES the default rather than
* extending it, so spread the constant if you only mean to add:
* `allowHeaders: [...DEFAULT_CORS_ALLOW_HEADERS, 'X-My-Header']`.
*/
allowHeaders?: string[];
/**
* Response headers exposed to JS (`Access-Control-Expose-Headers`).
*
* Defaults to {@link DEFAULT_CORS_EXPOSE_HEADERS}. Unlike `allowHeaders`,
* user-supplied values are MERGED with the default — those are always
* exposed unless CORS is disabled entirely.
*/
exposeHeaders?: string[];
credentials?: boolean;
maxAge?: number;
}
/**
* Hono Implementation of IHttpServer
*/
export class HonoHttpServer implements IHttpServer {
private app: Hono;
private server: any;
private listeningPort: number | undefined;
/**
* Every `(method, pattern)` pair registered through this server, kept so
* the `notFound` handler can answer "the path exists but the method is
* wrong" with a `405` + `Allow` instead of an opaque `404`. Populated by
* the verb methods below; static/SPA catch-alls registered straight on the
* raw Hono app are intentionally NOT tracked, so they never produce a 405.
*/
private registeredRoutes: Array<{ method: string; pattern: string }> = [];
constructor(
private port: number = 3000,
private staticRoot?: string,
/**
* Max time (ms) to let in-flight requests drain on `close()` before
* force-closing the remainder. Kept well under the kernel's 60s
* `shutdownTimeout` so a slow request can't hang the whole shutdown.
*/
private drainTimeoutMs: number = 10_000,
) {
this.app = new Hono();
}
// internal helper to convert standard handler to Hono handler
private wrap(handler: RouteHandler) {
return async (c: any) => {
let body: any = {};
// Ambient per-request timing collector — present only when the
// Server-Timing / perf-tuning middleware established one for this
// request. All marks below are no-ops otherwise (zero overhead).
const _perf = currentPerfTiming();
const _endParse = _perf?.start('parse', 'Body parse');
const contentType = c.req.header('content-type') ?? '';
const isOctetStream = contentType.includes('application/octet-stream');
// Try to parse JSON body first if content-type is JSON
if (contentType.includes('application/json')) {
try {
body = await c.req.json();
} catch(e) {
// If JSON parsing fails, try parseBody
try {
body = await c.req.parseBody();
} catch(e2) {}
}
} else if (!isOctetStream) {
// For non-JSON / non-binary content types, use parseBody
// (Skipping for octet-stream so the raw stream stays consumable
// via `req.rawBody()` for binary uploads.)
try {
body = await c.req.parseBody();
} catch(e) {}
}
_endParse?.();
const rawHeaders = c.req.header();
// Fetch API `Request` objects don't expose the `Host` header
// (it's a forbidden header — derived from the URL by the
// transport). Hostname-based routing in REST/dispatcher
// depends on it, so we backfill from `c.req.url`.
if (!rawHeaders.host) {
try {
const u = new URL(c.req.url);
if (u.host) rawHeaders.host = u.host;
} catch { /* non-URL request, leave headers as-is */ }
}
const req = {
params: c.req.param(),
query: c.req.query(),
body,
headers: rawHeaders,
method: c.req.method,
path: c.req.path,
rawBody: async () => {
const ab = await c.req.arrayBuffer();
return Buffer.from(ab);
},
};
let capturedResponse: any;
let streamController: ReadableStreamDefaultController | null = null;
let streamEncoder: TextEncoder | null = null;
let streamHeaders: Record<string, string> = {};
let isStreaming = false;
let streamClosed = false;
// The unused stream is always created (see below) and may be closed
// from two places — `res.end()` and the post-handler cleanup — so
// guard against the double-close that crashes the event loop with
// `ERR_INVALID_STATE: Controller is already closed`.
const closeStream = () => {
if (streamController && !streamClosed) {
streamClosed = true;
try { streamController.close(); } catch { /* already closed */ }
}
};
const res = {
json: (data: any) => {
// `serialize` Server-Timing span — JSON-encoding the body is
// the one adapter-owned cost between "handler done" and
// "bytes on the wire". No-op when perf-tuning is off.
const endSerialize = _perf?.start('serialize', 'Response serialize');
capturedResponse = c.json(data);
endSerialize?.();
},
send: (data: string | Uint8Array | ArrayBuffer | Buffer) => {
if (data instanceof Uint8Array || data instanceof ArrayBuffer || (typeof Buffer !== 'undefined' && Buffer.isBuffer?.(data))) {
const body = data instanceof ArrayBuffer ? data : (data as Uint8Array).buffer.slice((data as Uint8Array).byteOffset, (data as Uint8Array).byteOffset + (data as Uint8Array).byteLength);
capturedResponse = c.body(body as ArrayBuffer);
} else {
capturedResponse = c.html(data as string);
}
},
status: (code: number) => { c.status(code); return res; },
header: (name: string, value: string) => {
c.header(name, value);
streamHeaders[name] = value;
return res;
},
write: (chunk: string | Uint8Array) => {
isStreaming = true;
if (streamController && streamEncoder) {
const data = typeof chunk === 'string' ? streamEncoder.encode(chunk) : chunk;
streamController.enqueue(data);
}
},
end: () => {
// Body-less response (e.g. 204 No Content) honoring any
// status already set via `res.status()`. A null body avoids
// the undici "Invalid response status code 204" thrown when
// an empty *string* body is paired with a null-body status.
if (!isStreaming && capturedResponse === undefined) {
capturedResponse = c.body(null);
}
closeStream();
},
};
// Create a streaming response wrapper — if handler calls res.write(),
// we return a ReadableStream; otherwise fall back to capturedResponse.
const streamPromise = new Promise<Response | null>((resolve) => {
const stream = new ReadableStream({
start(controller) {
streamController = controller;
streamEncoder = new TextEncoder();
},
});
// Run the handler; once it's done, check if streaming was used
const _endHandler = _perf?.start('handler', 'Route handler');
const result = handler(req as any, res as any);
const done = result instanceof Promise ? result : Promise.resolve(result);
done.then(() => {
_endHandler?.();
if (isStreaming) {
resolve(new Response(stream, {
status: 200,
headers: streamHeaders,
}));
} else {
// Not streaming — close the unused stream and return null
closeStream();
resolve(null);
}
}).catch((err) => {
_endHandler?.();
closeStream();
resolve(null);
});
});
const streamResponse = await streamPromise;
return streamResponse ?? capturedResponse ?? c.json({ error: 'No response from handler' }, 500);
};
}
get(path: string, handler: RouteHandler) {
this.registeredRoutes.push({ method: 'GET', pattern: path });
this.app.get(path, this.wrap(handler));
}
post(path: string, handler: RouteHandler) {
this.registeredRoutes.push({ method: 'POST', pattern: path });
this.app.post(path, this.wrap(handler));
}
put(path: string, handler: RouteHandler) {
this.registeredRoutes.push({ method: 'PUT', pattern: path });
this.app.put(path, this.wrap(handler));
}
delete(path: string, handler: RouteHandler) {
this.registeredRoutes.push({ method: 'DELETE', pattern: path });
this.app.delete(path, this.wrap(handler));
}
patch(path: string, handler: RouteHandler) {
this.registeredRoutes.push({ method: 'PATCH', pattern: path });
this.app.patch(path, this.wrap(handler));
}
/**
* The HTTP methods registered for a concrete request `path`, ignoring the
* request's own method. Empty when no registered route matches the path at
* all (a genuine 404). Used by the `notFound` handler to build a `405`
* response with an accurate `Allow` header. `HEAD` is implied by `GET`
* (Hono answers HEAD from GET routes automatically).
*/
allowedMethodsForPath(path: string): string[] {
const methods = new Set<string>();
for (const route of this.registeredRoutes) {
if (matchesRoutePattern(route.pattern, path)) methods.add(route.method);
}
if (methods.has('GET')) methods.add('HEAD');
return Array.from(methods).sort();
}
use(pathOrHandler: string | Middleware, handler?: Middleware) {
if (typeof pathOrHandler === 'string' && handler) {
this.app.use(pathOrHandler, async (c, next) => {
let nextCalled = false;
const wrappedNext = () => { nextCalled = true; return next(); };
await handler({} as any, {} as any, wrappedNext);
if (!nextCalled) await next();
});
} else if (typeof pathOrHandler === 'function') {
this.app.use('*', async (c, next) => {
let nextCalled = false;
const wrappedNext = () => { nextCalled = true; return next(); };
await pathOrHandler({} as any, {} as any, wrappedNext);
if (!nextCalled) await next();
});
}
}
/**
* Mount a sub-application or router
*/
mount(path: string, subApp: Hono) {
this.app.route(path, subApp);
}
async listen(port: number) {
if (this.staticRoot) {
this.app.get('/*', serveStatic({ root: this.staticRoot }));
}
const targetPort = port || this.port;
const maxRetries = 20;
for (let attempt = 0; attempt < maxRetries; attempt++) {
const tryPort = targetPort + attempt;
try {
await this.tryListen(tryPort);
return;
} catch (err: any) {
if (err.code === 'EADDRINUSE' && attempt < maxRetries - 1) {
if (this.server && typeof this.server.close === 'function') {
this.server.close();
}
continue;
}
throw err;
}
}
}
private tryListen(port: number): Promise<void> {
return new Promise<void>((resolve, reject) => {
const server = serve({
fetch: this.app.fetch,
port
}, (info) => {
this.listeningPort = info.port;
resolve();
});
this.server = server;
server.on('error', (err: any) => {
reject(err);
});
});
}
getPort() {
return this.listeningPort || this.port;
}
// Expose raw app for scenarios where standard interface is not enough
getRawApp() {
return this.app;
}
async close() {
if (!this.server) return;
const server = this.server;
// Graceful drain (P1-3): stop accepting new connections and let in-flight
// requests finish rather than force-killing them mid-response.
// `closeIdleConnections()` releases idle keep-alive sockets so the process
// can exit promptly; active requests keep running until they complete or
// the drain window elapses.
await new Promise<void>((resolve) => {
let settled = false;
const finish = () => { if (!settled) { settled = true; resolve(); } };
// Fires once every connection has ended (drained).
server.close(() => finish());
if (typeof server.closeIdleConnections === 'function') {
server.closeIdleConnections();
}
// Safety net: if requests outlast the drain window, force-close the
// remainder so shutdown can't hang past the kernel's shutdownTimeout.
const timer = setTimeout(() => {
if (typeof server.closeAllConnections === 'function') {
server.closeAllConnections();
}
finish();
}, this.drainTimeoutMs);
if (typeof timer.unref === 'function') timer.unref();
});
this.server = undefined;
}
}