@decohere/http-fastify 0.0.0-stage → 0.0.1-dev.20261120.336
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 +15 -0
- package/README.md +74 -2
- package/es6/src/fastify.provider.js +394 -0
- package/es6/src/index.js +1 -0
- package/package.json +44 -4
- package/types/src/fastify.provider.d.ts +59 -0
- package/types/src/index.d.ts +1 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Typesmiths
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
10
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
11
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
12
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
13
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
14
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
15
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
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.
|
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
}
|
|
7
|
+
function _ts_metadata(k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
}
|
|
10
|
+
function _ts_param(paramIndex, decorator) {
|
|
11
|
+
return function(target, key) {
|
|
12
|
+
decorator(target, key, paramIndex);
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { stat } from "node:fs/promises";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import { Readable } from "node:stream";
|
|
19
|
+
import { inject } from "@decohere/crucible/decorators";
|
|
20
|
+
import { scribe } from "@decohere/scribe";
|
|
21
|
+
import compress from "@fastify/compress";
|
|
22
|
+
import cors from "@fastify/cors";
|
|
23
|
+
import helmet from "@fastify/helmet";
|
|
24
|
+
import rateLimit from "@fastify/rate-limit";
|
|
25
|
+
import fastifyStatic from "@fastify/static";
|
|
26
|
+
import Fastify from "fastify";
|
|
27
|
+
import { DEFAULT_COMPRESSION_ENCODINGS, DEFAULT_COMPRESSION_THRESHOLD, DEFAULT_HTTP_BODY_LIMIT, DEFAULT_HTTP_RATE_LIMIT, DEFAULT_SSE_HEARTBEAT_MS, DefaultHttpExceptionFilter, ExceptionFilterHostToken, HttpOptionsToken, HttpRequest, PROBLEM_CONTENT_TYPE, REQUEST_ID_HEADER, RouteRegistryToken, RouterToken, SseResponse, encodeSse, generateOpenApiDocument, normalizePrefix, problemDetails, resolveOpenApiPath, resolveRequestId, staticFiles } from "@decohere/http";
|
|
28
|
+
export class FastifyProvider {
|
|
29
|
+
provider;
|
|
30
|
+
router;
|
|
31
|
+
routeRegistry;
|
|
32
|
+
httpOptions;
|
|
33
|
+
exceptionFilterHost;
|
|
34
|
+
closing;
|
|
35
|
+
logger = scribe.logger(FastifyProvider.name);
|
|
36
|
+
/** One per live `@Sse()` request, so stopping the app can end the streams. */ openStreams = new Set();
|
|
37
|
+
constructor(routeRegistry, router, httpOptions, exceptionFilterHost){
|
|
38
|
+
this.routeRegistry = routeRegistry;
|
|
39
|
+
this.router = router;
|
|
40
|
+
this.httpOptions = httpOptions;
|
|
41
|
+
this.exceptionFilterHost = exceptionFilterHost;
|
|
42
|
+
this.provider = Fastify({
|
|
43
|
+
logger: false,
|
|
44
|
+
requestIdHeader: REQUEST_ID_HEADER,
|
|
45
|
+
genReqId: ()=>randomUUID(),
|
|
46
|
+
bodyLimit: httpOptions?.bodyLimit ?? DEFAULT_HTTP_BODY_LIMIT
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async start(options) {
|
|
50
|
+
const statics = await this.resolveStatics();
|
|
51
|
+
await this.registerHelmet(this.httpOptions?.helmet);
|
|
52
|
+
await this.registerRateLimit(this.httpOptions?.rateLimit, statics);
|
|
53
|
+
await this.registerCors(this.httpOptions?.cors);
|
|
54
|
+
await this.registerCompression(this.httpOptions?.compression);
|
|
55
|
+
this.registerProblemReplies(statics);
|
|
56
|
+
this.registerOpenApi(this.httpOptions);
|
|
57
|
+
this.registerAllRoutes(this.routeRegistry);
|
|
58
|
+
for (const mount of statics){
|
|
59
|
+
await this.registerStatic(mount, statics);
|
|
60
|
+
}
|
|
61
|
+
this.closeConnectionsWhileStopping();
|
|
62
|
+
await this.provider.listen(options);
|
|
63
|
+
return {
|
|
64
|
+
addresses: this.addresses
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
async stop() {
|
|
68
|
+
// App stops HTTP before disposing the container, which calls this again.
|
|
69
|
+
// A stream never finishes on its own, and close() waits for open responses, so end them first.
|
|
70
|
+
for (const stream of this.openStreams){
|
|
71
|
+
stream.abort(new Error("The app is stopping"));
|
|
72
|
+
}
|
|
73
|
+
this.closing ??= this.provider.close();
|
|
74
|
+
await this.closing;
|
|
75
|
+
return {
|
|
76
|
+
message: "closed"
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
async [Symbol.asyncDispose]() {
|
|
80
|
+
await this.stop();
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Once stopping, tell clients to drop the connection after their response. Otherwise
|
|
84
|
+
* a request that was in flight leaves a kept-alive socket that holds `close()` open
|
|
85
|
+
* until Node's keep-alive timeout (5s).
|
|
86
|
+
*/ closeConnectionsWhileStopping() {
|
|
87
|
+
this.provider.addHook("onSend", async (_request, reply, payload)=>{
|
|
88
|
+
if (this.closing) reply.header("connection", "close");
|
|
89
|
+
return payload;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
get addresses() {
|
|
93
|
+
return this.provider.addresses().filter((a)=>typeof a !== "string" && a.family === "IPv4").map((a)=>`http://${a.address}:${a.port}`);
|
|
94
|
+
}
|
|
95
|
+
async registerHelmet(helmetOptions) {
|
|
96
|
+
if (helmetOptions === false) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
await this.provider.register(helmet, helmetOptions ?? {});
|
|
100
|
+
}
|
|
101
|
+
async registerRateLimit(rateLimitOptions, statics) {
|
|
102
|
+
if (rateLimitOptions === false) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
// Static files are outside the rate limit (ADR 0007). Matched on the route the request
|
|
106
|
+
// resolved to, not on its URL, so only requests the static plugin serves are exempt.
|
|
107
|
+
const staticRoutes = new Set(statics.map((mount)=>`${mount.prefix}*`));
|
|
108
|
+
const userAllowList = rateLimitOptions?.allowList;
|
|
109
|
+
await this.provider.register(rateLimit, {
|
|
110
|
+
...DEFAULT_HTTP_RATE_LIMIT,
|
|
111
|
+
...rateLimitOptions,
|
|
112
|
+
allowList: (request, key)=>{
|
|
113
|
+
if (staticRoutes.has(request.routeOptions.url ?? "")) return true;
|
|
114
|
+
if (typeof userAllowList === "function") return userAllowList(request, key);
|
|
115
|
+
return Array.isArray(userAllowList) && userAllowList.includes(key);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
async resolveStatics() {
|
|
120
|
+
return staticFiles.resolve(this.httpOptions?.statics ?? [], {
|
|
121
|
+
nodeEnv: process.env.NODE_ENV,
|
|
122
|
+
directoryExists: async (directory)=>(await stat(directory).catch(()=>undefined))?.isDirectory() === true,
|
|
123
|
+
warn: (message)=>this.logger.warn(message)
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* One encapsulated context per mount: its not-found handler (the SPA fallback) applies to
|
|
128
|
+
* paths under the prefix and nowhere else, so an API 404 is never answered with the UI.
|
|
129
|
+
*/ async registerStatic(mount, mounts) {
|
|
130
|
+
const withoutSlash = mount.prefix.slice(0, -1);
|
|
131
|
+
const isRoot = mount.prefix === "/";
|
|
132
|
+
const excluded = staticFiles.excluder(mount.exclude);
|
|
133
|
+
const belongsToApi = this.apiBoundary();
|
|
134
|
+
// Requests that already fell back once: a missing index must be a 404, not a loop.
|
|
135
|
+
const fellBack = new WeakSet();
|
|
136
|
+
await this.provider.register(async (scope)=>{
|
|
137
|
+
await scope.register(fastifyStatic, {
|
|
138
|
+
root: mount.root,
|
|
139
|
+
prefix: "/",
|
|
140
|
+
index: mount.index,
|
|
141
|
+
dotfiles: "ignore",
|
|
142
|
+
list: false,
|
|
143
|
+
redirect: false,
|
|
144
|
+
etag: true,
|
|
145
|
+
lastModified: true,
|
|
146
|
+
// The header is set in setHeaders, per file.
|
|
147
|
+
cacheControl: false,
|
|
148
|
+
setHeaders: (reply, filePath)=>{
|
|
149
|
+
reply.header("cache-control", staticFiles.cacheControlFor(mount, path.relative(mount.root, filePath)));
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
// Excluded paths are not served at all: not as a file, not as the fallback.
|
|
153
|
+
scope.addHook("onRequest", async (request, reply)=>{
|
|
154
|
+
if (excluded(staticFiles.normalizePathname(request.url))) {
|
|
155
|
+
return reply.callNotFound();
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
scope.setNotFoundHandler((request, reply)=>{
|
|
159
|
+
const [pathname = "", query] = request.url.split("?");
|
|
160
|
+
const readOnly = request.method === "GET" || request.method === "HEAD";
|
|
161
|
+
// `/ui` goes to `/ui/`. A request for it reaches the root mount's handler instead
|
|
162
|
+
// when there is one, so that handler redirects for the other mounts too.
|
|
163
|
+
const redirectTo = mounts.find((other)=>other.prefix !== "/" && other.prefix.slice(0, -1) === pathname && (isRoot || other === mount));
|
|
164
|
+
if (readOnly && redirectTo != null) {
|
|
165
|
+
return reply.redirect(query == null ? redirectTo.prefix : `${redirectTo.prefix}?${query}`, 301);
|
|
166
|
+
}
|
|
167
|
+
const normalized = staticFiles.normalizePathname(request.url);
|
|
168
|
+
if (mount.spaFallback && !fellBack.has(request) && !excluded(normalized) && staticFiles.shouldFallBack({
|
|
169
|
+
method: request.method,
|
|
170
|
+
pathname: normalized,
|
|
171
|
+
accept: request.headers.accept
|
|
172
|
+
}, belongsToApi)) {
|
|
173
|
+
fellBack.add(request);
|
|
174
|
+
return reply.sendFile(mount.index);
|
|
175
|
+
}
|
|
176
|
+
return this.sendRouteNotFound(request, reply);
|
|
177
|
+
});
|
|
178
|
+
}, {
|
|
179
|
+
prefix: withoutSlash
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Fastify's own replies, for an unknown route or a request it rejects before any handler
|
|
184
|
+
* (a body that isn't valid JSON, too large, the rate limit), are problems like the API's.
|
|
185
|
+
*/ registerProblemReplies(statics) {
|
|
186
|
+
// A UI served from the root owns the root's not-found handler, and answers the same 404.
|
|
187
|
+
if (!statics.some((mount)=>mount.prefix === "/")) {
|
|
188
|
+
this.provider.setNotFoundHandler((request, reply)=>this.sendRouteNotFound(request, reply));
|
|
189
|
+
}
|
|
190
|
+
this.provider.setErrorHandler((error, _request, reply)=>{
|
|
191
|
+
const status = this.getErrorStatus(error);
|
|
192
|
+
const message = error instanceof Error ? error.message : undefined;
|
|
193
|
+
if (status >= 500) {
|
|
194
|
+
this.logger.error(message ?? "Request failed", error instanceof Error ? error.stack : undefined);
|
|
195
|
+
}
|
|
196
|
+
const problem = problemDetails.create(status, {
|
|
197
|
+
detail: status >= 500 ? undefined : message
|
|
198
|
+
});
|
|
199
|
+
return reply.status(status).header("content-type", PROBLEM_CONTENT_TYPE).send(problem);
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
getErrorStatus(error) {
|
|
203
|
+
const status = error?.statusCode;
|
|
204
|
+
return typeof status === "number" && status >= 400 && status < 600 ? status : 500;
|
|
205
|
+
}
|
|
206
|
+
sendRouteNotFound(request, reply) {
|
|
207
|
+
const [pathname = ""] = request.url.split("?");
|
|
208
|
+
const problem = problemDetails.create(404, {
|
|
209
|
+
detail: `Route ${request.method}:${pathname} not found`
|
|
210
|
+
});
|
|
211
|
+
return reply.code(404).header("content-type", PROBLEM_CONTENT_TYPE).send(problem);
|
|
212
|
+
}
|
|
213
|
+
/** What the static fallback leaves to the API: the global prefix, else the registered routes. ADR 0007. */ apiBoundary() {
|
|
214
|
+
return staticFiles.apiBoundary({
|
|
215
|
+
globalPrefix: normalizePrefix(this.httpOptions?.globalPrefix),
|
|
216
|
+
openApiPath: this.httpOptions?.openapi == null ? undefined : resolveOpenApiPath(this.httpOptions.openapi),
|
|
217
|
+
routePaths: [
|
|
218
|
+
...this.routeRegistry.routes
|
|
219
|
+
].map((route)=>route.path)
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* `@fastify/compress` with best-practice defaults; the plugin owns the policy. Registered
|
|
224
|
+
* before any route so every response goes through it, errors and static files included.
|
|
225
|
+
* `providerOptions` is merged last, so a user can override any plugin option.
|
|
226
|
+
*/ async registerCompression(compressionOptions) {
|
|
227
|
+
if (compressionOptions === false) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
await this.provider.register(compress, {
|
|
231
|
+
global: true,
|
|
232
|
+
threshold: compressionOptions?.threshold ?? DEFAULT_COMPRESSION_THRESHOLD,
|
|
233
|
+
encodings: [
|
|
234
|
+
...compressionOptions?.encodings ?? DEFAULT_COMPRESSION_ENCODINGS
|
|
235
|
+
],
|
|
236
|
+
...compressionOptions?.types != null && {
|
|
237
|
+
customTypes: compressionOptions.types
|
|
238
|
+
},
|
|
239
|
+
...compressionOptions?.providerOptions
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
async registerCors(corsOptions) {
|
|
243
|
+
if (corsOptions == null) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
await this.provider.register(cors, {
|
|
247
|
+
origin: corsOptions.origin,
|
|
248
|
+
methods: corsOptions.methods,
|
|
249
|
+
allowedHeaders: corsOptions.allowedHeaders,
|
|
250
|
+
exposedHeaders: corsOptions.exposedHeaders,
|
|
251
|
+
credentials: corsOptions.credentials,
|
|
252
|
+
maxAge: corsOptions.maxAge
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
registerOpenApi(httpOptions) {
|
|
256
|
+
const openapi = httpOptions?.openapi;
|
|
257
|
+
if (openapi == null) {
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const path = resolveOpenApiPath(openapi);
|
|
261
|
+
const document = generateOpenApiDocument(this.routeRegistry, openapi);
|
|
262
|
+
this.provider.get(path, async (_request, reply)=>{
|
|
263
|
+
reply.header("content-type", "application/json; charset=utf-8");
|
|
264
|
+
return document;
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
registerAllRoutes(registry) {
|
|
268
|
+
for (const route of registry.routes){
|
|
269
|
+
const { key, method, path } = route;
|
|
270
|
+
this.provider.route({
|
|
271
|
+
method,
|
|
272
|
+
url: path,
|
|
273
|
+
handler: (request, reply)=>this.routeRequest(route, key, request, reply)
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
async routeRequest(route, key, request, reply) {
|
|
278
|
+
const httpRequest = this.fastifyToRequest(request);
|
|
279
|
+
const disconnect = this.abortOnDisconnect(reply, httpRequest, route.sse != null);
|
|
280
|
+
try {
|
|
281
|
+
const response = await this.router.route(key, httpRequest);
|
|
282
|
+
if (route.httpCode != null) {
|
|
283
|
+
reply.status(route.httpCode);
|
|
284
|
+
}
|
|
285
|
+
if (route.headers != null) {
|
|
286
|
+
for (const [name, value] of Object.entries(route.headers)){
|
|
287
|
+
reply.header(name, value);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
this.applyResponseHeaders(reply, httpRequest);
|
|
291
|
+
if (response instanceof SseResponse) {
|
|
292
|
+
return this.sendEventStream(route, reply, response, disconnect);
|
|
293
|
+
}
|
|
294
|
+
return response;
|
|
295
|
+
} catch (error) {
|
|
296
|
+
const result = this.exceptionFilterHost ? await this.exceptionFilterHost.handle(error, {
|
|
297
|
+
request: httpRequest
|
|
298
|
+
}) : new DefaultHttpExceptionFilter().catch(error, {
|
|
299
|
+
request: httpRequest
|
|
300
|
+
});
|
|
301
|
+
if (result.headers) {
|
|
302
|
+
for (const [name, value] of Object.entries(result.headers)){
|
|
303
|
+
reply.header(name, value);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
this.applyResponseHeaders(reply, httpRequest);
|
|
307
|
+
// Returned so Fastify waits for the async onSend hooks instead of sending an empty reply of its own.
|
|
308
|
+
return reply.status(result.status).send(result.body);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Gives the handler a signal that aborts when the client goes away before the response
|
|
313
|
+
* finished. Streams are also tracked so that stopping the app can abort them.
|
|
314
|
+
*/ abortOnDisconnect(reply, httpRequest, isStream) {
|
|
315
|
+
const controller = new AbortController();
|
|
316
|
+
httpRequest.signal = controller.signal;
|
|
317
|
+
if (isStream) {
|
|
318
|
+
if (this.closing) controller.abort(new Error("The app is stopping"));
|
|
319
|
+
this.openStreams.add(controller);
|
|
320
|
+
}
|
|
321
|
+
reply.raw.once("close", ()=>{
|
|
322
|
+
this.openStreams.delete(controller);
|
|
323
|
+
if (!reply.raw.writableFinished) {
|
|
324
|
+
controller.abort(new Error("The client disconnected"));
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
return controller;
|
|
328
|
+
}
|
|
329
|
+
sendEventStream(route, reply, response, disconnect) {
|
|
330
|
+
let started = false;
|
|
331
|
+
const release = ()=>{
|
|
332
|
+
response.release().catch((error)=>{
|
|
333
|
+
this.logger.error("Releasing the request scope of an SSE stream failed", error);
|
|
334
|
+
});
|
|
335
|
+
};
|
|
336
|
+
const frames = encodeSse(response.events, {
|
|
337
|
+
signal: disconnect.signal,
|
|
338
|
+
heartbeatMs: route.sse?.heartbeatMs ?? DEFAULT_SSE_HEARTBEAT_MS,
|
|
339
|
+
onProducerStopped: (stopped)=>void stopped.then(release)
|
|
340
|
+
});
|
|
341
|
+
const guarded = async function*() {
|
|
342
|
+
started = true;
|
|
343
|
+
yield* frames;
|
|
344
|
+
}();
|
|
345
|
+
// Never pulled if the client left first, in which case nothing else would release the scope.
|
|
346
|
+
reply.raw.once("close", ()=>{
|
|
347
|
+
if (!started) release();
|
|
348
|
+
});
|
|
349
|
+
return reply.status(route.httpCode ?? 200).header("content-type", "text/event-stream; charset=utf-8").header("cache-control", "no-cache, no-transform").header("x-accel-buffering", "no")// A stream owns its connection; closing it afterwards lets app stop finish at once instead of waiting out keep-alive.
|
|
350
|
+
.header("connection", "close").send(Readable.from(guarded));
|
|
351
|
+
}
|
|
352
|
+
applyResponseHeaders(reply, httpRequest) {
|
|
353
|
+
reply.header(REQUEST_ID_HEADER, httpRequest.requestId);
|
|
354
|
+
for (const [name, value] of Object.entries(httpRequest.responseHeaders)){
|
|
355
|
+
reply.header(name, value);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
fastifyToRequest(fastifyRequest) {
|
|
359
|
+
const method = fastifyRequest.method;
|
|
360
|
+
const url = fastifyRequest.url;
|
|
361
|
+
const params = fastifyRequest.params;
|
|
362
|
+
const query = fastifyRequest.query;
|
|
363
|
+
const body = fastifyRequest.body ?? {};
|
|
364
|
+
const headers = {};
|
|
365
|
+
for (const [key, value] of Object.entries(fastifyRequest.headers)){
|
|
366
|
+
if (typeof value === "string") {
|
|
367
|
+
headers[key.toLowerCase()] = value;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const requestId = resolveRequestId(headers, String(fastifyRequest.id ?? ""));
|
|
371
|
+
return new HttpRequest({
|
|
372
|
+
requestId,
|
|
373
|
+
url,
|
|
374
|
+
method,
|
|
375
|
+
params,
|
|
376
|
+
query,
|
|
377
|
+
body,
|
|
378
|
+
headers
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
FastifyProvider = _ts_decorate([
|
|
383
|
+
_ts_param(0, inject(RouteRegistryToken)),
|
|
384
|
+
_ts_param(1, inject(RouterToken)),
|
|
385
|
+
_ts_param(2, inject(HttpOptionsToken)),
|
|
386
|
+
_ts_param(3, inject(ExceptionFilterHostToken)),
|
|
387
|
+
_ts_metadata("design:type", Function),
|
|
388
|
+
_ts_metadata("design:paramtypes", [
|
|
389
|
+
typeof RouteRegistry === "undefined" ? Object : RouteRegistry,
|
|
390
|
+
typeof Router === "undefined" ? Object : Router,
|
|
391
|
+
typeof HttpOptions === "undefined" ? Object : HttpOptions,
|
|
392
|
+
typeof ExceptionFilterHost === "undefined" ? Object : ExceptionFilterHost
|
|
393
|
+
])
|
|
394
|
+
], FastifyProvider);
|
package/es6/src/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { FastifyProvider } from "./fastify.provider.js";
|
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.20261120.336",
|
|
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.20261120.336",
|
|
36
|
+
"@decohere/http": "0.0.1-dev.20261120.336",
|
|
37
|
+
"@decohere/scribe": "0.0.1-dev.20261120.336",
|
|
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,59 @@
|
|
|
1
|
+
import { type FastifyInstance } from "fastify";
|
|
2
|
+
import { type ExceptionFilterHost, type HttpOptions, type HttpProvider, type RouteRegistry, type Router, type StartOptions, type StartResponse, type StopResponse } from "@decohere/http";
|
|
3
|
+
export declare class FastifyProvider implements HttpProvider {
|
|
4
|
+
readonly provider: FastifyInstance;
|
|
5
|
+
readonly router: Router;
|
|
6
|
+
private readonly routeRegistry;
|
|
7
|
+
private readonly httpOptions?;
|
|
8
|
+
private readonly exceptionFilterHost?;
|
|
9
|
+
private closing;
|
|
10
|
+
private readonly logger;
|
|
11
|
+
/** One per live `@Sse()` request, so stopping the app can end the streams. */
|
|
12
|
+
private readonly openStreams;
|
|
13
|
+
constructor(routeRegistry?: RouteRegistry, router?: Router, httpOptions?: HttpOptions, exceptionFilterHost?: ExceptionFilterHost);
|
|
14
|
+
start<T extends StartOptions>(options?: T): Promise<StartResponse>;
|
|
15
|
+
stop(): Promise<StopResponse>;
|
|
16
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Once stopping, tell clients to drop the connection after their response. Otherwise
|
|
19
|
+
* a request that was in flight leaves a kept-alive socket that holds `close()` open
|
|
20
|
+
* until Node's keep-alive timeout (5s).
|
|
21
|
+
*/
|
|
22
|
+
private closeConnectionsWhileStopping;
|
|
23
|
+
get addresses(): string[];
|
|
24
|
+
private registerHelmet;
|
|
25
|
+
private registerRateLimit;
|
|
26
|
+
private resolveStatics;
|
|
27
|
+
/**
|
|
28
|
+
* One encapsulated context per mount: its not-found handler (the SPA fallback) applies to
|
|
29
|
+
* paths under the prefix and nowhere else, so an API 404 is never answered with the UI.
|
|
30
|
+
*/
|
|
31
|
+
private registerStatic;
|
|
32
|
+
/**
|
|
33
|
+
* Fastify's own replies, for an unknown route or a request it rejects before any handler
|
|
34
|
+
* (a body that isn't valid JSON, too large, the rate limit), are problems like the API's.
|
|
35
|
+
*/
|
|
36
|
+
private registerProblemReplies;
|
|
37
|
+
private getErrorStatus;
|
|
38
|
+
private sendRouteNotFound;
|
|
39
|
+
/** What the static fallback leaves to the API: the global prefix, else the registered routes. ADR 0007. */
|
|
40
|
+
private apiBoundary;
|
|
41
|
+
/**
|
|
42
|
+
* `@fastify/compress` with best-practice defaults; the plugin owns the policy. Registered
|
|
43
|
+
* before any route so every response goes through it, errors and static files included.
|
|
44
|
+
* `providerOptions` is merged last, so a user can override any plugin option.
|
|
45
|
+
*/
|
|
46
|
+
private registerCompression;
|
|
47
|
+
private registerCors;
|
|
48
|
+
private registerOpenApi;
|
|
49
|
+
private registerAllRoutes;
|
|
50
|
+
private routeRequest;
|
|
51
|
+
/**
|
|
52
|
+
* Gives the handler a signal that aborts when the client goes away before the response
|
|
53
|
+
* finished. Streams are also tracked so that stopping the app can abort them.
|
|
54
|
+
*/
|
|
55
|
+
private abortOnDisconnect;
|
|
56
|
+
private sendEventStream;
|
|
57
|
+
private applyResponseHeaders;
|
|
58
|
+
private fastifyToRequest;
|
|
59
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { FastifyProvider } from "./fastify.provider.js";
|