@decohere/http-fastify 0.0.1-dev.20261120.336 → 0.0.1-dev.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decohere/http-fastify",
3
- "version": "0.0.1-dev.20261120.336",
3
+ "version": "0.0.1-dev.5",
4
4
  "description": "Fastify provider for @decohere/http: the web server, with helmet, CORS, compression, rate limit and static files",
5
5
  "keywords": [
6
6
  "typescript",
@@ -32,9 +32,9 @@
32
32
  "test": "echo \"Error: no test specified\" && exit 1"
33
33
  },
34
34
  "dependencies": {
35
- "@decohere/crucible": "0.0.1-dev.20261120.336",
36
- "@decohere/http": "0.0.1-dev.20261120.336",
37
- "@decohere/scribe": "0.0.1-dev.20261120.336",
35
+ "@decohere/crucible": "0.0.1-dev.5",
36
+ "@decohere/http": "0.0.1-dev.5",
37
+ "@decohere/scribe": "0.0.1-dev.5",
38
38
  "@fastify/compress": "^9.2.1",
39
39
  "@fastify/cors": "^11.3.0",
40
40
  "@fastify/helmet": "^13.1.0",
@@ -0,0 +1,490 @@
1
+ import type { AddressInfo } from "node:net";
2
+ import { randomUUID } from "node:crypto";
3
+ import { stat } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { Readable } from "node:stream";
6
+ import { inject } from "@decohere/crucible/decorators";
7
+ import { scribe } from "@decohere/scribe";
8
+ import compress from "@fastify/compress";
9
+ import cors from "@fastify/cors";
10
+ import helmet from "@fastify/helmet";
11
+ import rateLimit from "@fastify/rate-limit";
12
+ import fastifyStatic from "@fastify/static";
13
+ import Fastify, {
14
+ type FastifyInstance,
15
+ type FastifyReply,
16
+ type FastifyRequest,
17
+ } from "fastify";
18
+ import {
19
+ type CompressionOptions,
20
+ type CorsOptions,
21
+ DEFAULT_COMPRESSION_ENCODINGS,
22
+ DEFAULT_COMPRESSION_THRESHOLD,
23
+ DEFAULT_HTTP_BODY_LIMIT,
24
+ DEFAULT_HTTP_RATE_LIMIT,
25
+ DEFAULT_SSE_HEARTBEAT_MS,
26
+ DefaultHttpExceptionFilter,
27
+ type ExceptionFilterHost,
28
+ ExceptionFilterHostToken,
29
+ type HelmetOptions,
30
+ type HttpOptions,
31
+ HttpOptionsToken,
32
+ type HttpProvider,
33
+ HttpRequest,
34
+ type MappedRoute,
35
+ PROBLEM_CONTENT_TYPE,
36
+ REQUEST_ID_HEADER,
37
+ type RateLimitOptions,
38
+ type ResolvedStaticMount,
39
+ type RouteRegistry,
40
+ RouteRegistryToken,
41
+ type Router,
42
+ RouterToken,
43
+ SseResponse,
44
+ type StartOptions,
45
+ type StartResponse,
46
+ type StopResponse,
47
+ encodeSse,
48
+ generateOpenApiDocument,
49
+ normalizePrefix,
50
+ problemDetails,
51
+ resolveOpenApiPath,
52
+ resolveRequestId,
53
+ staticFiles,
54
+ } from "@decohere/http";
55
+
56
+ export class FastifyProvider implements HttpProvider {
57
+ public readonly provider: FastifyInstance;
58
+ public readonly router: Router;
59
+ private readonly routeRegistry: RouteRegistry;
60
+ private readonly httpOptions?: HttpOptions;
61
+ private readonly exceptionFilterHost?: ExceptionFilterHost;
62
+ private closing: Promise<void> | undefined;
63
+ private readonly logger = scribe.logger(FastifyProvider.name);
64
+ /** One per live `@Sse()` request, so stopping the app can end the streams. */
65
+ private readonly openStreams = new Set<AbortController>();
66
+
67
+ public constructor(
68
+ @inject(RouteRegistryToken) routeRegistry?: RouteRegistry,
69
+ @inject(RouterToken) router?: Router,
70
+ @inject(HttpOptionsToken) httpOptions?: HttpOptions,
71
+ @inject(ExceptionFilterHostToken) exceptionFilterHost?: ExceptionFilterHost,
72
+ ) {
73
+ this.routeRegistry = routeRegistry;
74
+ this.router = router;
75
+ this.httpOptions = httpOptions;
76
+ this.exceptionFilterHost = exceptionFilterHost;
77
+ this.provider = Fastify({
78
+ logger: false,
79
+ requestIdHeader: REQUEST_ID_HEADER,
80
+ genReqId: () => randomUUID(),
81
+ bodyLimit: httpOptions?.bodyLimit ?? DEFAULT_HTTP_BODY_LIMIT,
82
+ });
83
+ }
84
+
85
+ public async start<T extends StartOptions>(options?: T): Promise<StartResponse> {
86
+ const statics = await this.resolveStatics();
87
+ await this.registerHelmet(this.httpOptions?.helmet);
88
+ await this.registerRateLimit(this.httpOptions?.rateLimit, statics);
89
+ await this.registerCors(this.httpOptions?.cors);
90
+ await this.registerCompression(this.httpOptions?.compression);
91
+ this.registerProblemReplies(statics);
92
+ this.registerOpenApi(this.httpOptions);
93
+ this.registerAllRoutes(this.routeRegistry);
94
+ for (const mount of statics) {
95
+ await this.registerStatic(mount, statics);
96
+ }
97
+ this.closeConnectionsWhileStopping();
98
+ await this.provider.listen(options);
99
+ return {
100
+ addresses: this.addresses,
101
+ };
102
+ }
103
+
104
+ public async stop(): Promise<StopResponse> {
105
+ // App stops HTTP before disposing the container, which calls this again.
106
+ // A stream never finishes on its own, and close() waits for open responses, so end them first.
107
+ for (const stream of this.openStreams) {
108
+ stream.abort(new Error("The app is stopping"));
109
+ }
110
+ this.closing ??= this.provider.close();
111
+ await this.closing;
112
+ return { message: "closed" };
113
+ }
114
+
115
+ public async [Symbol.asyncDispose](): Promise<void> {
116
+ await this.stop();
117
+ }
118
+
119
+ /**
120
+ * Once stopping, tell clients to drop the connection after their response. Otherwise
121
+ * a request that was in flight leaves a kept-alive socket that holds `close()` open
122
+ * until Node's keep-alive timeout (5s).
123
+ */
124
+ private closeConnectionsWhileStopping() {
125
+ this.provider.addHook("onSend", async (_request, reply, payload) => {
126
+ if (this.closing) reply.header("connection", "close");
127
+ return payload;
128
+ });
129
+ }
130
+
131
+ public get addresses() {
132
+ return this.provider
133
+ .addresses()
134
+ .filter((a): a is AddressInfo => typeof a !== "string" && a.family === "IPv4")
135
+ .map((a) => `http://${a.address}:${a.port}`);
136
+ }
137
+
138
+ private async registerHelmet(helmetOptions?: HelmetOptions) {
139
+ if (helmetOptions === false) {
140
+ return;
141
+ }
142
+ await this.provider.register(helmet, helmetOptions ?? {});
143
+ }
144
+
145
+ private async registerRateLimit(
146
+ rateLimitOptions: RateLimitOptions | undefined,
147
+ statics: readonly ResolvedStaticMount[],
148
+ ) {
149
+ if (rateLimitOptions === false) {
150
+ return;
151
+ }
152
+ // Static files are outside the rate limit (ADR 0007). Matched on the route the request
153
+ // resolved to, not on its URL, so only requests the static plugin serves are exempt.
154
+ const staticRoutes = new Set(statics.map((mount) => `${mount.prefix}*`));
155
+ const userAllowList = rateLimitOptions?.allowList;
156
+ await this.provider.register(rateLimit, {
157
+ ...DEFAULT_HTTP_RATE_LIMIT,
158
+ ...rateLimitOptions,
159
+ allowList: (request: FastifyRequest, key: string) => {
160
+ if (staticRoutes.has(request.routeOptions.url ?? "")) return true;
161
+ if (typeof userAllowList === "function") return userAllowList(request, key);
162
+ return Array.isArray(userAllowList) && userAllowList.includes(key);
163
+ },
164
+ });
165
+ }
166
+
167
+ private async resolveStatics(): Promise<ResolvedStaticMount[]> {
168
+ return staticFiles.resolve(this.httpOptions?.statics ?? [], {
169
+ nodeEnv: process.env.NODE_ENV,
170
+ directoryExists: async (directory) =>
171
+ (await stat(directory).catch(() => undefined))?.isDirectory() === true,
172
+ warn: (message) => this.logger.warn(message),
173
+ });
174
+ }
175
+
176
+ /**
177
+ * One encapsulated context per mount: its not-found handler (the SPA fallback) applies to
178
+ * paths under the prefix and nowhere else, so an API 404 is never answered with the UI.
179
+ */
180
+ private async registerStatic(
181
+ mount: ResolvedStaticMount,
182
+ mounts: readonly ResolvedStaticMount[],
183
+ ) {
184
+ const withoutSlash = mount.prefix.slice(0, -1);
185
+ const isRoot = mount.prefix === "/";
186
+ const excluded = staticFiles.excluder(mount.exclude);
187
+ const belongsToApi = this.apiBoundary();
188
+ // Requests that already fell back once: a missing index must be a 404, not a loop.
189
+ const fellBack = new WeakSet<FastifyRequest>();
190
+ await this.provider.register(
191
+ async (scope) => {
192
+ await scope.register(fastifyStatic, {
193
+ root: mount.root,
194
+ prefix: "/",
195
+ index: mount.index,
196
+ dotfiles: "ignore",
197
+ list: false,
198
+ redirect: false,
199
+ etag: true,
200
+ lastModified: true,
201
+ // The header is set in setHeaders, per file.
202
+ cacheControl: false,
203
+ setHeaders: (reply, filePath) => {
204
+ reply.header(
205
+ "cache-control",
206
+ staticFiles.cacheControlFor(mount, path.relative(mount.root, filePath)),
207
+ );
208
+ },
209
+ });
210
+ // Excluded paths are not served at all: not as a file, not as the fallback.
211
+ scope.addHook("onRequest", async (request, reply) => {
212
+ if (excluded(staticFiles.normalizePathname(request.url))) {
213
+ return reply.callNotFound();
214
+ }
215
+ });
216
+ scope.setNotFoundHandler((request, reply) => {
217
+ const [pathname = "", query] = request.url.split("?");
218
+ const readOnly = request.method === "GET" || request.method === "HEAD";
219
+ // `/ui` goes to `/ui/`. A request for it reaches the root mount's handler instead
220
+ // when there is one, so that handler redirects for the other mounts too.
221
+ const redirectTo = mounts.find(
222
+ (other) =>
223
+ other.prefix !== "/" &&
224
+ other.prefix.slice(0, -1) === pathname &&
225
+ (isRoot || other === mount),
226
+ );
227
+ if (readOnly && redirectTo != null) {
228
+ return reply.redirect(
229
+ query == null ? redirectTo.prefix : `${redirectTo.prefix}?${query}`,
230
+ 301,
231
+ );
232
+ }
233
+ const normalized = staticFiles.normalizePathname(request.url);
234
+ if (
235
+ mount.spaFallback &&
236
+ !fellBack.has(request) &&
237
+ !excluded(normalized) &&
238
+ staticFiles.shouldFallBack(
239
+ { method: request.method, pathname: normalized, accept: request.headers.accept },
240
+ belongsToApi,
241
+ )
242
+ ) {
243
+ fellBack.add(request);
244
+ return reply.sendFile(mount.index);
245
+ }
246
+ return this.sendRouteNotFound(request, reply);
247
+ });
248
+ },
249
+ { prefix: withoutSlash },
250
+ );
251
+ }
252
+
253
+ /**
254
+ * Fastify's own replies, for an unknown route or a request it rejects before any handler
255
+ * (a body that isn't valid JSON, too large, the rate limit), are problems like the API's.
256
+ */
257
+ private registerProblemReplies(statics: ResolvedStaticMount[]) {
258
+ // A UI served from the root owns the root's not-found handler, and answers the same 404.
259
+ if (!statics.some((mount) => mount.prefix === "/")) {
260
+ this.provider.setNotFoundHandler((request, reply) =>
261
+ this.sendRouteNotFound(request, reply),
262
+ );
263
+ }
264
+ this.provider.setErrorHandler((error: unknown, _request, reply) => {
265
+ const status = this.getErrorStatus(error);
266
+ const message = error instanceof Error ? error.message : undefined;
267
+ if (status >= 500) {
268
+ this.logger.error(
269
+ message ?? "Request failed",
270
+ error instanceof Error ? error.stack : undefined,
271
+ );
272
+ }
273
+ const problem = problemDetails.create(status, {
274
+ detail: status >= 500 ? undefined : message,
275
+ });
276
+ return reply.status(status).header("content-type", PROBLEM_CONTENT_TYPE).send(problem);
277
+ });
278
+ }
279
+
280
+ private getErrorStatus(error: unknown): number {
281
+ const status = (error as { statusCode?: unknown } | null)?.statusCode;
282
+ return typeof status === "number" && status >= 400 && status < 600 ? status : 500;
283
+ }
284
+
285
+ private sendRouteNotFound(request: FastifyRequest, reply: FastifyReply) {
286
+ const [pathname = ""] = request.url.split("?");
287
+ const problem = problemDetails.create(404, {
288
+ detail: `Route ${request.method}:${pathname} not found`,
289
+ });
290
+ return reply.code(404).header("content-type", PROBLEM_CONTENT_TYPE).send(problem);
291
+ }
292
+
293
+ /** What the static fallback leaves to the API: the global prefix, else the registered routes. ADR 0007. */
294
+ private apiBoundary(): (pathname: string) => boolean {
295
+ return staticFiles.apiBoundary({
296
+ globalPrefix: normalizePrefix(this.httpOptions?.globalPrefix),
297
+ openApiPath:
298
+ this.httpOptions?.openapi == null
299
+ ? undefined
300
+ : resolveOpenApiPath(this.httpOptions.openapi),
301
+ routePaths: [...this.routeRegistry.routes].map((route) => route.path),
302
+ });
303
+ }
304
+
305
+ /**
306
+ * `@fastify/compress` with best-practice defaults; the plugin owns the policy. Registered
307
+ * before any route so every response goes through it, errors and static files included.
308
+ * `providerOptions` is merged last, so a user can override any plugin option.
309
+ */
310
+ private async registerCompression(compressionOptions: CompressionOptions | undefined) {
311
+ if (compressionOptions === false) {
312
+ return;
313
+ }
314
+ await this.provider.register(compress, {
315
+ global: true,
316
+ threshold: compressionOptions?.threshold ?? DEFAULT_COMPRESSION_THRESHOLD,
317
+ encodings: [...(compressionOptions?.encodings ?? DEFAULT_COMPRESSION_ENCODINGS)],
318
+ ...(compressionOptions?.types != null && { customTypes: compressionOptions.types }),
319
+ ...compressionOptions?.providerOptions,
320
+ });
321
+ }
322
+
323
+ private async registerCors(corsOptions?: CorsOptions) {
324
+ if (corsOptions == null) {
325
+ return;
326
+ }
327
+ await this.provider.register(cors, {
328
+ origin: corsOptions.origin,
329
+ methods: corsOptions.methods,
330
+ allowedHeaders: corsOptions.allowedHeaders,
331
+ exposedHeaders: corsOptions.exposedHeaders,
332
+ credentials: corsOptions.credentials,
333
+ maxAge: corsOptions.maxAge,
334
+ });
335
+ }
336
+
337
+ private registerOpenApi(httpOptions?: HttpOptions) {
338
+ const openapi = httpOptions?.openapi;
339
+ if (openapi == null) {
340
+ return;
341
+ }
342
+ const path = resolveOpenApiPath(openapi);
343
+ const document = generateOpenApiDocument(this.routeRegistry, openapi);
344
+ this.provider.get(path, async (_request, reply) => {
345
+ reply.header("content-type", "application/json; charset=utf-8");
346
+ return document;
347
+ });
348
+ }
349
+
350
+ private registerAllRoutes(registry: RouteRegistry) {
351
+ for (const route of registry.routes) {
352
+ const { key, method, path } = route;
353
+ this.provider.route({
354
+ method,
355
+ url: path,
356
+ handler: (request, reply) => this.routeRequest(route, key, request, reply),
357
+ });
358
+ }
359
+ }
360
+
361
+ private async routeRequest(
362
+ route: MappedRoute,
363
+ key: string,
364
+ request: FastifyRequest,
365
+ reply: FastifyReply,
366
+ ) {
367
+ const httpRequest = this.fastifyToRequest(request);
368
+ const disconnect = this.abortOnDisconnect(reply, httpRequest, route.sse != null);
369
+ try {
370
+ const response = await this.router.route(key, httpRequest);
371
+ if (route.httpCode != null) {
372
+ reply.status(route.httpCode);
373
+ }
374
+ if (route.headers != null) {
375
+ for (const [name, value] of Object.entries(route.headers)) {
376
+ reply.header(name, value);
377
+ }
378
+ }
379
+ this.applyResponseHeaders(reply, httpRequest);
380
+ if (response instanceof SseResponse) {
381
+ return this.sendEventStream(route, reply, response, disconnect);
382
+ }
383
+ return response;
384
+ } catch (error) {
385
+ const result = this.exceptionFilterHost
386
+ ? await this.exceptionFilterHost.handle(error, { request: httpRequest })
387
+ : new DefaultHttpExceptionFilter().catch(error, { request: httpRequest });
388
+ if (result.headers) {
389
+ for (const [name, value] of Object.entries(result.headers)) {
390
+ reply.header(name, value);
391
+ }
392
+ }
393
+ this.applyResponseHeaders(reply, httpRequest);
394
+ // Returned so Fastify waits for the async onSend hooks instead of sending an empty reply of its own.
395
+ return reply.status(result.status).send(result.body);
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Gives the handler a signal that aborts when the client goes away before the response
401
+ * finished. Streams are also tracked so that stopping the app can abort them.
402
+ */
403
+ private abortOnDisconnect(
404
+ reply: FastifyReply,
405
+ httpRequest: HttpRequest,
406
+ isStream: boolean,
407
+ ): AbortController {
408
+ const controller = new AbortController();
409
+ httpRequest.signal = controller.signal;
410
+ if (isStream) {
411
+ if (this.closing) controller.abort(new Error("The app is stopping"));
412
+ this.openStreams.add(controller);
413
+ }
414
+ reply.raw.once("close", () => {
415
+ this.openStreams.delete(controller);
416
+ if (!reply.raw.writableFinished) {
417
+ controller.abort(new Error("The client disconnected"));
418
+ }
419
+ });
420
+ return controller;
421
+ }
422
+
423
+ private sendEventStream(
424
+ route: MappedRoute,
425
+ reply: FastifyReply,
426
+ response: SseResponse,
427
+ disconnect: AbortController,
428
+ ) {
429
+ let started = false;
430
+ const release = () => {
431
+ response.release().catch((error: unknown) => {
432
+ this.logger.error("Releasing the request scope of an SSE stream failed", error);
433
+ });
434
+ };
435
+ const frames = encodeSse(response.events, {
436
+ signal: disconnect.signal,
437
+ heartbeatMs: route.sse?.heartbeatMs ?? DEFAULT_SSE_HEARTBEAT_MS,
438
+ onProducerStopped: (stopped) => void stopped.then(release),
439
+ });
440
+ const guarded = (async function* () {
441
+ started = true;
442
+ yield* frames;
443
+ })();
444
+ // Never pulled if the client left first, in which case nothing else would release the scope.
445
+ reply.raw.once("close", () => {
446
+ if (!started) release();
447
+ });
448
+ return (
449
+ reply
450
+ .status(route.httpCode ?? 200)
451
+ .header("content-type", "text/event-stream; charset=utf-8")
452
+ .header("cache-control", "no-cache, no-transform")
453
+ .header("x-accel-buffering", "no")
454
+ // A stream owns its connection; closing it afterwards lets app stop finish at once instead of waiting out keep-alive.
455
+ .header("connection", "close")
456
+ .send(Readable.from(guarded))
457
+ );
458
+ }
459
+
460
+ private applyResponseHeaders(reply: FastifyReply, httpRequest: HttpRequest) {
461
+ reply.header(REQUEST_ID_HEADER, httpRequest.requestId);
462
+ for (const [name, value] of Object.entries(httpRequest.responseHeaders)) {
463
+ reply.header(name, value);
464
+ }
465
+ }
466
+
467
+ private fastifyToRequest(fastifyRequest: FastifyRequest): HttpRequest {
468
+ const method = fastifyRequest.method;
469
+ const url = fastifyRequest.url;
470
+ const params = fastifyRequest.params as Record<string, string>;
471
+ const query = fastifyRequest.query as Record<string, string>;
472
+ const body = fastifyRequest.body ?? {};
473
+ const headers: Record<string, string> = {};
474
+ for (const [key, value] of Object.entries(fastifyRequest.headers)) {
475
+ if (typeof value === "string") {
476
+ headers[key.toLowerCase()] = value;
477
+ }
478
+ }
479
+ const requestId = resolveRequestId(headers, String(fastifyRequest.id ?? ""));
480
+ return new HttpRequest({
481
+ requestId,
482
+ url,
483
+ method,
484
+ params,
485
+ query,
486
+ body,
487
+ headers,
488
+ });
489
+ }
490
+ }