@tessellation/http 0.0.0-stage → 2.0.0
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/LICENSE +21 -0
- package/README.md +412 -2
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/lib/auth/api-key.d.ts +17 -0
- package/dist/lib/auth/api-key.d.ts.map +1 -0
- package/dist/lib/auth/api-key.js +48 -0
- package/dist/lib/auth/jwt.d.ts +33 -0
- package/dist/lib/auth/jwt.d.ts.map +1 -0
- package/dist/lib/auth/jwt.js +227 -0
- package/dist/lib/auth/provide-auth.d.ts +30 -0
- package/dist/lib/auth/provide-auth.d.ts.map +1 -0
- package/dist/lib/auth/provide-auth.js +69 -0
- package/dist/lib/auth/strategy.d.ts +47 -0
- package/dist/lib/auth/strategy.d.ts.map +1 -0
- package/dist/lib/auth/strategy.js +18 -0
- package/dist/lib/compile.d.ts +46 -0
- package/dist/lib/compile.d.ts.map +1 -0
- package/dist/lib/compile.js +126 -0
- package/dist/lib/compression.d.ts +23 -0
- package/dist/lib/compression.d.ts.map +1 -0
- package/dist/lib/compression.js +86 -0
- package/dist/lib/config.d.ts +173 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +93 -0
- package/dist/lib/cors.d.ts +41 -0
- package/dist/lib/cors.d.ts.map +1 -0
- package/dist/lib/cors.js +101 -0
- package/dist/lib/docs.d.ts +15 -0
- package/dist/lib/docs.d.ts.map +1 -0
- package/dist/lib/docs.js +93 -0
- package/dist/lib/engine.d.ts +83 -0
- package/dist/lib/engine.d.ts.map +1 -0
- package/dist/lib/engine.js +562 -0
- package/dist/lib/errors.d.ts +31 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +55 -0
- package/dist/lib/etag.d.ts +5 -0
- package/dist/lib/etag.d.ts.map +1 -0
- package/dist/lib/etag.js +30 -0
- package/dist/lib/headers.d.ts +3 -0
- package/dist/lib/headers.d.ts.map +1 -0
- package/dist/lib/headers.js +14 -0
- package/dist/lib/json-schema.d.ts +11 -0
- package/dist/lib/json-schema.d.ts.map +1 -0
- package/dist/lib/json-schema.js +23 -0
- package/dist/lib/openapi.d.ts +18 -0
- package/dist/lib/openapi.d.ts.map +1 -0
- package/dist/lib/openapi.js +218 -0
- package/dist/lib/rate-limit.d.ts +52 -0
- package/dist/lib/rate-limit.d.ts.map +1 -0
- package/dist/lib/rate-limit.js +87 -0
- package/dist/lib/reply.d.ts +27 -0
- package/dist/lib/reply.d.ts.map +1 -0
- package/dist/lib/reply.js +52 -0
- package/dist/lib/request.d.ts +55 -0
- package/dist/lib/request.d.ts.map +1 -0
- package/dist/lib/request.js +36 -0
- package/dist/lib/router.d.ts +35 -0
- package/dist/lib/router.d.ts.map +1 -0
- package/dist/lib/router.js +173 -0
- package/dist/lib/routes.d.ts +196 -0
- package/dist/lib/routes.d.ts.map +1 -0
- package/dist/lib/routes.js +98 -0
- package/dist/lib/security-headers.d.ts +19 -0
- package/dist/lib/security-headers.d.ts.map +1 -0
- package/dist/lib/security-headers.js +22 -0
- package/dist/lib/serializer.d.ts +35 -0
- package/dist/lib/serializer.d.ts.map +1 -0
- package/dist/lib/serializer.js +147 -0
- package/dist/lib/server.d.ts +86 -0
- package/dist/lib/server.d.ts.map +1 -0
- package/dist/lib/server.js +255 -0
- package/dist/lib/testing.d.ts +21 -0
- package/dist/lib/testing.d.ts.map +1 -0
- package/dist/lib/testing.js +62 -0
- package/dist/lib/transports/node.d.ts +4 -0
- package/dist/lib/transports/node.d.ts.map +1 -0
- package/dist/lib/transports/node.js +249 -0
- package/dist/lib/transports/transport.d.ts +32 -0
- package/dist/lib/transports/transport.d.ts.map +1 -0
- package/dist/lib/transports/transport.js +1 -0
- package/dist/lib/transports/uws.d.ts +8 -0
- package/dist/lib/transports/uws.d.ts.map +1 -0
- package/dist/lib/transports/uws.js +246 -0
- package/dist/lib/websocket.d.ts +71 -0
- package/dist/lib/websocket.d.ts.map +1 -0
- package/dist/lib/websocket.js +125 -0
- package/package.json +67 -3
- package/src/index.ts +103 -0
- package/src/lib/auth/api-key.ts +73 -0
- package/src/lib/auth/jwt.ts +339 -0
- package/src/lib/auth/provide-auth.ts +99 -0
- package/src/lib/auth/strategy.ts +66 -0
- package/src/lib/compile.ts +207 -0
- package/src/lib/compression.ts +121 -0
- package/src/lib/config.ts +107 -0
- package/src/lib/cors.ts +146 -0
- package/src/lib/docs.ts +115 -0
- package/src/lib/engine.ts +770 -0
- package/src/lib/errors.ts +84 -0
- package/src/lib/etag.ts +37 -0
- package/src/lib/headers.ts +18 -0
- package/src/lib/json-schema.ts +36 -0
- package/src/lib/openapi.ts +299 -0
- package/src/lib/rate-limit.ts +142 -0
- package/src/lib/reply.ts +70 -0
- package/src/lib/request.ts +83 -0
- package/src/lib/router.ts +217 -0
- package/src/lib/routes.ts +414 -0
- package/src/lib/security-headers.ts +38 -0
- package/src/lib/serializer.ts +203 -0
- package/src/lib/server.ts +352 -0
- package/src/lib/testing.ts +88 -0
- package/src/lib/transports/node.ts +315 -0
- package/src/lib/transports/transport.ts +39 -0
- package/src/lib/transports/uws.ts +310 -0
- package/src/lib/websocket.ts +184 -0
|
@@ -0,0 +1,770 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
Injector,
|
|
5
|
+
type Logger,
|
|
6
|
+
parseTraceparent,
|
|
7
|
+
provide,
|
|
8
|
+
runInInjectionContext,
|
|
9
|
+
type Span,
|
|
10
|
+
type StandardSchemaIssue,
|
|
11
|
+
type StandardSchemaV1,
|
|
12
|
+
type Tracer,
|
|
13
|
+
withLogFields,
|
|
14
|
+
} from '@tessellation/core';
|
|
15
|
+
|
|
16
|
+
import type { CompiledRoute } from './compile.js';
|
|
17
|
+
import type { Compressor } from './compression.js';
|
|
18
|
+
import type { CorsPolicy } from './cors.js';
|
|
19
|
+
import { badRequest, errorReply, HttpError, problem } from './errors.js';
|
|
20
|
+
import { etagMatches, weakEtag } from './etag.js';
|
|
21
|
+
import { Reply } from './reply.js';
|
|
22
|
+
import { HttpRequest, type ResponseSink } from './request.js';
|
|
23
|
+
import { UpgradeReply, WebSocketSession } from './websocket.js';
|
|
24
|
+
import { Router } from './router.js';
|
|
25
|
+
import type { RawQuery } from './routes.js';
|
|
26
|
+
|
|
27
|
+
type Schema = StandardSchemaV1;
|
|
28
|
+
|
|
29
|
+
export interface EngineOptions {
|
|
30
|
+
/** The application injector; request injectors are its children. */
|
|
31
|
+
injector: Injector;
|
|
32
|
+
logger: Logger;
|
|
33
|
+
accessLog: boolean;
|
|
34
|
+
/** Applied to every response, and answers preflight requests. */
|
|
35
|
+
cors?: CorsPolicy | undefined;
|
|
36
|
+
/** Header carrying request ids, lower-case; undefined disables request ids. */
|
|
37
|
+
requestIdHeader?: string | undefined;
|
|
38
|
+
/** Milliseconds before a request is answered with 503; 0 disables. */
|
|
39
|
+
requestTimeout?: number;
|
|
40
|
+
/** Proxies in front of the server, for `HttpRequest.clientIp`. */
|
|
41
|
+
trustProxy?: number;
|
|
42
|
+
/** Added to every response that does not set them. */
|
|
43
|
+
securityHeaders?: readonly (readonly [string, string])[];
|
|
44
|
+
/** Compresses responses the client accepts compressed. */
|
|
45
|
+
compressor?: Compressor | undefined;
|
|
46
|
+
/** Generate weak ETags for successful GET responses. */
|
|
47
|
+
etag?: boolean;
|
|
48
|
+
/** Creates a server span per request; pass only when tracing is on. */
|
|
49
|
+
tracer?: Tracer | undefined;
|
|
50
|
+
/**
|
|
51
|
+
* Called after every response with the route pattern (or `(unmatched)` /
|
|
52
|
+
* `(preflight)`), the status and the duration in seconds. Used for metrics.
|
|
53
|
+
*/
|
|
54
|
+
observe?:
|
|
55
|
+
| ((method: string, route: string, status: number, seconds: number) => void)
|
|
56
|
+
| undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const KNOWN_METHODS = new Set([
|
|
60
|
+
'GET',
|
|
61
|
+
'HEAD',
|
|
62
|
+
'POST',
|
|
63
|
+
'PUT',
|
|
64
|
+
'PATCH',
|
|
65
|
+
'DELETE',
|
|
66
|
+
'OPTIONS',
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
const REQUEST_ID = /^[\w.:-]{1,128}$/;
|
|
70
|
+
|
|
71
|
+
/** Classes (not object literals with getters) keep one hidden class for V8. */
|
|
72
|
+
class HandlerContext {
|
|
73
|
+
constructor(
|
|
74
|
+
readonly params: unknown,
|
|
75
|
+
readonly query: unknown,
|
|
76
|
+
readonly body: unknown,
|
|
77
|
+
readonly request: HttpRequest,
|
|
78
|
+
private readonly scope: RequestScope,
|
|
79
|
+
) {}
|
|
80
|
+
|
|
81
|
+
get signal(): AbortSignal {
|
|
82
|
+
return this.scope.signal;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
class MiddlewareContextImpl {
|
|
87
|
+
readonly route: { readonly method: string; readonly path: string };
|
|
88
|
+
|
|
89
|
+
constructor(
|
|
90
|
+
readonly request: HttpRequest,
|
|
91
|
+
route: CompiledRoute,
|
|
92
|
+
private readonly scope: RequestScope,
|
|
93
|
+
) {
|
|
94
|
+
this.route = { method: route.method, path: route.path };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
get signal(): AbortSignal {
|
|
98
|
+
return this.scope.signal;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Per-request state: the abort signal handlers see. The controller is only
|
|
104
|
+
* created when something reads the signal, so requests that do not use it
|
|
105
|
+
* pay nothing.
|
|
106
|
+
*/
|
|
107
|
+
class RequestScope {
|
|
108
|
+
private controller: AbortController | undefined;
|
|
109
|
+
private reason: unknown;
|
|
110
|
+
|
|
111
|
+
constructor(private readonly sink: ResponseSink) {}
|
|
112
|
+
|
|
113
|
+
get signal(): AbortSignal {
|
|
114
|
+
if (this.controller === undefined) {
|
|
115
|
+
this.controller = new AbortController();
|
|
116
|
+
if (this.reason === undefined) {
|
|
117
|
+
this.sink.onAbort(() =>
|
|
118
|
+
this.abort(
|
|
119
|
+
new DOMException('The client disconnected.', 'AbortError'),
|
|
120
|
+
),
|
|
121
|
+
);
|
|
122
|
+
} else {
|
|
123
|
+
this.controller.abort(this.reason);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return this.controller.signal;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
abort(reason: unknown): void {
|
|
130
|
+
if (this.reason === undefined) {
|
|
131
|
+
this.reason = reason;
|
|
132
|
+
this.controller?.abort(reason);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
interface ValidationIssue {
|
|
138
|
+
in: 'params' | 'query' | 'body';
|
|
139
|
+
path: string;
|
|
140
|
+
message: string;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const decoder = new TextDecoder();
|
|
144
|
+
const JSON_TYPE = /^application\/(?:[\w.+-]*\+)?json\b/i;
|
|
145
|
+
|
|
146
|
+
/** Handles requests for a set of compiled routes, independent of transport. */
|
|
147
|
+
export class HttpEngine {
|
|
148
|
+
private readonly router = new Router<CompiledRoute>();
|
|
149
|
+
private readonly injector: Injector;
|
|
150
|
+
private readonly logger: Logger;
|
|
151
|
+
private readonly accessLog: boolean;
|
|
152
|
+
private readonly cors: CorsPolicy | undefined;
|
|
153
|
+
private readonly requestIdHeader: string | undefined;
|
|
154
|
+
private readonly requestTimeout: number;
|
|
155
|
+
private readonly trustProxy: number;
|
|
156
|
+
private readonly securityHeaders: readonly (readonly [string, string])[];
|
|
157
|
+
private readonly compressor: Compressor | undefined;
|
|
158
|
+
private readonly observe: EngineOptions['observe'];
|
|
159
|
+
private readonly etag: boolean;
|
|
160
|
+
private readonly tracer: Tracer | undefined;
|
|
161
|
+
private inFlight = 0;
|
|
162
|
+
private readonly webSockets = new Set<WebSocketSession>();
|
|
163
|
+
private readonly sessionLifecycle = {
|
|
164
|
+
opened: (session: WebSocketSession) => this.webSockets.add(session),
|
|
165
|
+
closed: (session: WebSocketSession) => this.webSockets.delete(session),
|
|
166
|
+
};
|
|
167
|
+
private idle: PromiseWithResolvers<void> | undefined;
|
|
168
|
+
/** Set while shutting down: responses ask clients to close the connection. */
|
|
169
|
+
closing = false;
|
|
170
|
+
|
|
171
|
+
constructor(
|
|
172
|
+
readonly routes: readonly CompiledRoute[],
|
|
173
|
+
options: EngineOptions,
|
|
174
|
+
) {
|
|
175
|
+
this.injector = options.injector;
|
|
176
|
+
this.logger = options.logger;
|
|
177
|
+
this.accessLog = options.accessLog;
|
|
178
|
+
this.cors = options.cors?.enabled === true ? options.cors : undefined;
|
|
179
|
+
this.requestIdHeader = options.requestIdHeader;
|
|
180
|
+
this.requestTimeout = options.requestTimeout ?? 0;
|
|
181
|
+
this.trustProxy = options.trustProxy ?? 0;
|
|
182
|
+
this.securityHeaders = options.securityHeaders ?? [];
|
|
183
|
+
this.compressor = options.compressor;
|
|
184
|
+
this.observe = options.observe;
|
|
185
|
+
this.etag = options.etag ?? false;
|
|
186
|
+
this.tracer = options.tracer;
|
|
187
|
+
|
|
188
|
+
for (const route of routes) {
|
|
189
|
+
this.router.add(route.method, route.path, route);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Number of requests being handled. */
|
|
194
|
+
get pending(): number {
|
|
195
|
+
return this.inFlight;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The transport entry point. Never throws. */
|
|
199
|
+
readonly handle = (request: HttpRequest, sink: ResponseSink): void => {
|
|
200
|
+
this.inFlight += 1;
|
|
201
|
+
request.trustedProxies = this.trustProxy;
|
|
202
|
+
|
|
203
|
+
let work: Promise<void>;
|
|
204
|
+
if (this.requestIdHeader === undefined) {
|
|
205
|
+
work = this.traced(request, sink);
|
|
206
|
+
} else {
|
|
207
|
+
const incoming = request.headers[this.requestIdHeader];
|
|
208
|
+
const id =
|
|
209
|
+
incoming !== undefined && REQUEST_ID.test(incoming)
|
|
210
|
+
? incoming
|
|
211
|
+
: randomUUID();
|
|
212
|
+
request.id = id;
|
|
213
|
+
// Everything logged while handling the request carries its id.
|
|
214
|
+
work = withLogFields({ requestId: id }, () => this.traced(request, sink));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
work
|
|
218
|
+
.catch((error: unknown) => {
|
|
219
|
+
this.logger.error('Failed to send response', { err: error });
|
|
220
|
+
})
|
|
221
|
+
.finally(() => {
|
|
222
|
+
this.inFlight -= 1;
|
|
223
|
+
if (this.inFlight === 0) {
|
|
224
|
+
this.idle?.resolve();
|
|
225
|
+
this.idle = undefined;
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
/** Open WebSocket connections. */
|
|
231
|
+
get webSocketCount(): number {
|
|
232
|
+
return this.webSockets.size;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Closes every open WebSocket, such as when shutting down. */
|
|
236
|
+
closeWebSockets(code: number, reason: string): void {
|
|
237
|
+
for (const session of [...this.webSockets]) {
|
|
238
|
+
session.close(code, reason);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Resolves once no request is being handled. */
|
|
243
|
+
drain(): Promise<void> {
|
|
244
|
+
if (this.inFlight === 0) {
|
|
245
|
+
return Promise.resolve();
|
|
246
|
+
}
|
|
247
|
+
this.idle ??= Promise.withResolvers();
|
|
248
|
+
return this.idle.promise;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Handles the request in a server span when tracing is on. */
|
|
252
|
+
private traced(request: HttpRequest, sink: ResponseSink): Promise<void> {
|
|
253
|
+
const { tracer } = this;
|
|
254
|
+
if (tracer === undefined) {
|
|
255
|
+
return this.process(request, sink, undefined);
|
|
256
|
+
}
|
|
257
|
+
return tracer.span(
|
|
258
|
+
request.method,
|
|
259
|
+
(span) => this.process(request, sink, span),
|
|
260
|
+
{
|
|
261
|
+
kind: 'server',
|
|
262
|
+
parent: parseTraceparent(request.headers['traceparent']),
|
|
263
|
+
attributes: {
|
|
264
|
+
'http.request.method': request.method,
|
|
265
|
+
'url.path': request.path,
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
private async process(
|
|
272
|
+
request: HttpRequest,
|
|
273
|
+
sink: ResponseSink,
|
|
274
|
+
span: Span | undefined,
|
|
275
|
+
): Promise<void> {
|
|
276
|
+
const timed = this.accessLog || this.observe !== undefined;
|
|
277
|
+
const started = timed ? performance.now() : 0;
|
|
278
|
+
const { cors } = this;
|
|
279
|
+
let route: CompiledRoute | undefined;
|
|
280
|
+
let requestInjector: Injector | undefined;
|
|
281
|
+
let response: Reply;
|
|
282
|
+
|
|
283
|
+
if (cors !== undefined && cors.isPreflight(request)) {
|
|
284
|
+
// No route has a NUL method, so this lists the methods the path supports.
|
|
285
|
+
const methods = this.router.find('\0', request.path);
|
|
286
|
+
response =
|
|
287
|
+
methods.kind === 'method-not-allowed'
|
|
288
|
+
? cors.preflight(request, methods.allowed)
|
|
289
|
+
: problem(404);
|
|
290
|
+
const sending = this.send(response, undefined, request, sink);
|
|
291
|
+
if (sending !== undefined) {
|
|
292
|
+
await sending;
|
|
293
|
+
}
|
|
294
|
+
this.observe?.(
|
|
295
|
+
methodLabel(request.method),
|
|
296
|
+
'(preflight)',
|
|
297
|
+
response.status,
|
|
298
|
+
(performance.now() - started) / 1000,
|
|
299
|
+
);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
let pending: Promise<Reply> | undefined;
|
|
304
|
+
const match = this.router.find(request.method, request.path);
|
|
305
|
+
if (match.kind === 'found') {
|
|
306
|
+
route = match.value;
|
|
307
|
+
if (span !== undefined) {
|
|
308
|
+
span.name = `${request.method} ${route.path}`;
|
|
309
|
+
span.setAttribute('http.route', route.path);
|
|
310
|
+
}
|
|
311
|
+
try {
|
|
312
|
+
if (
|
|
313
|
+
route.websocket !== undefined &&
|
|
314
|
+
request.headers['upgrade']?.toLowerCase() !== 'websocket'
|
|
315
|
+
) {
|
|
316
|
+
throw new HttpError(
|
|
317
|
+
426,
|
|
318
|
+
'This endpoint only accepts WebSocket connections.',
|
|
319
|
+
{
|
|
320
|
+
headers: { upgrade: 'websocket' },
|
|
321
|
+
},
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
if (route.providers.length > 0) {
|
|
325
|
+
requestInjector = Injector.create({
|
|
326
|
+
name: 'request',
|
|
327
|
+
parent: this.injector,
|
|
328
|
+
providers: [
|
|
329
|
+
provide(HttpRequest, { useValue: request }),
|
|
330
|
+
...route.providers,
|
|
331
|
+
],
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
const scope = new RequestScope(sink);
|
|
335
|
+
pending = this.run(
|
|
336
|
+
route,
|
|
337
|
+
request,
|
|
338
|
+
match.params,
|
|
339
|
+
requestInjector ?? this.injector,
|
|
340
|
+
scope,
|
|
341
|
+
);
|
|
342
|
+
response =
|
|
343
|
+
this.requestTimeout > 0
|
|
344
|
+
? await this.withTimeout(pending, scope, request, route)
|
|
345
|
+
: await pending;
|
|
346
|
+
} catch (error) {
|
|
347
|
+
response = this.errorResponse(error, request, route);
|
|
348
|
+
}
|
|
349
|
+
} else if (match.kind === 'method-not-allowed') {
|
|
350
|
+
response = problem(
|
|
351
|
+
405,
|
|
352
|
+
undefined,
|
|
353
|
+
{},
|
|
354
|
+
{ allow: match.allowed.join(', ') },
|
|
355
|
+
);
|
|
356
|
+
} else {
|
|
357
|
+
response = problem(404);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
let upgraded = false;
|
|
361
|
+
if (response instanceof UpgradeReply) {
|
|
362
|
+
if (route?.websocket !== undefined && sink.upgrade !== undefined) {
|
|
363
|
+
sink.upgrade(
|
|
364
|
+
new WebSocketSession(
|
|
365
|
+
route.path,
|
|
366
|
+
route.websocket,
|
|
367
|
+
response,
|
|
368
|
+
this.injector,
|
|
369
|
+
this.logger,
|
|
370
|
+
this.sessionLifecycle,
|
|
371
|
+
),
|
|
372
|
+
);
|
|
373
|
+
upgraded = true;
|
|
374
|
+
} else {
|
|
375
|
+
response = problem(
|
|
376
|
+
426,
|
|
377
|
+
'This endpoint only accepts WebSocket connections.',
|
|
378
|
+
{},
|
|
379
|
+
{
|
|
380
|
+
upgrade: 'websocket',
|
|
381
|
+
},
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
if (span !== undefined) {
|
|
387
|
+
span.setAttribute('http.response.status_code', response.status);
|
|
388
|
+
if (response.status >= 500) {
|
|
389
|
+
span.status = 'error';
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
cors?.apply(request, response);
|
|
394
|
+
if (request.id !== undefined && this.requestIdHeader !== undefined) {
|
|
395
|
+
response.header(this.requestIdHeader, request.id);
|
|
396
|
+
}
|
|
397
|
+
if (!upgraded) {
|
|
398
|
+
const sent = this.send(response, route, request, sink);
|
|
399
|
+
if (sent !== undefined) {
|
|
400
|
+
await sent;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (requestInjector !== undefined) {
|
|
405
|
+
const injector = requestInjector;
|
|
406
|
+
// After a timeout the handler may still be running: clean up once it ends.
|
|
407
|
+
void (pending ?? Promise.resolve())
|
|
408
|
+
.catch(() => undefined)
|
|
409
|
+
.then(() => injector.destroy())
|
|
410
|
+
.catch((error: unknown) => {
|
|
411
|
+
this.logger.error('Failed to clean up request providers', {
|
|
412
|
+
err: error,
|
|
413
|
+
});
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
if (this.observe !== undefined) {
|
|
418
|
+
this.observe(
|
|
419
|
+
methodLabel(request.method),
|
|
420
|
+
route?.path ?? '(unmatched)',
|
|
421
|
+
response.status,
|
|
422
|
+
(performance.now() - started) / 1000,
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
if (this.accessLog) {
|
|
427
|
+
this.logger.info('Request', {
|
|
428
|
+
method: request.method,
|
|
429
|
+
path: request.path,
|
|
430
|
+
route: route?.path,
|
|
431
|
+
status: response.status,
|
|
432
|
+
durationMs: Math.round((performance.now() - started) * 100) / 100,
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Answers 503 and aborts the request's signal if it takes too long. */
|
|
438
|
+
private async withTimeout(
|
|
439
|
+
work: Promise<Reply>,
|
|
440
|
+
scope: RequestScope,
|
|
441
|
+
request: HttpRequest,
|
|
442
|
+
route: CompiledRoute,
|
|
443
|
+
): Promise<Reply> {
|
|
444
|
+
let timer: NodeJS.Timeout | undefined;
|
|
445
|
+
const timeout = new Promise<Reply>((resolve) => {
|
|
446
|
+
timer = setTimeout(() => {
|
|
447
|
+
scope.abort(new DOMException('The request timed out.', 'TimeoutError'));
|
|
448
|
+
this.logger.warn('Request timed out', {
|
|
449
|
+
method: request.method,
|
|
450
|
+
route: route.path,
|
|
451
|
+
timeoutMs: this.requestTimeout,
|
|
452
|
+
});
|
|
453
|
+
resolve(problem(503, 'The request timed out.'));
|
|
454
|
+
}, this.requestTimeout);
|
|
455
|
+
});
|
|
456
|
+
try {
|
|
457
|
+
return await Promise.race([work, timeout]);
|
|
458
|
+
} finally {
|
|
459
|
+
clearTimeout(timer);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Runs middleware around the endpoint. Errors from the endpoint are already replies. */
|
|
464
|
+
private run(
|
|
465
|
+
route: CompiledRoute,
|
|
466
|
+
request: HttpRequest,
|
|
467
|
+
rawParams: string[],
|
|
468
|
+
injector: Injector,
|
|
469
|
+
scope: RequestScope,
|
|
470
|
+
): Promise<Reply> {
|
|
471
|
+
const { middleware } = route;
|
|
472
|
+
if (middleware.length === 0) {
|
|
473
|
+
return this.endpoint(route, request, rawParams, injector, scope);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const context = new MiddlewareContextImpl(request, route, scope);
|
|
477
|
+
const dispatch = async (index: number): Promise<Reply> => {
|
|
478
|
+
const current = middleware[index];
|
|
479
|
+
if (current === undefined) {
|
|
480
|
+
return this.endpoint(route, request, rawParams, injector, scope);
|
|
481
|
+
}
|
|
482
|
+
return runInInjectionContext(injector, () =>
|
|
483
|
+
current(context, () => dispatch(index + 1)),
|
|
484
|
+
);
|
|
485
|
+
};
|
|
486
|
+
return dispatch(0);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
private async endpoint(
|
|
490
|
+
route: CompiledRoute,
|
|
491
|
+
request: HttpRequest,
|
|
492
|
+
rawParams: string[],
|
|
493
|
+
injector: Injector,
|
|
494
|
+
scope: RequestScope,
|
|
495
|
+
): Promise<Reply> {
|
|
496
|
+
try {
|
|
497
|
+
const issues: ValidationIssue[] = [];
|
|
498
|
+
const params = await this.params(route, rawParams, issues);
|
|
499
|
+
const rawQuery = parseQuery(request.query);
|
|
500
|
+
const query = route.query
|
|
501
|
+
? await validate(route.query, rawQuery, 'query', issues)
|
|
502
|
+
: rawQuery;
|
|
503
|
+
const body = route.body
|
|
504
|
+
? await this.body(route.body, request, issues)
|
|
505
|
+
: undefined;
|
|
506
|
+
|
|
507
|
+
if (issues.length > 0) {
|
|
508
|
+
throw badRequest('The request is invalid.', { details: { issues } });
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const result = runInInjectionContext(injector, () =>
|
|
512
|
+
route.handler(
|
|
513
|
+
new HandlerContext(params, query, body, request, scope) as never,
|
|
514
|
+
),
|
|
515
|
+
);
|
|
516
|
+
const value: unknown = result instanceof Promise ? await result : result;
|
|
517
|
+
|
|
518
|
+
if (value instanceof Reply) {
|
|
519
|
+
return value;
|
|
520
|
+
}
|
|
521
|
+
return value === undefined
|
|
522
|
+
? new Reply(204, undefined)
|
|
523
|
+
: new Reply(200, value);
|
|
524
|
+
} catch (error) {
|
|
525
|
+
return this.errorResponse(error, request, route);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
private async params(
|
|
530
|
+
route: CompiledRoute,
|
|
531
|
+
values: string[],
|
|
532
|
+
issues: ValidationIssue[],
|
|
533
|
+
): Promise<Record<string, unknown>> {
|
|
534
|
+
const params: Record<string, unknown> = {};
|
|
535
|
+
const names = route.paramNames;
|
|
536
|
+
|
|
537
|
+
for (let index = 0; index < names.length; index += 1) {
|
|
538
|
+
params[names[index] as string] = decodeComponent(values[index] as string);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
for (const level of route.paramLevels) {
|
|
542
|
+
const input: Record<string, unknown> = {};
|
|
543
|
+
for (const name of level.names) {
|
|
544
|
+
input[name] = params[name];
|
|
545
|
+
}
|
|
546
|
+
const output = await validate(level.schema, input, 'params', issues);
|
|
547
|
+
if (output !== undefined) {
|
|
548
|
+
Object.assign(params, output);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
return params;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
private async body(
|
|
556
|
+
schema: Schema,
|
|
557
|
+
request: HttpRequest,
|
|
558
|
+
issues: ValidationIssue[],
|
|
559
|
+
): Promise<unknown> {
|
|
560
|
+
const bytes = await request.body();
|
|
561
|
+
let value: unknown;
|
|
562
|
+
|
|
563
|
+
if (bytes.byteLength > 0) {
|
|
564
|
+
const type = request.headers['content-type'] ?? '';
|
|
565
|
+
if (!JSON_TYPE.test(type)) {
|
|
566
|
+
throw new HttpError(
|
|
567
|
+
415,
|
|
568
|
+
'The request body must be JSON (content-type: application/json).',
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
try {
|
|
572
|
+
value = JSON.parse(decoder.decode(bytes));
|
|
573
|
+
} catch {
|
|
574
|
+
throw badRequest('The request body is not valid JSON.');
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
return validate(schema, value, 'body', issues);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
private errorResponse(
|
|
582
|
+
error: unknown,
|
|
583
|
+
request: HttpRequest,
|
|
584
|
+
route: CompiledRoute | undefined,
|
|
585
|
+
): Reply {
|
|
586
|
+
if (error instanceof HttpError) {
|
|
587
|
+
if (error.status >= 500) {
|
|
588
|
+
this.logger.error('Request failed', {
|
|
589
|
+
method: request.method,
|
|
590
|
+
route: route?.path,
|
|
591
|
+
err: error,
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
return errorReply(error);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
this.logger.error('Unhandled error', {
|
|
598
|
+
method: request.method,
|
|
599
|
+
route: route?.path,
|
|
600
|
+
err: error,
|
|
601
|
+
});
|
|
602
|
+
return problem(500);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** Sends a reply. Returns a promise only when compression makes it asynchronous. */
|
|
606
|
+
private send(
|
|
607
|
+
response: Reply,
|
|
608
|
+
route: CompiledRoute | undefined,
|
|
609
|
+
request: HttpRequest,
|
|
610
|
+
sink: ResponseSink,
|
|
611
|
+
): Promise<void> | undefined {
|
|
612
|
+
if (sink.aborted) {
|
|
613
|
+
return undefined;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const { headers, body, status } = response;
|
|
617
|
+
let payload: string | Uint8Array | undefined;
|
|
618
|
+
|
|
619
|
+
if (body === undefined || (body === null && status === 204)) {
|
|
620
|
+
payload = undefined;
|
|
621
|
+
} else if (typeof body === 'string') {
|
|
622
|
+
payload = body;
|
|
623
|
+
headers['content-type'] ??= 'text/plain; charset=utf-8';
|
|
624
|
+
} else if (body instanceof Uint8Array) {
|
|
625
|
+
payload = body;
|
|
626
|
+
headers['content-type'] ??= 'application/octet-stream';
|
|
627
|
+
} else {
|
|
628
|
+
const serialize = route?.serializers.get(status) ?? JSON.stringify;
|
|
629
|
+
payload = serialize(body);
|
|
630
|
+
headers['content-type'] ??= 'application/json';
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
for (const [name, value] of this.securityHeaders) {
|
|
634
|
+
headers[name] ??= value;
|
|
635
|
+
}
|
|
636
|
+
if (this.closing) {
|
|
637
|
+
headers['connection'] = 'close';
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const head = request.method === 'HEAD';
|
|
641
|
+
|
|
642
|
+
// Conditional GET: honour ETags set by handlers, or generate them.
|
|
643
|
+
if (
|
|
644
|
+
status === 200 &&
|
|
645
|
+
payload !== undefined &&
|
|
646
|
+
(head || request.method === 'GET')
|
|
647
|
+
) {
|
|
648
|
+
let tag = headers['etag'];
|
|
649
|
+
if (tag === undefined && this.etag) {
|
|
650
|
+
tag = weakEtag(payload);
|
|
651
|
+
headers['etag'] = tag;
|
|
652
|
+
}
|
|
653
|
+
if (
|
|
654
|
+
tag !== undefined &&
|
|
655
|
+
etagMatches(request.headers['if-none-match'], tag)
|
|
656
|
+
) {
|
|
657
|
+
delete headers['content-type'];
|
|
658
|
+
sink.send(304, headers, undefined, head);
|
|
659
|
+
return undefined;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (
|
|
663
|
+
this.compressor !== undefined &&
|
|
664
|
+
payload !== undefined &&
|
|
665
|
+
!head &&
|
|
666
|
+
status !== 204 &&
|
|
667
|
+
status !== 304
|
|
668
|
+
) {
|
|
669
|
+
return this.compressor
|
|
670
|
+
.apply(request.headers['accept-encoding'], headers, payload)
|
|
671
|
+
.then((compressed) => {
|
|
672
|
+
if (!sink.aborted) {
|
|
673
|
+
sink.send(status, headers, compressed, head);
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
sink.send(status, headers, payload, head);
|
|
679
|
+
return undefined;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
async function validate(
|
|
684
|
+
schema: Schema,
|
|
685
|
+
value: unknown,
|
|
686
|
+
location: ValidationIssue['in'],
|
|
687
|
+
issues: ValidationIssue[],
|
|
688
|
+
): Promise<unknown> {
|
|
689
|
+
let result = schema['~standard'].validate(value);
|
|
690
|
+
if (result instanceof Promise) {
|
|
691
|
+
result = await result;
|
|
692
|
+
}
|
|
693
|
+
if (result.issues === undefined) {
|
|
694
|
+
return result.value;
|
|
695
|
+
}
|
|
696
|
+
for (const issue of result.issues) {
|
|
697
|
+
issues.push({
|
|
698
|
+
in: location,
|
|
699
|
+
path: issuePath(issue),
|
|
700
|
+
message: issue.message,
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
return undefined;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function issuePath(issue: StandardSchemaIssue): string {
|
|
707
|
+
return (issue.path ?? [])
|
|
708
|
+
.map((segment) =>
|
|
709
|
+
String(typeof segment === 'object' ? segment.key : segment),
|
|
710
|
+
)
|
|
711
|
+
.join('.');
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function decodeComponent(value: string): string {
|
|
715
|
+
if (!value.includes('%')) {
|
|
716
|
+
return value;
|
|
717
|
+
}
|
|
718
|
+
try {
|
|
719
|
+
return decodeURIComponent(value);
|
|
720
|
+
} catch {
|
|
721
|
+
throw badRequest('The request path is not correctly URL-encoded.');
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** Parses a query string; repeated keys become arrays. */
|
|
726
|
+
export function parseQuery(query: string): RawQuery {
|
|
727
|
+
const result: RawQuery = Object.create(null) as RawQuery;
|
|
728
|
+
if (query === '') {
|
|
729
|
+
return result;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
for (const pair of query.split('&')) {
|
|
733
|
+
if (pair === '') {
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
const equals = pair.indexOf('=');
|
|
737
|
+
const key = decodeQueryComponent(
|
|
738
|
+
equals === -1 ? pair : pair.slice(0, equals),
|
|
739
|
+
);
|
|
740
|
+
const value =
|
|
741
|
+
equals === -1 ? '' : decodeQueryComponent(pair.slice(equals + 1));
|
|
742
|
+
const existing = result[key];
|
|
743
|
+
if (existing === undefined) {
|
|
744
|
+
result[key] = value;
|
|
745
|
+
} else if (Array.isArray(existing)) {
|
|
746
|
+
existing.push(value);
|
|
747
|
+
} else {
|
|
748
|
+
result[key] = [existing, value];
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
return result;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function decodeQueryComponent(value: string): string {
|
|
756
|
+
const spaced = value.includes('+') ? value.replaceAll('+', ' ') : value;
|
|
757
|
+
if (!spaced.includes('%')) {
|
|
758
|
+
return spaced;
|
|
759
|
+
}
|
|
760
|
+
try {
|
|
761
|
+
return decodeURIComponent(spaced);
|
|
762
|
+
} catch {
|
|
763
|
+
throw badRequest('The query string is not correctly URL-encoded.');
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Bounded method values for metric labels. */
|
|
768
|
+
function methodLabel(method: string): string {
|
|
769
|
+
return KNOWN_METHODS.has(method) ? method : 'OTHER';
|
|
770
|
+
}
|