@decohere/http-fastify 0.0.0-stage → 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/README.md +74 -2
- package/package.json +44 -4
- package/src/fastify.provider.ts +490 -0
- package/src/index.ts +1 -0
- package/tests/compression.integration.spec.ts +627 -0
- package/tests/helpers/boot-module.ts +7 -0
- package/tests/static.integration.spec.ts +935 -0
package/README.md
CHANGED
|
@@ -1,3 +1,75 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @decohere/http-fastify
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The [Fastify](https://fastify.dev) provider for [`@decohere/http`](../http/README.md): `FastifyProvider`, the web server that serves an app's controllers. `@decohere/http` holds the controllers, routing, auth, OpenAPI, health and problem details; this package is where Fastify and its plugins are. Why the split: [architecture §2](../../docs/architecture/README.md#2-vendors-stay-at-the-composition-edge).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @decohere/http @decohere/http-fastify
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Pass the provider to `http(...)` at the app's composition root:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Builder } from "@decohere/core/hosting";
|
|
13
|
+
import { ServiceContainerBuilder } from "@decohere/crucible";
|
|
14
|
+
import { health, http } from "@decohere/http";
|
|
15
|
+
import { FastifyProvider } from "@decohere/http-fastify";
|
|
16
|
+
|
|
17
|
+
await Builder.create(new ServiceContainerBuilder())
|
|
18
|
+
.use(http(FastifyProvider, { controllers: [HelloController] }))
|
|
19
|
+
.use(health())
|
|
20
|
+
.buildAndStart();
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Controllers and services never import this package. Swapping the web server is changing that one line.
|
|
24
|
+
|
|
25
|
+
## What it does with each setting
|
|
26
|
+
|
|
27
|
+
The settings are `@decohere/http`'s `HttpSettings`, documented there. This is how Fastify carries them out.
|
|
28
|
+
|
|
29
|
+
| Setting | Default | Fastify |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| `helmet` | on | [`@fastify/helmet`](https://github.com/fastify/fastify-helmet); an object is passed to it, `false` leaves it out |
|
|
32
|
+
| `rateLimit` | 100 requests a minute | [`@fastify/rate-limit`](https://github.com/fastify/fastify-rate-limit); an object is merged over the default. Static files are exempt, matched on the route Fastify resolved, not on the URL |
|
|
33
|
+
| `cors` | off | [`@fastify/cors`](https://github.com/fastify/fastify-cors) with the options given |
|
|
34
|
+
| `compression` | on | [`@fastify/compress`](https://github.com/fastify/fastify-compress), registered before any route ([below](#compression)) |
|
|
35
|
+
| `statics` | none | [`@fastify/static`](https://github.com/fastify/fastify-static), one encapsulated context per mount, whose not-found handler is the SPA fallback |
|
|
36
|
+
| `bodyLimit` | 1 MiB | Fastify's `bodyLimit` |
|
|
37
|
+
| `openApi` | off | a `GET` route that returns the generated document |
|
|
38
|
+
|
|
39
|
+
A request Fastify answers itself, before any handler, is a problem like the API's (`application/problem+json`): an unknown route (`404`, `detail: "Route GET:/nope not found"`), a body that isn't valid JSON or is too large, the rate limit. Fastify matches a registered route before a static wildcard, so a UI served from `/` never shadows the API.
|
|
40
|
+
|
|
41
|
+
## Compression
|
|
42
|
+
|
|
43
|
+
`@fastify/compress` owns the policy, with `global: true` and the setting's threshold and encodings. Its default list of compressible types is text, JSON, XML, `octet-stream` and anything the MIME database marks compressible; images, video, woff2 fonts, zip and PDF are not compressed again. `compression.providerOptions` takes any other `@fastify/compress` option, merged last:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
compression: {
|
|
47
|
+
providerOptions: { brotliOptions: { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 6 } } },
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
What to know about the plugin's behaviour:
|
|
52
|
+
|
|
53
|
+
- **`types` is for adding types.** It is passed as `customTypes`: it replaces the plugin's default pattern, but anything the MIME database marks compressible is still compressed. Do not match `text/event-stream` unless you want streams buffered.
|
|
54
|
+
- **The threshold does not apply to streams.** Files served by `statics` are streams, so even a small text file is compressed on the fly. Their `Cache-Control`, `ETag` and `304` behave as before.
|
|
55
|
+
- **`application/octet-stream` is compressed by default.** If you serve already-compressed bytes under that type, set the `Content-Type` of the real format or set your own `Content-Encoding`.
|
|
56
|
+
- **Server-sent events are not compressed** by the plugin's default pattern. Keep it that way.
|
|
57
|
+
- **Unread streamed bodies hold up stopping.** A compressed file stays open until the client has read it, so `app.dispose()` waits for a client that fetched a static file and never read the body. In tests, read or cancel the body (or send `Accept-Encoding: identity`).
|
|
58
|
+
- **Already encoded.** A response that sets its own `Content-Encoding` is passed through.
|
|
59
|
+
- **`Vary: Accept-Encoding`** is added when a response is compressed.
|
|
60
|
+
- **`HEAD`** is answered uncompressed: Fastify builds a `HEAD` reply before the plugin runs, so it has the plain `Content-Length` and no `Vary`. It has no body either way.
|
|
61
|
+
- **A `304`** for a file can carry the `Content-Encoding` header of the `200` it stands for. It has no body.
|
|
62
|
+
- **Helmet, CORS and the rate limit** are unaffected, and an error reply (a `401`, a `400` with a large body) is compressed like any other.
|
|
63
|
+
- **Pre-compressed files.** Serving `.br`/`.gz` files built ahead of time is a possible later step; today static files are compressed on the fly.
|
|
64
|
+
|
|
65
|
+
Why this shape: [ADR 0008](../../docs/adr/0008-response-compression-in-http.md).
|
|
66
|
+
|
|
67
|
+
## Streams and stopping
|
|
68
|
+
|
|
69
|
+
- **Server-sent events.** `@decohere/http` frames the events; the provider writes them to the reply with `text/event-stream`, `cache-control: no-cache, no-transform`, `x-accel-buffering: no` and `connection: close`. It aborts the handler's `@Signal()` when the client goes away.
|
|
70
|
+
- **Stopping.** `stop()` (what `app.dispose()` calls) aborts every open stream first, then closes Fastify, which lets in-flight requests finish. Responses sent while stopping carry `connection: close`, so a kept-alive socket doesn't hold the close open.
|
|
71
|
+
- **Addresses.** `app.addresses` lists the IPv4 origins Fastify listens on, such as `http://127.0.0.1:41233`.
|
|
72
|
+
|
|
73
|
+
## Testing
|
|
74
|
+
|
|
75
|
+
`bootModule({ controllers, provider: FastifyProvider })`, from `@decohere/http/testing`, runs controllers as a real app on this provider, on a free loopback port. This package's own suites, `tests/*.integration.spec.ts`, cover what only the wire shows: compression and static files.
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decohere/http-fastify",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1-dev.5",
|
|
4
|
+
"description": "Fastify provider for @decohere/http: the web server, with helmet, CORS, compression, rate limit and static files",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"typescript",
|
|
7
|
+
"http",
|
|
8
|
+
"fastify",
|
|
9
|
+
"rest",
|
|
10
|
+
"api",
|
|
11
|
+
"decohere"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/typesmiths/decohere/tree/main/projects/http-fastify#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/typesmiths/decohere/issues"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/typesmiths/decohere.git",
|
|
20
|
+
"directory": "projects/http-fastify"
|
|
21
|
+
},
|
|
22
|
+
"license": "ISC",
|
|
23
|
+
"author": "Typesmiths",
|
|
24
|
+
"type": "module",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./types/src/index.d.ts",
|
|
28
|
+
"import": "./es6/src/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
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
|
+
"@fastify/compress": "^9.2.1",
|
|
39
|
+
"@fastify/cors": "^11.3.0",
|
|
40
|
+
"@fastify/helmet": "^13.1.0",
|
|
41
|
+
"@fastify/rate-limit": "^11.2.2",
|
|
42
|
+
"@fastify/static": "^10.1.10",
|
|
43
|
+
"fastify": "^5.12.8"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {}
|
|
46
|
+
}
|
|
@@ -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
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { FastifyProvider } from "./fastify.provider.js";
|