@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,315 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createServer,
|
|
3
|
+
STATUS_CODES,
|
|
4
|
+
type IncomingMessage,
|
|
5
|
+
type ServerResponse,
|
|
6
|
+
} from 'node:http';
|
|
7
|
+
import type { AddressInfo, Socket } from 'node:net';
|
|
8
|
+
|
|
9
|
+
import { type WebSocket as WsSocket, WebSocketServer } from 'ws';
|
|
10
|
+
|
|
11
|
+
import { HttpError } from '../errors.js';
|
|
12
|
+
import { HttpRequest, type ResponseSink } from '../request.js';
|
|
13
|
+
import type { TransportSocket, WebSocketSession } from '../websocket.js';
|
|
14
|
+
import {
|
|
15
|
+
EMPTY_BODY,
|
|
16
|
+
type ListeningServer,
|
|
17
|
+
type RequestHandler,
|
|
18
|
+
type Transport,
|
|
19
|
+
type TransportOptions,
|
|
20
|
+
} from './transport.js';
|
|
21
|
+
|
|
22
|
+
class NodeRequest extends HttpRequest {
|
|
23
|
+
readonly method: string;
|
|
24
|
+
readonly path: string;
|
|
25
|
+
readonly query: string;
|
|
26
|
+
readonly headers: Readonly<Record<string, string | undefined>>;
|
|
27
|
+
/** Set when the body was rejected, so the connection is closed after replying. */
|
|
28
|
+
closeConnection = false;
|
|
29
|
+
private bodyPromise: Promise<Uint8Array> | undefined;
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
private readonly raw: IncomingMessage,
|
|
33
|
+
private readonly bodyLimit: number,
|
|
34
|
+
) {
|
|
35
|
+
super();
|
|
36
|
+
const url = raw.url ?? '/';
|
|
37
|
+
const queryStart = url.indexOf('?');
|
|
38
|
+
this.method = raw.method ?? 'GET';
|
|
39
|
+
this.path = queryStart === -1 ? url : url.slice(0, queryStart);
|
|
40
|
+
this.query = queryStart === -1 ? '' : url.slice(queryStart + 1);
|
|
41
|
+
this.headers = raw.headers as Record<string, string | undefined>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
get remoteAddress(): string {
|
|
45
|
+
return this.raw.socket.remoteAddress ?? '';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
body(): Promise<Uint8Array> {
|
|
49
|
+
this.bodyPromise ??= this.readBody();
|
|
50
|
+
return this.bodyPromise;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private readBody(): Promise<Uint8Array> {
|
|
54
|
+
const { raw, bodyLimit } = this;
|
|
55
|
+
const declared = Number(raw.headers['content-length'] ?? Number.NaN);
|
|
56
|
+
|
|
57
|
+
if (declared > bodyLimit) {
|
|
58
|
+
this.closeConnection = true;
|
|
59
|
+
return Promise.reject(tooLarge(bodyLimit));
|
|
60
|
+
}
|
|
61
|
+
if (
|
|
62
|
+
declared === 0 ||
|
|
63
|
+
(Number.isNaN(declared) && raw.headers['transfer-encoding'] === undefined)
|
|
64
|
+
) {
|
|
65
|
+
return Promise.resolve(EMPTY_BODY);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return new Promise((resolve, reject) => {
|
|
69
|
+
const chunks: Buffer[] = [];
|
|
70
|
+
let size = 0;
|
|
71
|
+
let rejected = false;
|
|
72
|
+
|
|
73
|
+
raw.on('data', (chunk: Buffer) => {
|
|
74
|
+
if (rejected) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
size += chunk.byteLength;
|
|
78
|
+
if (size > bodyLimit) {
|
|
79
|
+
rejected = true;
|
|
80
|
+
this.closeConnection = true;
|
|
81
|
+
chunks.length = 0;
|
|
82
|
+
reject(tooLarge(bodyLimit));
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
chunks.push(chunk);
|
|
86
|
+
});
|
|
87
|
+
raw.on('end', () => {
|
|
88
|
+
if (!rejected) {
|
|
89
|
+
resolve(
|
|
90
|
+
chunks.length === 1
|
|
91
|
+
? (chunks[0] as Buffer)
|
|
92
|
+
: Buffer.concat(chunks, size),
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
raw.on('error', (error) => {
|
|
97
|
+
if (!rejected) {
|
|
98
|
+
rejected = true;
|
|
99
|
+
reject(error);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function tooLarge(limit: number): HttpError {
|
|
107
|
+
return new HttpError(
|
|
108
|
+
413,
|
|
109
|
+
`The request body exceeds the limit of ${limit} bytes.`,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
class NodeSink implements ResponseSink {
|
|
114
|
+
constructor(
|
|
115
|
+
private readonly request: NodeRequest,
|
|
116
|
+
private readonly response: ServerResponse,
|
|
117
|
+
) {}
|
|
118
|
+
|
|
119
|
+
get aborted(): boolean {
|
|
120
|
+
return this.response.destroyed;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
onAbort(handler: () => void): void {
|
|
124
|
+
this.response.once('close', () => {
|
|
125
|
+
if (!this.response.writableFinished) {
|
|
126
|
+
handler();
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
send(
|
|
132
|
+
status: number,
|
|
133
|
+
headers: Readonly<Record<string, string>>,
|
|
134
|
+
body: string | Uint8Array | undefined,
|
|
135
|
+
): void {
|
|
136
|
+
const { response } = this;
|
|
137
|
+
const outgoing: Record<string, string> = { ...headers };
|
|
138
|
+
|
|
139
|
+
if (body !== undefined) {
|
|
140
|
+
outgoing['content-length'] = String(
|
|
141
|
+
typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength,
|
|
142
|
+
);
|
|
143
|
+
} else if (status !== 204 && status !== 304) {
|
|
144
|
+
outgoing['content-length'] = '0';
|
|
145
|
+
}
|
|
146
|
+
if (this.request.closeConnection) {
|
|
147
|
+
outgoing['connection'] = 'close';
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Node omits the body of responses to HEAD requests itself.
|
|
151
|
+
response.writeHead(status, outgoing);
|
|
152
|
+
response.end(body);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Answers upgrade requests that are refused, directly on the socket. */
|
|
157
|
+
class UpgradeSink implements ResponseSink {
|
|
158
|
+
upgrade?: (session: WebSocketSession) => void;
|
|
159
|
+
|
|
160
|
+
constructor(private readonly socket: Socket) {}
|
|
161
|
+
|
|
162
|
+
get aborted(): boolean {
|
|
163
|
+
return this.socket.destroyed;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
onAbort(handler: () => void): void {
|
|
167
|
+
this.socket.once('close', handler);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
send(
|
|
171
|
+
status: number,
|
|
172
|
+
headers: Readonly<Record<string, string>>,
|
|
173
|
+
body: string | Uint8Array | undefined,
|
|
174
|
+
): void {
|
|
175
|
+
const bytes = body === undefined ? Buffer.alloc(0) : Buffer.from(body);
|
|
176
|
+
const lines = [`HTTP/1.1 ${status} ${STATUS_CODES[status] ?? ''}`];
|
|
177
|
+
for (const [name, value] of Object.entries({
|
|
178
|
+
...headers,
|
|
179
|
+
connection: 'close',
|
|
180
|
+
})) {
|
|
181
|
+
lines.push(`${name}: ${value}`);
|
|
182
|
+
}
|
|
183
|
+
lines.push(`content-length: ${bytes.byteLength}`, '', '');
|
|
184
|
+
this.socket.end(Buffer.concat([Buffer.from(lines.join('\r\n')), bytes]));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** A WebSocket from the `ws` package, with in-memory topics. */
|
|
189
|
+
class NodeSocket implements TransportSocket {
|
|
190
|
+
private readonly subscriptions = new Set<string>();
|
|
191
|
+
|
|
192
|
+
constructor(
|
|
193
|
+
private readonly ws: WsSocket,
|
|
194
|
+
private readonly topics: Map<string, Set<NodeSocket>>,
|
|
195
|
+
readonly remoteAddress: string,
|
|
196
|
+
) {}
|
|
197
|
+
|
|
198
|
+
send(message: string | Uint8Array): boolean {
|
|
199
|
+
if (this.ws.readyState !== this.ws.OPEN) {
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
this.ws.send(message);
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
close(code?: number, reason?: string): void {
|
|
207
|
+
this.ws.close(code, reason);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
subscribe(topic: string): void {
|
|
211
|
+
let members = this.topics.get(topic);
|
|
212
|
+
if (members === undefined) {
|
|
213
|
+
members = new Set();
|
|
214
|
+
this.topics.set(topic, members);
|
|
215
|
+
}
|
|
216
|
+
members.add(this);
|
|
217
|
+
this.subscriptions.add(topic);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
unsubscribe(topic: string): void {
|
|
221
|
+
this.topics.get(topic)?.delete(this);
|
|
222
|
+
this.subscriptions.delete(topic);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
publish(topic: string, message: string | Uint8Array): void {
|
|
226
|
+
for (const member of this.topics.get(topic) ?? []) {
|
|
227
|
+
if (member !== this) {
|
|
228
|
+
member.send(message);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
dispose(): void {
|
|
234
|
+
for (const topic of [...this.subscriptions]) {
|
|
235
|
+
this.unsubscribe(topic);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** A transport on Node's built-in `node:http` server. No native code. */
|
|
241
|
+
export const nodeTransport: Transport = {
|
|
242
|
+
name: 'node',
|
|
243
|
+
|
|
244
|
+
listen(
|
|
245
|
+
options: TransportOptions,
|
|
246
|
+
handler: RequestHandler,
|
|
247
|
+
): Promise<ListeningServer> {
|
|
248
|
+
const server = createServer((raw, response) => {
|
|
249
|
+
const request = new NodeRequest(raw, options.bodyLimit);
|
|
250
|
+
handler(request, new NodeSink(request, response));
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
const sockets = new WebSocketServer({
|
|
254
|
+
noServer: true,
|
|
255
|
+
maxPayload: options.websocket.maxPayload,
|
|
256
|
+
});
|
|
257
|
+
const topics = new Map<string, Set<NodeSocket>>();
|
|
258
|
+
server.on(
|
|
259
|
+
'upgrade',
|
|
260
|
+
(raw: IncomingMessage, socket: Socket, head: Buffer) => {
|
|
261
|
+
const request = new NodeRequest(raw, options.bodyLimit);
|
|
262
|
+
const sink = new UpgradeSink(socket);
|
|
263
|
+
sink.upgrade = (session) => {
|
|
264
|
+
sockets.handleUpgrade(raw, socket, head, (ws) => {
|
|
265
|
+
const transport = new NodeSocket(
|
|
266
|
+
ws,
|
|
267
|
+
topics,
|
|
268
|
+
socket.remoteAddress ?? '',
|
|
269
|
+
);
|
|
270
|
+
ws.on('message', (data: Buffer, isBinary: boolean) => {
|
|
271
|
+
session.received(
|
|
272
|
+
isBinary ? new Uint8Array(data) : data.toString('utf8'),
|
|
273
|
+
);
|
|
274
|
+
});
|
|
275
|
+
ws.on('close', (code: number, reason: Buffer) => {
|
|
276
|
+
transport.dispose();
|
|
277
|
+
session.closed(code, reason.toString('utf8'));
|
|
278
|
+
});
|
|
279
|
+
session.opened(transport);
|
|
280
|
+
});
|
|
281
|
+
};
|
|
282
|
+
handler(request, sink);
|
|
283
|
+
},
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
return new Promise((resolve, reject) => {
|
|
287
|
+
server.once('error', reject);
|
|
288
|
+
server.listen(options.port, options.host, () => {
|
|
289
|
+
server.off('error', reject);
|
|
290
|
+
resolve({
|
|
291
|
+
port: (server.address() as AddressInfo).port,
|
|
292
|
+
stopAccepting() {
|
|
293
|
+
server.close();
|
|
294
|
+
server.closeIdleConnections();
|
|
295
|
+
},
|
|
296
|
+
close() {
|
|
297
|
+
for (const client of sockets.clients) {
|
|
298
|
+
client.terminate();
|
|
299
|
+
}
|
|
300
|
+
sockets.close();
|
|
301
|
+
return new Promise<void>((done) => {
|
|
302
|
+
server.close(() => done());
|
|
303
|
+
server.closeAllConnections();
|
|
304
|
+
});
|
|
305
|
+
},
|
|
306
|
+
publish(topic, message) {
|
|
307
|
+
for (const member of topics.get(topic) ?? []) {
|
|
308
|
+
member.send(message);
|
|
309
|
+
}
|
|
310
|
+
},
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
},
|
|
315
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { HttpRequest, ResponseSink } from '../request.js';
|
|
2
|
+
|
|
3
|
+
export type RequestHandler = (request: HttpRequest, sink: ResponseSink) => void;
|
|
4
|
+
|
|
5
|
+
export interface TransportOptions {
|
|
6
|
+
port: number;
|
|
7
|
+
/** Interface to bind; all interfaces when undefined. */
|
|
8
|
+
host: string | undefined;
|
|
9
|
+
/** Maximum request body size in bytes. */
|
|
10
|
+
bodyLimit: number;
|
|
11
|
+
websocket: {
|
|
12
|
+
/** Largest accepted message, in bytes. */
|
|
13
|
+
maxPayload: number;
|
|
14
|
+
/** Close connections idle this long, in milliseconds (uws only). */
|
|
15
|
+
idleTimeout: number;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface ListeningServer {
|
|
20
|
+
/** The bound port (useful when listening on port 0). */
|
|
21
|
+
readonly port: number;
|
|
22
|
+
/** Stops accepting connections and closes idle keep-alive connections. */
|
|
23
|
+
stopAccepting(): void;
|
|
24
|
+
/** Closes every remaining connection. */
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
/** Sends a message to every WebSocket subscribed to `topic`. */
|
|
27
|
+
publish(topic: string, message: string | Uint8Array): void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Turns network traffic into `HttpRequest`s and writes `ResponseSink` replies. */
|
|
31
|
+
export interface Transport {
|
|
32
|
+
readonly name: string;
|
|
33
|
+
listen(
|
|
34
|
+
options: TransportOptions,
|
|
35
|
+
handler: RequestHandler,
|
|
36
|
+
): Promise<ListeningServer>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const EMPTY_BODY = new Uint8Array(0);
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { STATUS_CODES } from 'node:http';
|
|
2
|
+
|
|
3
|
+
import type * as UWS from 'uWebSockets.js';
|
|
4
|
+
|
|
5
|
+
import { HttpError } from '../errors.js';
|
|
6
|
+
import { HttpRequest, type ResponseSink } from '../request.js';
|
|
7
|
+
import type { TransportSocket, WebSocketSession } from '../websocket.js';
|
|
8
|
+
import {
|
|
9
|
+
EMPTY_BODY,
|
|
10
|
+
type ListeningServer,
|
|
11
|
+
type RequestHandler,
|
|
12
|
+
type Transport,
|
|
13
|
+
type TransportOptions,
|
|
14
|
+
} from './transport.js';
|
|
15
|
+
|
|
16
|
+
const textDecoder = new TextDecoder();
|
|
17
|
+
const statusLines = new Map<number, string>();
|
|
18
|
+
|
|
19
|
+
function statusLine(status: number): string {
|
|
20
|
+
let line = statusLines.get(status);
|
|
21
|
+
if (line === undefined) {
|
|
22
|
+
line = `${status} ${STATUS_CODES[status] ?? 'Unknown'}`;
|
|
23
|
+
statusLines.set(status, line);
|
|
24
|
+
}
|
|
25
|
+
return line;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* uWebSockets.js only lets a request be read synchronously inside its
|
|
30
|
+
* handler, so everything is copied out up front, and the body is collected
|
|
31
|
+
* immediately when there is one.
|
|
32
|
+
*/
|
|
33
|
+
class UwsRequest extends HttpRequest {
|
|
34
|
+
readonly method: string;
|
|
35
|
+
readonly path: string;
|
|
36
|
+
readonly query: string;
|
|
37
|
+
readonly headers: Record<string, string | undefined> = {};
|
|
38
|
+
closeConnection = false;
|
|
39
|
+
private readonly bodyPromise: Promise<Uint8Array>;
|
|
40
|
+
private address: string | undefined;
|
|
41
|
+
|
|
42
|
+
constructor(
|
|
43
|
+
request: UWS.HttpRequest,
|
|
44
|
+
private readonly response: UWS.HttpResponse,
|
|
45
|
+
sink: UwsSink,
|
|
46
|
+
bodyLimit: number,
|
|
47
|
+
) {
|
|
48
|
+
super();
|
|
49
|
+
this.method = request.getCaseSensitiveMethod();
|
|
50
|
+
this.path = request.getUrl();
|
|
51
|
+
this.query = request.getQuery() ?? '';
|
|
52
|
+
request.forEach((name, value) => {
|
|
53
|
+
const existing = this.headers[name];
|
|
54
|
+
this.headers[name] =
|
|
55
|
+
existing === undefined ? value : `${existing}, ${value}`;
|
|
56
|
+
});
|
|
57
|
+
this.bodyPromise = this.collect(sink, bodyLimit);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
get remoteAddress(): string {
|
|
61
|
+
// The response is only usable until it has been sent.
|
|
62
|
+
this.address ??= textDecoder.decode(this.response.getRemoteAddressAsText());
|
|
63
|
+
return this.address;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
body(): Promise<Uint8Array> {
|
|
67
|
+
return this.bodyPromise;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private collect(sink: UwsSink, limit: number): Promise<Uint8Array> {
|
|
71
|
+
const length = this.headers['content-length'];
|
|
72
|
+
const chunked = this.headers['transfer-encoding'] !== undefined;
|
|
73
|
+
const declared = length === undefined ? 0 : Number(length);
|
|
74
|
+
|
|
75
|
+
if (!chunked && !(declared > 0)) {
|
|
76
|
+
return Promise.resolve(EMPTY_BODY);
|
|
77
|
+
}
|
|
78
|
+
if (declared > limit) {
|
|
79
|
+
this.closeConnection = true;
|
|
80
|
+
return rejected(tooLarge(limit));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
sink.onAbort(() => reject(new Error('The client disconnected.')));
|
|
85
|
+
this.response.collectBody(limit, (body) => {
|
|
86
|
+
if (body === null) {
|
|
87
|
+
this.closeConnection = true;
|
|
88
|
+
reject(tooLarge(limit));
|
|
89
|
+
} else {
|
|
90
|
+
// Copy: the buffer may not outlive this callback.
|
|
91
|
+
resolve(new Uint8Array(body.slice(0)));
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** A rejected promise that does not count as unhandled until someone awaits it. */
|
|
99
|
+
function rejected(error: Error): Promise<never> {
|
|
100
|
+
const promise = Promise.reject(error);
|
|
101
|
+
promise.catch(() => undefined);
|
|
102
|
+
return promise;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function tooLarge(limit: number): HttpError {
|
|
106
|
+
return new HttpError(
|
|
107
|
+
413,
|
|
108
|
+
`The request body exceeds the limit of ${limit} bytes.`,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
class UwsSink implements ResponseSink {
|
|
113
|
+
aborted = false;
|
|
114
|
+
upgrade?: (session: WebSocketSession) => void;
|
|
115
|
+
request!: UwsRequest;
|
|
116
|
+
private abortHandlers: (() => void)[] | undefined;
|
|
117
|
+
|
|
118
|
+
constructor(private readonly response: UWS.HttpResponse) {
|
|
119
|
+
response.onAborted(() => {
|
|
120
|
+
this.aborted = true;
|
|
121
|
+
for (const handler of this.abortHandlers ?? []) {
|
|
122
|
+
handler();
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
onAbort(handler: () => void): void {
|
|
128
|
+
(this.abortHandlers ??= []).push(handler);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
send(
|
|
132
|
+
status: number,
|
|
133
|
+
headers: Readonly<Record<string, string>>,
|
|
134
|
+
body: string | Uint8Array | undefined,
|
|
135
|
+
head: boolean,
|
|
136
|
+
): void {
|
|
137
|
+
if (this.aborted) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const { response } = this;
|
|
142
|
+
let close = this.request.closeConnection;
|
|
143
|
+
|
|
144
|
+
response.cork(() => {
|
|
145
|
+
response.writeStatus(statusLine(status));
|
|
146
|
+
for (const name in headers) {
|
|
147
|
+
if (name === 'connection') {
|
|
148
|
+
// uWebSockets.js writes this header itself when closing.
|
|
149
|
+
close ||= headers[name] === 'close';
|
|
150
|
+
} else if (name !== 'content-length') {
|
|
151
|
+
response.writeHeader(name, headers[name] as string);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (body === undefined) {
|
|
156
|
+
if (status === 204 || status === 304) {
|
|
157
|
+
response.endWithoutBody(undefined, close);
|
|
158
|
+
} else {
|
|
159
|
+
response.end(undefined, close);
|
|
160
|
+
}
|
|
161
|
+
} else if (head) {
|
|
162
|
+
const length =
|
|
163
|
+
typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength;
|
|
164
|
+
response.endWithoutBody(length, close);
|
|
165
|
+
} else {
|
|
166
|
+
response.end(body, close);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* A transport on uWebSockets.js: native networking and HTTP parsing, much
|
|
174
|
+
* faster than `node:http`. Throws if the native module cannot be loaded on
|
|
175
|
+
* this platform or Node version.
|
|
176
|
+
*/
|
|
177
|
+
export async function uwsTransport(): Promise<Transport> {
|
|
178
|
+
const uws: typeof UWS = await import('uWebSockets.js');
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
name: 'uws',
|
|
182
|
+
|
|
183
|
+
listen(
|
|
184
|
+
options: TransportOptions,
|
|
185
|
+
handler: RequestHandler,
|
|
186
|
+
): Promise<ListeningServer> {
|
|
187
|
+
const app = uws.App();
|
|
188
|
+
|
|
189
|
+
app.ws<{ session: WebSocketSession; closed: boolean }>('/*', {
|
|
190
|
+
maxPayloadLength: options.websocket.maxPayload,
|
|
191
|
+
// uWebSockets.js accepts 0 (off) or at least 8 seconds.
|
|
192
|
+
idleTimeout: Math.max(
|
|
193
|
+
8,
|
|
194
|
+
Math.round(options.websocket.idleTimeout / 1000),
|
|
195
|
+
),
|
|
196
|
+
sendPingsAutomatically: true,
|
|
197
|
+
upgrade: (response, request, context) => {
|
|
198
|
+
const sink = new UwsSink(response);
|
|
199
|
+
const uwsRequest = new UwsRequest(
|
|
200
|
+
request,
|
|
201
|
+
response,
|
|
202
|
+
sink,
|
|
203
|
+
options.bodyLimit,
|
|
204
|
+
);
|
|
205
|
+
sink.request = uwsRequest;
|
|
206
|
+
const { headers } = uwsRequest;
|
|
207
|
+
sink.upgrade = (session) => {
|
|
208
|
+
if (sink.aborted) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
response.cork(() =>
|
|
212
|
+
response.upgrade(
|
|
213
|
+
{ session, closed: false },
|
|
214
|
+
headers['sec-websocket-key'] ?? '',
|
|
215
|
+
headers['sec-websocket-protocol'] ?? '',
|
|
216
|
+
headers['sec-websocket-extensions'] ?? '',
|
|
217
|
+
context,
|
|
218
|
+
),
|
|
219
|
+
);
|
|
220
|
+
};
|
|
221
|
+
handler(uwsRequest, sink);
|
|
222
|
+
},
|
|
223
|
+
open: (ws) => {
|
|
224
|
+
const state = ws.getUserData();
|
|
225
|
+
const remoteAddress = textDecoder.decode(ws.getRemoteAddressAsText());
|
|
226
|
+
const socket: TransportSocket = {
|
|
227
|
+
remoteAddress,
|
|
228
|
+
send: (message) =>
|
|
229
|
+
!state.closed &&
|
|
230
|
+
ws.send(message, typeof message !== 'string') !== 2,
|
|
231
|
+
close: (code, reason) => {
|
|
232
|
+
if (!state.closed) ws.end(code, reason);
|
|
233
|
+
},
|
|
234
|
+
subscribe: (topic) => {
|
|
235
|
+
if (!state.closed) ws.subscribe(topic);
|
|
236
|
+
},
|
|
237
|
+
unsubscribe: (topic) => {
|
|
238
|
+
if (!state.closed) ws.unsubscribe(topic);
|
|
239
|
+
},
|
|
240
|
+
publish: (topic, message) => {
|
|
241
|
+
if (!state.closed)
|
|
242
|
+
ws.publish(topic, message, typeof message !== 'string');
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
state.session.opened(socket);
|
|
246
|
+
},
|
|
247
|
+
message: (ws, message, isBinary) => {
|
|
248
|
+
// The buffer is only valid during this call: copy or decode it now.
|
|
249
|
+
ws.getUserData().session.received(
|
|
250
|
+
isBinary
|
|
251
|
+
? new Uint8Array(message.slice(0))
|
|
252
|
+
: textDecoder.decode(message),
|
|
253
|
+
);
|
|
254
|
+
},
|
|
255
|
+
close: (ws, code, message) => {
|
|
256
|
+
const state = ws.getUserData();
|
|
257
|
+
state.closed = true;
|
|
258
|
+
state.session.closed(code, textDecoder.decode(message));
|
|
259
|
+
},
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
app.any('/*', (response, request) => {
|
|
263
|
+
const sink = new UwsSink(response);
|
|
264
|
+
sink.request = new UwsRequest(
|
|
265
|
+
request,
|
|
266
|
+
response,
|
|
267
|
+
sink,
|
|
268
|
+
options.bodyLimit,
|
|
269
|
+
);
|
|
270
|
+
handler(sink.request, sink);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
return new Promise((resolve, reject) => {
|
|
274
|
+
const onListen = (socket: UWS.us_listen_socket | false): void => {
|
|
275
|
+
if (socket === false) {
|
|
276
|
+
app.close();
|
|
277
|
+
reject(new Error(`Could not listen on port ${options.port}.`));
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
let listening: UWS.us_listen_socket | undefined = socket;
|
|
282
|
+
const stopAccepting = (): void => {
|
|
283
|
+
if (listening !== undefined) {
|
|
284
|
+
uws.us_listen_socket_close(listening);
|
|
285
|
+
listening = undefined;
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
resolve({
|
|
289
|
+
port: uws.us_socket_local_port(socket),
|
|
290
|
+
stopAccepting,
|
|
291
|
+
close() {
|
|
292
|
+
stopAccepting();
|
|
293
|
+
app.close();
|
|
294
|
+
return Promise.resolve();
|
|
295
|
+
},
|
|
296
|
+
publish(topic, message) {
|
|
297
|
+
app.publish(topic, message, typeof message !== 'string');
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
if (options.host === undefined) {
|
|
303
|
+
app.listen(options.port, onListen);
|
|
304
|
+
} else {
|
|
305
|
+
app.listen(options.host, options.port, onListen);
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
},
|
|
309
|
+
};
|
|
310
|
+
}
|