weida-http 0.0.0-stage → 0.1.0-alpha.19
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 +70 -2
- package/lib/errors.js +31 -0
- package/lib/index.d.ts +349 -0
- package/lib/index.js +1429 -0
- package/lib/native.js +12 -0
- package/lib/shared/convert.js +208 -0
- package/lib/shared/errors.js +28 -0
- package/lib/shared/handle.js +55 -0
- package/lib/shared/load.js +74 -0
- package/lib/shared/wait.js +90 -0
- package/package.json +45 -4
- package/prebuilds/darwin-arm64/libweida_http.dylib +0 -0
- package/prebuilds/darwin-arm64/weida_http.node +0 -0
- package/prebuilds/linux-arm64/libweida_http.so +0 -0
- package/prebuilds/linux-arm64/weida_http.node +0 -0
- package/prebuilds/linux-x64/libweida_http.so +0 -0
- package/prebuilds/linux-x64/weida_http.node +0 -0
- package/prebuilds/win32-x64/weida_http.dll +0 -0
- package/prebuilds/win32-x64/weida_http.node +0 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1429 @@
|
|
|
1
|
+
// weida-http: HTTP/1.1, HTTP/2 and HTTP/3 for JavaScript, a client and a
|
|
2
|
+
// server, over the Node-API addon of libweida_http, the C ABI of the Rust
|
|
3
|
+
// `weida-http` library (docs/libraries/http-js.md). The API is the Python
|
|
4
|
+
// package `weida_http`'s in JavaScript idiom: a Client whose requests
|
|
5
|
+
// resolve with a Response whose body streams, a Server whose exchanges are
|
|
6
|
+
// pulled and answered, immutable values a caller builds (Fields, Url,
|
|
7
|
+
// Limits, ClientTls, ServerTls, ClientOptions, ServerOptions) and one error
|
|
8
|
+
// class, HttpError.
|
|
9
|
+
//
|
|
10
|
+
// Every method that waits returns a Promise and takes an optional last
|
|
11
|
+
// `{ signal }`; `AbortSignal.timeout(ms)` is the timeout. Aborting a request
|
|
12
|
+
// abandons it; aborting a read or a write of a body leaves that body
|
|
13
|
+
// unusable, except a receive of the next chunk (`Body.recv`) or exchange
|
|
14
|
+
// (`Server.accept`), which loses nothing. A dropped object throws HttpError
|
|
15
|
+
// `WEIDA_HTTP_ECLOSED` without calling C. Durations are milliseconds.
|
|
16
|
+
import { readFileSync } from "node:fs";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
|
|
19
|
+
import native, { libraryPath as LIBRARY_PATH } from "./native.js";
|
|
20
|
+
import { HttpError } from "./errors.js";
|
|
21
|
+
import {
|
|
22
|
+
bytes,
|
|
23
|
+
certPem,
|
|
24
|
+
configured,
|
|
25
|
+
defaultThreads,
|
|
26
|
+
describe,
|
|
27
|
+
duration,
|
|
28
|
+
integer,
|
|
29
|
+
isAnchor,
|
|
30
|
+
isBytes,
|
|
31
|
+
keyPem,
|
|
32
|
+
millis,
|
|
33
|
+
optionalInteger,
|
|
34
|
+
optionsOf,
|
|
35
|
+
text,
|
|
36
|
+
withBuilt,
|
|
37
|
+
} from "./shared/convert.js";
|
|
38
|
+
import { HANDLE, Handle, adopt, handleOf, init, noConstructor } from "./shared/handle.js";
|
|
39
|
+
import { call, op } from "./shared/wait.js";
|
|
40
|
+
|
|
41
|
+
export { HttpError };
|
|
42
|
+
|
|
43
|
+
const C = native.CONSTANTS;
|
|
44
|
+
const constant = (name) => C[`WEIDA_HTTP_${name}`];
|
|
45
|
+
|
|
46
|
+
const U16 = 0xffff;
|
|
47
|
+
const U32 = 0xffffffff;
|
|
48
|
+
const U64 = 2n ** 64n - 1n;
|
|
49
|
+
|
|
50
|
+
/** Every constant of weida_http.h by name (`WEIDA_HTTP_ETOO_LARGE`, ...),
|
|
51
|
+
* frozen. */
|
|
52
|
+
export const CONSTANTS = C;
|
|
53
|
+
|
|
54
|
+
/** What this side accepts from its peer by default (`Limits`): the largest
|
|
55
|
+
* head, field section or trailer section, in bytes. */
|
|
56
|
+
export const DEFAULT_MAX_HEAD_BYTES = constant("DEFAULT_MAX_HEAD_BYTES");
|
|
57
|
+
/** Fields in one section. */
|
|
58
|
+
export const DEFAULT_MAX_FIELDS = constant("DEFAULT_MAX_FIELDS");
|
|
59
|
+
/** The largest HTTP/1.1 chunk-size line. */
|
|
60
|
+
export const DEFAULT_MAX_CHUNK_LINE = constant("DEFAULT_MAX_CHUNK_LINE");
|
|
61
|
+
/** The largest HTTP/2 frame payload: the protocol's default and minimum. */
|
|
62
|
+
export const DEFAULT_MAX_FRAME_SIZE = constant("DEFAULT_MAX_FRAME_SIZE");
|
|
63
|
+
|
|
64
|
+
/** The version of the native library this package opened, which is the
|
|
65
|
+
* package's own (the loader refuses a library of another version). */
|
|
66
|
+
export function version() {
|
|
67
|
+
return native.version();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The absolute path of the native library this package opened: the
|
|
71
|
+
* libweida_full of weida-native-full when that is installed at this
|
|
72
|
+
* package's version (and then the same file `weida` opened), else the
|
|
73
|
+
* libweida_http the package carries. */
|
|
74
|
+
export function libraryPath() {
|
|
75
|
+
return LIBRARY_PATH;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The description of a status code, either sign; "unknown error" for one
|
|
79
|
+
* libweida_http does not define. */
|
|
80
|
+
export function strerror(code) {
|
|
81
|
+
return native.strerror(code);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The HttpError of the library code `name` that this package detects
|
|
85
|
+
* itself, as the library would report it. */
|
|
86
|
+
function failure(name, message, condition = null) {
|
|
87
|
+
return native.errorWith(constant(name), message, condition, null, null, null);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The options object of a call: a plain object, so that Fields or a Map
|
|
91
|
+
* handed where the options go is refused rather than read as no options. */
|
|
92
|
+
function callOptions(value, known, what) {
|
|
93
|
+
if (value != null && typeof value === "object") {
|
|
94
|
+
const proto = Object.getPrototypeOf(value);
|
|
95
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
96
|
+
throw new TypeError(`the options of ${what} are a plain object: { ${known.join(", ")} }`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return optionsOf(value, known, what);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ---- methods, statuses, versions ----
|
|
103
|
+
|
|
104
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Request methods: a method is a token (RFC 9110 section 9.1),
|
|
108
|
+
* case-sensitive, and a plain string wherever one is taken. The nine of RFC
|
|
109
|
+
* 9110 are named here; any other token is a method too. `CONNECT` is a
|
|
110
|
+
* method and a client refuses to send it (kind "Unsupported").
|
|
111
|
+
* `Method.check(token)` returns the token or throws kind "EncodeError", as
|
|
112
|
+
* the library refuses one.
|
|
113
|
+
*/
|
|
114
|
+
export const Method = Object.freeze({
|
|
115
|
+
GET: "GET",
|
|
116
|
+
HEAD: "HEAD",
|
|
117
|
+
POST: "POST",
|
|
118
|
+
PUT: "PUT",
|
|
119
|
+
DELETE: "DELETE",
|
|
120
|
+
OPTIONS: "OPTIONS",
|
|
121
|
+
PATCH: "PATCH",
|
|
122
|
+
TRACE: "TRACE",
|
|
123
|
+
CONNECT: "CONNECT",
|
|
124
|
+
check(token) {
|
|
125
|
+
if (typeof token !== "string") {
|
|
126
|
+
throw new TypeError(`a method is a string, not ${describe(token)}`);
|
|
127
|
+
}
|
|
128
|
+
if (!TOKEN.test(token)) {
|
|
129
|
+
throw failure("EENCODE", "method is not a token");
|
|
130
|
+
}
|
|
131
|
+
return token;
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
/** A status as a checked number: an integer from 100 to 999. */
|
|
136
|
+
function statusCode(code) {
|
|
137
|
+
if (typeof code !== "number" || !Number.isInteger(code)) {
|
|
138
|
+
throw new TypeError(`a status is an integer, not ${describe(code)}`);
|
|
139
|
+
}
|
|
140
|
+
if (code < 100 || code > 999) {
|
|
141
|
+
throw failure("EPROTOCOL", `status ${code} is not three digits`);
|
|
142
|
+
}
|
|
143
|
+
return code;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Response statuses: a status is three digits, 100 to 999, and a plain
|
|
148
|
+
* number wherever one is taken (`response.status`). Six are named here; any
|
|
149
|
+
* other code is a status too. `Status.check(code)` returns the code or
|
|
150
|
+
* throws kind "ProtocolError", as the library refuses one; the three
|
|
151
|
+
* classifications are the library's.
|
|
152
|
+
*/
|
|
153
|
+
export const Status = Object.freeze({
|
|
154
|
+
OK: constant("STATUS_OK"),
|
|
155
|
+
NO_CONTENT: constant("STATUS_NO_CONTENT"),
|
|
156
|
+
BAD_REQUEST: constant("STATUS_BAD_REQUEST"),
|
|
157
|
+
NOT_FOUND: constant("STATUS_NOT_FOUND"),
|
|
158
|
+
INTERNAL_SERVER_ERROR: constant("STATUS_INTERNAL_SERVER_ERROR"),
|
|
159
|
+
NOT_IMPLEMENTED: constant("STATUS_NOT_IMPLEMENTED"),
|
|
160
|
+
check: statusCode,
|
|
161
|
+
/** 1xx. */
|
|
162
|
+
isInformational(code) {
|
|
163
|
+
return native.statusIsInformational(statusCode(code));
|
|
164
|
+
},
|
|
165
|
+
/** 2xx. */
|
|
166
|
+
isSuccess(code) {
|
|
167
|
+
return native.statusIsSuccess(statusCode(code));
|
|
168
|
+
},
|
|
169
|
+
/** 3xx. */
|
|
170
|
+
isRedirection(code) {
|
|
171
|
+
return native.statusIsRedirection(statusCode(code));
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
/** The HTTP version an exchange used, spelled as the Python package (and
|
|
176
|
+
* httpx) spells it. */
|
|
177
|
+
export const Version = Object.freeze({ HTTP11: "HTTP/1.1", HTTP2: "HTTP/2", HTTP3: "HTTP/3" });
|
|
178
|
+
|
|
179
|
+
const VERSIONS = new Map([
|
|
180
|
+
[constant("VERSION_HTTP11"), Version.HTTP11],
|
|
181
|
+
[constant("VERSION_HTTP2"), Version.HTTP2],
|
|
182
|
+
[constant("VERSION_HTTP3"), Version.HTTP3],
|
|
183
|
+
]);
|
|
184
|
+
|
|
185
|
+
/** Which HTTP version a client speaks: `"auto"` negotiates by ALPN (HTTP/2
|
|
186
|
+
* over TLS where the server offers it, HTTP/1.1 otherwise). */
|
|
187
|
+
export const Protocol = Object.freeze({ AUTO: "auto", HTTP1: "http1", HTTP2: "http2", HTTP3: "http3" });
|
|
188
|
+
|
|
189
|
+
const PROTOCOLS = new Map([
|
|
190
|
+
[Protocol.AUTO, constant("PROTOCOL_AUTO")],
|
|
191
|
+
[Protocol.HTTP1, constant("PROTOCOL_HTTP1")],
|
|
192
|
+
[Protocol.HTTP2, constant("PROTOCOL_HTTP2")],
|
|
193
|
+
[Protocol.HTTP3, constant("PROTOCOL_HTTP3")],
|
|
194
|
+
]);
|
|
195
|
+
|
|
196
|
+
/** What a server asks of a client's certificate. */
|
|
197
|
+
export const ClientAuth = Object.freeze({ NONE: "none", OPTIONAL: "optional", REQUIRED: "required" });
|
|
198
|
+
|
|
199
|
+
const CLIENT_AUTHS = new Map([
|
|
200
|
+
[ClientAuth.NONE, constant("CLIENT_AUTH_NONE")],
|
|
201
|
+
[ClientAuth.OPTIONAL, constant("CLIENT_AUTH_OPTIONAL")],
|
|
202
|
+
[ClientAuth.REQUIRED, constant("CLIENT_AUTH_REQUIRED")],
|
|
203
|
+
]);
|
|
204
|
+
|
|
205
|
+
/** One of the string values of `enumeration`, named `name`. */
|
|
206
|
+
function oneOf(name, value, values) {
|
|
207
|
+
if (typeof value !== "string") {
|
|
208
|
+
throw new TypeError(`${name} is one of ${[...values.keys()].join(", ")}, not ${describe(value)}`);
|
|
209
|
+
}
|
|
210
|
+
if (!values.has(value)) {
|
|
211
|
+
throw new RangeError(`${name} is one of ${[...values.keys()].join(", ")}, not ${JSON.stringify(value)}`);
|
|
212
|
+
}
|
|
213
|
+
return value;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function schemeOf(code) {
|
|
217
|
+
return code === constant("SCHEME_HTTPS") ? "https" : "http";
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// ---- fields ----
|
|
221
|
+
|
|
222
|
+
/** A field value as octets: bytes as they are (copied), a string as
|
|
223
|
+
* ISO-8859-1, which is what RFC 9110 section 5.5 says a value's characters
|
|
224
|
+
* are. */
|
|
225
|
+
function valueOctets(value) {
|
|
226
|
+
if (typeof value === "string") {
|
|
227
|
+
const out = new Uint8Array(value.length);
|
|
228
|
+
for (let i = 0; i < value.length; i++) {
|
|
229
|
+
const c = value.charCodeAt(i);
|
|
230
|
+
if (c > 0xff) {
|
|
231
|
+
throw new RangeError("a field value holds characters outside ISO-8859-1; pass bytes");
|
|
232
|
+
}
|
|
233
|
+
out[i] = c;
|
|
234
|
+
}
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
if (isBytes(value)) {
|
|
238
|
+
return bytes("value", value).slice();
|
|
239
|
+
}
|
|
240
|
+
throw new TypeError(`a field value is a string or bytes, not ${describe(value)}`);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Octets as the ISO-8859-1 string they are. */
|
|
244
|
+
function latin1(octets) {
|
|
245
|
+
let out = "";
|
|
246
|
+
for (let i = 0; i < octets.length; i += 0x2000) {
|
|
247
|
+
out += String.fromCharCode.apply(null, octets.subarray(i, i + 0x2000));
|
|
248
|
+
}
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The octets of `value` after the library judged `name` and `value` (kind
|
|
253
|
+
* "EncodeError" for a name that is not a token or a value the wire cannot
|
|
254
|
+
* carry), on a scratch list. */
|
|
255
|
+
function validated(name, value) {
|
|
256
|
+
text("name", name);
|
|
257
|
+
const octets = valueOctets(value);
|
|
258
|
+
withBuilt(
|
|
259
|
+
() => native.fieldsNew(),
|
|
260
|
+
null,
|
|
261
|
+
(h) => native.fieldsAppend(h, name, octets),
|
|
262
|
+
);
|
|
263
|
+
return octets;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** A name as the lookups compare it. */
|
|
267
|
+
function key(name) {
|
|
268
|
+
return text("name", name).toLowerCase();
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
let received;
|
|
272
|
+
let withNative;
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* The fields of an HTTP message, in order, names case-insensitive: the
|
|
276
|
+
* `weida-http` `Fields`, with the lookups of the Python package (and
|
|
277
|
+
* `http.client`, `httpx`). Unlike WHATWG `Headers` it keeps every field as
|
|
278
|
+
* it came, in order, a repeated name as many fields, never joined.
|
|
279
|
+
*
|
|
280
|
+
* `new Fields()` is empty; `new Fields({ accept: "*\/*" })` and
|
|
281
|
+
* `new Fields([["set-cookie", "a=1"], ["set-cookie", "b=2"]])` are filled
|
|
282
|
+
* from an object or from pairs (any iterable of `[name, value]`: an array, a
|
|
283
|
+
* Map, a `Headers`, other Fields). Names are kept lowercased. A value is a
|
|
284
|
+
* string (ISO-8859-1) or bytes; reading gives a string, `raw()` the octets.
|
|
285
|
+
* `add` and `set` refuse, at the line that wrote them, what the wire cannot
|
|
286
|
+
* carry (kind "EncodeError"). `add(name, value, { sensitive: true })` marks
|
|
287
|
+
* a credential: it is never indexed by HTTP/2 or HTTP/3 header compression
|
|
288
|
+
* and prints as `<redacted>`.
|
|
289
|
+
*/
|
|
290
|
+
export class Fields {
|
|
291
|
+
/** `[name, octets, sensitive]` per field. */
|
|
292
|
+
#entries = [];
|
|
293
|
+
|
|
294
|
+
static {
|
|
295
|
+
received = (pairs) => {
|
|
296
|
+
const fields = new Fields();
|
|
297
|
+
fields.#entries = pairs.map(([name, value]) => [name, value, false]);
|
|
298
|
+
return fields;
|
|
299
|
+
};
|
|
300
|
+
withNative = (fields, use) => {
|
|
301
|
+
if (fields === null) {
|
|
302
|
+
return use(null);
|
|
303
|
+
}
|
|
304
|
+
const handle = native.fieldsNew();
|
|
305
|
+
try {
|
|
306
|
+
for (const [name, value, sensitive] of fields.#entries) {
|
|
307
|
+
if (sensitive) {
|
|
308
|
+
native.fieldsAppendSensitive(handle, name, value);
|
|
309
|
+
} else {
|
|
310
|
+
native.fieldsAppend(handle, name, value);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return use(handle);
|
|
314
|
+
} finally {
|
|
315
|
+
native.drop(handle);
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
constructor(items = null) {
|
|
321
|
+
if (items == null) {
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (items instanceof Fields) {
|
|
325
|
+
this.#entries = items.#entries.slice();
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const shape = "fields are an object or an iterable of [name, value] pairs";
|
|
329
|
+
if (typeof items === "string" || typeof items !== "object") {
|
|
330
|
+
throw new TypeError(shape);
|
|
331
|
+
}
|
|
332
|
+
const pairs = typeof items[Symbol.iterator] === "function" ? items : Object.entries(items);
|
|
333
|
+
for (const pair of pairs) {
|
|
334
|
+
if (!Array.isArray(pair) || pair.length !== 2) {
|
|
335
|
+
throw new TypeError(shape);
|
|
336
|
+
}
|
|
337
|
+
this.add(pair[0], pair[1]);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Adds a field after the others. */
|
|
342
|
+
add(name, value, { sensitive = false } = {}) {
|
|
343
|
+
const octets = validated(name, value);
|
|
344
|
+
this.#entries.push([name.toLowerCase(), octets, Boolean(sensitive)]);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Replaces every field named `name` with one holding `value`. */
|
|
348
|
+
set(name, value) {
|
|
349
|
+
const octets = validated(name, value);
|
|
350
|
+
const lower = name.toLowerCase();
|
|
351
|
+
this.#entries = this.#entries.filter((entry) => entry[0] !== lower);
|
|
352
|
+
this.#entries.push([lower, octets, false]);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Removes every field named `name`; whether there was one. */
|
|
356
|
+
remove(name) {
|
|
357
|
+
const lower = key(name);
|
|
358
|
+
const kept = this.#entries.filter((entry) => entry[0] !== lower);
|
|
359
|
+
const removed = kept.length !== this.#entries.length;
|
|
360
|
+
this.#entries = kept;
|
|
361
|
+
return removed;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The first value of `name`, or `fallback` (null). */
|
|
365
|
+
get(name, fallback = null) {
|
|
366
|
+
const lower = key(name);
|
|
367
|
+
const entry = this.#entries.find((e) => e[0] === lower);
|
|
368
|
+
return entry === undefined ? fallback : latin1(entry[1]);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Every value of `name`, in order. */
|
|
372
|
+
getAll(name) {
|
|
373
|
+
const lower = key(name);
|
|
374
|
+
return this.#entries.filter((e) => e[0] === lower).map((e) => latin1(e[1]));
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Whether a field named `name` is there. */
|
|
378
|
+
has(name) {
|
|
379
|
+
const lower = key(name);
|
|
380
|
+
return this.#entries.some((e) => e[0] === lower);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** The number of fields, repeats counted. */
|
|
384
|
+
get size() {
|
|
385
|
+
return this.#entries.length;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Every field as `[name, octets]`, in order, the octets a copy. */
|
|
389
|
+
raw() {
|
|
390
|
+
return this.#entries.map(([name, value]) => [name, value.slice()]);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** An independent copy. */
|
|
394
|
+
copy() {
|
|
395
|
+
return new Fields(this);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Whether `other` holds the same fields in the same order (names and
|
|
399
|
+
* octets; whether a value is sensitive is not compared). */
|
|
400
|
+
equals(other) {
|
|
401
|
+
if (!(other instanceof Fields) || other.#entries.length !== this.#entries.length) {
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
return this.#entries.every(([name, value], i) => {
|
|
405
|
+
const [otherName, otherValue] = other.#entries[i];
|
|
406
|
+
return name === otherName && value.length === otherValue.length && value.every((b, j) => b === otherValue[j]);
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** `[name, value]` per field, in order, the value as a string. */
|
|
411
|
+
*[Symbol.iterator]() {
|
|
412
|
+
for (const [name, value] of this.#entries) {
|
|
413
|
+
yield [name, latin1(value)];
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** The fields as text, a sensitive value as `<redacted>`. */
|
|
418
|
+
toString() {
|
|
419
|
+
const shown = this.#entries.map(([name, value, sensitive]) => [name, sensitive ? "<redacted>" : latin1(value)]);
|
|
420
|
+
return `Fields(${JSON.stringify(shown)})`;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
424
|
+
return this.toString();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
[Symbol.for("Deno.customInspect")]() {
|
|
428
|
+
return this.toString();
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** `value` as Fields for a `headers` or `trailers` option: null stays
|
|
433
|
+
* null, Fields are themselves, an object or pairs are converted. */
|
|
434
|
+
function fieldsOf(name, value) {
|
|
435
|
+
if (value == null) {
|
|
436
|
+
return null;
|
|
437
|
+
}
|
|
438
|
+
if (value instanceof Fields) {
|
|
439
|
+
return value;
|
|
440
|
+
}
|
|
441
|
+
try {
|
|
442
|
+
return new Fields(value);
|
|
443
|
+
} catch (error) {
|
|
444
|
+
if (error instanceof TypeError) {
|
|
445
|
+
throw new TypeError(`${name} are Fields, an object or an iterable of [name, value] pairs`);
|
|
446
|
+
}
|
|
447
|
+
throw error;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// ---- URLs and addresses ----
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* An absolute `http` or `https` URL, parsed by the library, immutable:
|
|
455
|
+
* userinfo is refused, a fragment dropped, every octet must be visible
|
|
456
|
+
* ASCII. A bad one is kind "InvalidUrl" naming the rule it broke. `scheme`
|
|
457
|
+
* is `"http"` or `"https"`, `host` a name or an IP address (IPv6 without
|
|
458
|
+
* brackets), `port` the URL's or the scheme's default, `pathAndQuery` starts
|
|
459
|
+
* with `/`, and `authority` is what a request sends as `host` or
|
|
460
|
+
* `:authority`: the host and, when it is not the scheme's default, the port.
|
|
461
|
+
*/
|
|
462
|
+
export class Url {
|
|
463
|
+
constructor(input) {
|
|
464
|
+
const parsed = native.urlParse(text("url", input));
|
|
465
|
+
this.scheme = schemeOf(parsed.scheme);
|
|
466
|
+
this.host = parsed.host;
|
|
467
|
+
this.port = parsed.port;
|
|
468
|
+
this.pathAndQuery = parsed.pathAndQuery;
|
|
469
|
+
this.authority = parsed.authority;
|
|
470
|
+
Object.freeze(this);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** The same as the constructor, named as the Rust `Url::parse`. */
|
|
474
|
+
static parse(input) {
|
|
475
|
+
return new Url(input);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
toString() {
|
|
479
|
+
return `${this.scheme}://${this.authority}${this.pathAndQuery}`;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
toJSON() {
|
|
483
|
+
return this.toString();
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Whether `other` is a Url of the same text. */
|
|
487
|
+
equals(other) {
|
|
488
|
+
return other instanceof Url && other.toString() === this.toString();
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** A URL argument as the text the ABI takes: a string, a Url, or a WHATWG
|
|
493
|
+
* URL (its `href`). */
|
|
494
|
+
function urlText(url) {
|
|
495
|
+
if (typeof url === "string") {
|
|
496
|
+
return text("url", url);
|
|
497
|
+
}
|
|
498
|
+
if (url instanceof Url) {
|
|
499
|
+
return url.toString();
|
|
500
|
+
}
|
|
501
|
+
if (url instanceof URL) {
|
|
502
|
+
return url.href;
|
|
503
|
+
}
|
|
504
|
+
throw new TypeError(`url is a string, a Url or a URL, not ${describe(url)}`);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Where a listener bound, immutable: `host` (an IP address, IPv6 without
|
|
509
|
+
* brackets) and `port` (the one the OS picked for port 0). A bind takes one
|
|
510
|
+
* as its address too, as it takes `"ip:port"` text.
|
|
511
|
+
*/
|
|
512
|
+
export class Address {
|
|
513
|
+
constructor(host, port) {
|
|
514
|
+
this.host = text("host", host);
|
|
515
|
+
this.port = integer("port", port, U16);
|
|
516
|
+
Object.freeze(this);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** The Address of `ip:port` or `[v6]:port` text. */
|
|
520
|
+
static parse(input) {
|
|
521
|
+
const at = text("address", input).lastIndexOf(":");
|
|
522
|
+
if (at < 0) {
|
|
523
|
+
throw new RangeError(`${JSON.stringify(input)} is not ip:port`);
|
|
524
|
+
}
|
|
525
|
+
let host = input.slice(0, at);
|
|
526
|
+
if (host.startsWith("[") && host.endsWith("]")) {
|
|
527
|
+
host = host.slice(1, -1);
|
|
528
|
+
}
|
|
529
|
+
const port = Number(input.slice(at + 1));
|
|
530
|
+
return new Address(host, Number.isInteger(port) ? port : Number.NaN);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** `ip:port`, an IPv6 host in brackets: the text a bind takes. */
|
|
534
|
+
toString() {
|
|
535
|
+
return this.host.includes(":") ? `[${this.host}]:${this.port}` : `${this.host}:${this.port}`;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
toJSON() {
|
|
539
|
+
return this.toString();
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** A bind address as the `ip:port` text the ABI takes. */
|
|
544
|
+
function addressText(address) {
|
|
545
|
+
if (typeof address === "string") {
|
|
546
|
+
return text("address", address);
|
|
547
|
+
}
|
|
548
|
+
if (address instanceof Address) {
|
|
549
|
+
return address.toString();
|
|
550
|
+
}
|
|
551
|
+
const shape = "address is 'ip:port' text or an Address ({ host, port })";
|
|
552
|
+
if (address === null || typeof address !== "object") {
|
|
553
|
+
throw new TypeError(shape);
|
|
554
|
+
}
|
|
555
|
+
const { host, port } = address;
|
|
556
|
+
if (typeof host !== "string" || typeof port !== "number" || !Number.isInteger(port)) {
|
|
557
|
+
throw new TypeError(shape);
|
|
558
|
+
}
|
|
559
|
+
return new Address(host, port).toString();
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** The Address a bind op reported. */
|
|
563
|
+
function bound(raw) {
|
|
564
|
+
return raw.address === null ? new Address("", raw.port) : new Address(Address.parse(raw.address).host, raw.port);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// ---- limits, TLS and options ----
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* What this side accepts from its peer, immutable: bounds that hold back a
|
|
571
|
+
* peer that sends too much. Every bound is the recipient's own; there is no
|
|
572
|
+
* way to switch one off. null is the library's default (`DEFAULT_MAX_*`).
|
|
573
|
+
* `maxHeadBytes`: the largest head, field section or trailer section, in
|
|
574
|
+
* bytes. `maxFields`: fields in one section. `maxChunkLine`: the largest
|
|
575
|
+
* HTTP/1.1 chunk-size line. `maxFrameSize`: the largest HTTP/2 frame
|
|
576
|
+
* payload, 16 384 to 16 777 215 (checked when the options are built).
|
|
577
|
+
*/
|
|
578
|
+
export class Limits {
|
|
579
|
+
constructor(options = {}) {
|
|
580
|
+
const o = optionsOf(options, ["maxHeadBytes", "maxFields", "maxChunkLine", "maxFrameSize"], "Limits");
|
|
581
|
+
this.maxHeadBytes = optionalInteger("maxHeadBytes", o.maxHeadBytes, U64);
|
|
582
|
+
this.maxFields = optionalInteger("maxFields", o.maxFields, U64);
|
|
583
|
+
this.maxChunkLine = optionalInteger("maxChunkLine", o.maxChunkLine, U64);
|
|
584
|
+
this.maxFrameSize = optionalInteger("maxFrameSize", o.maxFrameSize, U32);
|
|
585
|
+
Object.freeze(this);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function buildLimits(l) {
|
|
590
|
+
return configured(native.limitsNew(), (h) => {
|
|
591
|
+
for (const [value, setter] of [
|
|
592
|
+
[l.maxHeadBytes, native.limitsSetMaxHeadBytes],
|
|
593
|
+
[l.maxFields, native.limitsSetMaxFields],
|
|
594
|
+
[l.maxChunkLine, native.limitsSetMaxChunkLine],
|
|
595
|
+
[l.maxFrameSize, native.limitsSetMaxFrameSize],
|
|
596
|
+
]) {
|
|
597
|
+
if (value !== null) {
|
|
598
|
+
setter(h, value);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** An identity `{ cert, key }`, checked: `cert` PEM bytes, an
|
|
605
|
+
* X509Certificate or an array of them, `key` PEM bytes or a private
|
|
606
|
+
* KeyObject. */
|
|
607
|
+
function identityOf(value) {
|
|
608
|
+
if (value === null || typeof value !== "object" || isBytes(value) || Array.isArray(value)) {
|
|
609
|
+
throw new TypeError("identity is { cert, key }");
|
|
610
|
+
}
|
|
611
|
+
const { cert, key: privateKey } = optionsOf(value, ["cert", "key"], "identity");
|
|
612
|
+
certPem(cert);
|
|
613
|
+
keyPem(privateKey);
|
|
614
|
+
return Object.freeze({ cert, key: privateKey });
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** Trust anchors as a frozen array: one anchor or an array of them. */
|
|
618
|
+
function anchorsOf(name, value) {
|
|
619
|
+
const anchors = value == null ? [] : Array.isArray(value) ? value : [value];
|
|
620
|
+
for (const anchor of anchors) {
|
|
621
|
+
if (!isAnchor(anchor)) {
|
|
622
|
+
throw new TypeError(`${name} is PEM bytes, an X509Certificate, a path, or an array of those`);
|
|
623
|
+
}
|
|
624
|
+
if (typeof anchor === "string") {
|
|
625
|
+
text(name, anchor);
|
|
626
|
+
} else if (anchor instanceof URL) {
|
|
627
|
+
fileURLToPath(anchor);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return Object.freeze([...anchors]);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* The client side of TLS, immutable: what a server's certificate must
|
|
635
|
+
* chain to, an optional client certificate, and whether to verify at all.
|
|
636
|
+
* `ca` is PEM bytes, an X509Certificate, the path of a PEM file (a string or
|
|
637
|
+
* a file: URL, read when the options are built, which is at construction of
|
|
638
|
+
* the ClientOptions), or an array of those. `identity` is an optional client
|
|
639
|
+
* certificate `{ cert, key }`. The name the certificate must carry is the
|
|
640
|
+
* host of each URL: there is no `serverName`. `verify: false` accepts any
|
|
641
|
+
* certificate: it exists for a test against a throwaway certificate.
|
|
642
|
+
* Verifying with no `ca` is refused where the options are built (kind
|
|
643
|
+
* "Tls"), because it could only fail every handshake.
|
|
644
|
+
*/
|
|
645
|
+
export class ClientTls {
|
|
646
|
+
constructor(options = {}) {
|
|
647
|
+
const o = optionsOf(options, ["ca", "identity", "verify"], "ClientTls");
|
|
648
|
+
this.ca = anchorsOf("ca", o.ca);
|
|
649
|
+
this.identity = o.identity == null ? null : identityOf(o.identity);
|
|
650
|
+
this.verify = o.verify === undefined ? true : Boolean(o.verify);
|
|
651
|
+
Object.freeze(this);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function buildClientTls(t) {
|
|
656
|
+
return configured(native.tlsClientNew(), (h) => {
|
|
657
|
+
for (const anchor of t.ca) {
|
|
658
|
+
if (typeof anchor === "string") {
|
|
659
|
+
native.tlsClientAddAnchorsPath(h, anchor);
|
|
660
|
+
} else if (anchor instanceof URL) {
|
|
661
|
+
native.tlsClientAddAnchorsPath(h, fileURLToPath(anchor));
|
|
662
|
+
} else {
|
|
663
|
+
native.tlsClientAddAnchorsPem(h, certPem(anchor));
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
if (t.identity !== null) {
|
|
667
|
+
native.tlsClientSetIdentityPem(h, certPem(t.identity.cert), keyPem(t.identity.key));
|
|
668
|
+
}
|
|
669
|
+
native.tlsClientSetVerify(h, t.verify ? constant("TLS_VERIFY_PEER") : constant("TLS_VERIFY_NONE"));
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* The server side of TLS, immutable: the certificate it presents, and what
|
|
675
|
+
* it asks of a client's. `identity` is `{ cert, key }`: the chain, leaf
|
|
676
|
+
* first, as PEM bytes, an X509Certificate or an array of them, and its key
|
|
677
|
+
* as PEM bytes or a private KeyObject. `clientCa` is what a client's
|
|
678
|
+
* certificate must chain to (PEM bytes, an X509Certificate, the path of a
|
|
679
|
+
* PEM file, read here, or an array of those) and `clientAuth` a
|
|
680
|
+
* `ClientAuth`: `"none"` (the default) asks for no certificate,
|
|
681
|
+
* `"optional"` verifies one when presented, `"required"` requires one; the
|
|
682
|
+
* last two need a `clientCa`.
|
|
683
|
+
*/
|
|
684
|
+
export class ServerTls {
|
|
685
|
+
constructor(identity, options = {}) {
|
|
686
|
+
const o = optionsOf(options, ["clientCa", "clientAuth"], "ServerTls");
|
|
687
|
+
this.identity = identityOf(identity);
|
|
688
|
+
this.clientCa = Object.freeze(
|
|
689
|
+
anchorsOf("clientCa", o.clientCa).map((anchor) =>
|
|
690
|
+
typeof anchor === "string" || anchor instanceof URL
|
|
691
|
+
? new Uint8Array(readFileSync(anchor instanceof URL ? fileURLToPath(anchor) : anchor))
|
|
692
|
+
: certPem(anchor),
|
|
693
|
+
),
|
|
694
|
+
);
|
|
695
|
+
this.clientAuth = oneOf("clientAuth", o.clientAuth ?? ClientAuth.NONE, CLIENT_AUTHS);
|
|
696
|
+
Object.freeze(this);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function buildServerTls(t) {
|
|
701
|
+
return configured(native.tlsServerNew(), (h) => {
|
|
702
|
+
native.tlsServerSetIdentityPem(h, certPem(t.identity.cert), keyPem(t.identity.key));
|
|
703
|
+
for (const anchor of t.clientCa) {
|
|
704
|
+
native.tlsServerAddClientAnchorsPem(h, anchor);
|
|
705
|
+
}
|
|
706
|
+
native.tlsServerSetClientAuth(h, CLIENT_AUTHS.get(t.clientAuth));
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function limitsOf(value) {
|
|
711
|
+
if (value != null && !(value instanceof Limits)) {
|
|
712
|
+
throw new TypeError("limits is a Limits");
|
|
713
|
+
}
|
|
714
|
+
return value ?? null;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const CLIENT_OPTIONS = [
|
|
718
|
+
"tls",
|
|
719
|
+
"protocol",
|
|
720
|
+
"connectTimeoutMs",
|
|
721
|
+
"idleTimeoutMs",
|
|
722
|
+
"maxIdlePerOrigin",
|
|
723
|
+
"maxResolvedAddresses",
|
|
724
|
+
"streamWindow",
|
|
725
|
+
"connectionWindow",
|
|
726
|
+
"limits",
|
|
727
|
+
];
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* How a client connects and what it accepts, immutable. null for a setting
|
|
731
|
+
* is the library's default (a 10 s connect timeout, 90 s idle timeout, 4
|
|
732
|
+
* idle connections per origin, 8 addresses, a 1 MiB stream window and a 4
|
|
733
|
+
* MiB connection window, `"auto"`, no TLS). `tls` is a ClientTls; without
|
|
734
|
+
* it an `https` URL is refused (kind "Configuration"). `connectTimeoutMs`
|
|
735
|
+
* covers the name lookup, the TCP connect and the TLS or QUIC handshake
|
|
736
|
+
* together; there is no request timeout (the caller's is a `signal`).
|
|
737
|
+
* `idleTimeoutMs` is how long an idle HTTP/1.1 connection is kept for
|
|
738
|
+
* reuse.
|
|
739
|
+
*
|
|
740
|
+
* Every refusal happens at construction: the library validates the
|
|
741
|
+
* options, a zero count or a window outside 1 to 2^31 - 1 is kind
|
|
742
|
+
* "Configuration" naming the option, and TLS terms it cannot use are kind
|
|
743
|
+
* "Tls".
|
|
744
|
+
*/
|
|
745
|
+
export class ClientOptions {
|
|
746
|
+
constructor(options = {}) {
|
|
747
|
+
const o = optionsOf(options, CLIENT_OPTIONS, "ClientOptions");
|
|
748
|
+
if (o.tls != null && !(o.tls instanceof ClientTls)) {
|
|
749
|
+
throw new TypeError("tls is a ClientTls");
|
|
750
|
+
}
|
|
751
|
+
this.tls = o.tls ?? null;
|
|
752
|
+
this.protocol = o.protocol == null ? null : oneOf("protocol", o.protocol, PROTOCOLS);
|
|
753
|
+
this.connectTimeoutMs = duration("connectTimeoutMs", o.connectTimeoutMs);
|
|
754
|
+
this.idleTimeoutMs = duration("idleTimeoutMs", o.idleTimeoutMs);
|
|
755
|
+
this.maxIdlePerOrigin = optionalInteger("maxIdlePerOrigin", o.maxIdlePerOrigin, U64);
|
|
756
|
+
this.maxResolvedAddresses = optionalInteger("maxResolvedAddresses", o.maxResolvedAddresses, U64);
|
|
757
|
+
this.streamWindow = optionalInteger("streamWindow", o.streamWindow, U32);
|
|
758
|
+
this.connectionWindow = optionalInteger("connectionWindow", o.connectionWindow, U32);
|
|
759
|
+
this.limits = limitsOf(o.limits);
|
|
760
|
+
Object.freeze(this);
|
|
761
|
+
withBuilt(buildClientOptions, this, (h) => native.clientOptionsValidate(h));
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function buildClientOptions(o) {
|
|
766
|
+
return configured(native.clientOptionsNew(), (h) => {
|
|
767
|
+
if (o.tls !== null) {
|
|
768
|
+
withBuilt(buildClientTls, o.tls, (t) => native.clientOptionsSetTls(h, t));
|
|
769
|
+
}
|
|
770
|
+
if (o.protocol !== null) {
|
|
771
|
+
native.clientOptionsSetProtocol(h, PROTOCOLS.get(o.protocol));
|
|
772
|
+
}
|
|
773
|
+
if (o.connectTimeoutMs !== null) {
|
|
774
|
+
native.clientOptionsSetConnectTimeoutMs(h, millis("connectTimeoutMs", o.connectTimeoutMs));
|
|
775
|
+
}
|
|
776
|
+
if (o.idleTimeoutMs !== null) {
|
|
777
|
+
native.clientOptionsSetIdleTimeoutMs(h, millis("idleTimeoutMs", o.idleTimeoutMs));
|
|
778
|
+
}
|
|
779
|
+
for (const [value, setter] of [
|
|
780
|
+
[o.maxIdlePerOrigin, native.clientOptionsSetMaxIdlePerOrigin],
|
|
781
|
+
[o.maxResolvedAddresses, native.clientOptionsSetMaxResolvedAddresses],
|
|
782
|
+
[o.streamWindow, native.clientOptionsSetStreamWindow],
|
|
783
|
+
[o.connectionWindow, native.clientOptionsSetConnectionWindow],
|
|
784
|
+
]) {
|
|
785
|
+
if (value !== null) {
|
|
786
|
+
setter(h, value);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
if (o.limits !== null) {
|
|
790
|
+
withBuilt(buildLimits, o.limits, (l) => native.clientOptionsSetLimits(h, l));
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const SERVER_OPTIONS = [
|
|
796
|
+
"maxConnections",
|
|
797
|
+
"acceptQueue",
|
|
798
|
+
"maxConcurrentStreams",
|
|
799
|
+
"headerTimeoutMs",
|
|
800
|
+
"idleTimeoutMs",
|
|
801
|
+
"closeTimeoutMs",
|
|
802
|
+
"streamWindow",
|
|
803
|
+
"connectionWindow",
|
|
804
|
+
"limits",
|
|
805
|
+
];
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* How a server serves and what it accepts, immutable. null for a setting is
|
|
809
|
+
* the library's default (1024 connections, an accept queue of 64, 100
|
|
810
|
+
* concurrent HTTP/2 streams, a 10 s header timeout, a 60 s idle timeout, a
|
|
811
|
+
* 5 s close timeout, a 1 MiB stream window and a 4 MiB connection window).
|
|
812
|
+
* `headerTimeoutMs` is how long an HTTP/1.1 head, an HTTP/2 preface, or a
|
|
813
|
+
* TLS or QUIC handshake may take; `idleTimeoutMs` how long a connection may
|
|
814
|
+
* sit idle between requests; `closeTimeoutMs` how long `Server.close` waits
|
|
815
|
+
* for exchanges in flight. Every refusal happens at construction, as in
|
|
816
|
+
* ClientOptions.
|
|
817
|
+
*/
|
|
818
|
+
export class ServerOptions {
|
|
819
|
+
constructor(options = {}) {
|
|
820
|
+
const o = optionsOf(options, SERVER_OPTIONS, "ServerOptions");
|
|
821
|
+
this.maxConnections = optionalInteger("maxConnections", o.maxConnections, U64);
|
|
822
|
+
this.acceptQueue = optionalInteger("acceptQueue", o.acceptQueue, U64);
|
|
823
|
+
this.maxConcurrentStreams = optionalInteger("maxConcurrentStreams", o.maxConcurrentStreams, U32);
|
|
824
|
+
this.headerTimeoutMs = duration("headerTimeoutMs", o.headerTimeoutMs);
|
|
825
|
+
this.idleTimeoutMs = duration("idleTimeoutMs", o.idleTimeoutMs);
|
|
826
|
+
this.closeTimeoutMs = duration("closeTimeoutMs", o.closeTimeoutMs);
|
|
827
|
+
this.streamWindow = optionalInteger("streamWindow", o.streamWindow, U32);
|
|
828
|
+
this.connectionWindow = optionalInteger("connectionWindow", o.connectionWindow, U32);
|
|
829
|
+
this.limits = limitsOf(o.limits);
|
|
830
|
+
Object.freeze(this);
|
|
831
|
+
withBuilt(buildServerOptions, this, (h) => native.serverOptionsValidate(h));
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
function buildServerOptions(o) {
|
|
836
|
+
return configured(native.serverOptionsNew(), (h) => {
|
|
837
|
+
for (const [value, setter] of [
|
|
838
|
+
[o.maxConnections, native.serverOptionsSetMaxConnections],
|
|
839
|
+
[o.acceptQueue, native.serverOptionsSetAcceptQueue],
|
|
840
|
+
[o.maxConcurrentStreams, native.serverOptionsSetMaxConcurrentStreams],
|
|
841
|
+
[o.streamWindow, native.serverOptionsSetStreamWindow],
|
|
842
|
+
[o.connectionWindow, native.serverOptionsSetConnectionWindow],
|
|
843
|
+
]) {
|
|
844
|
+
if (value !== null) {
|
|
845
|
+
setter(h, value);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
for (const [value, name, setter] of [
|
|
849
|
+
[o.headerTimeoutMs, "headerTimeoutMs", native.serverOptionsSetHeaderTimeoutMs],
|
|
850
|
+
[o.idleTimeoutMs, "idleTimeoutMs", native.serverOptionsSetIdleTimeoutMs],
|
|
851
|
+
[o.closeTimeoutMs, "closeTimeoutMs", native.serverOptionsSetCloseTimeoutMs],
|
|
852
|
+
]) {
|
|
853
|
+
if (value !== null) {
|
|
854
|
+
setter(h, millis(name, value));
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
if (o.limits !== null) {
|
|
858
|
+
withBuilt(buildLimits, o.limits, (l) => native.serverOptionsSetLimits(h, l));
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
// ---- the context ----
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* A context owning a reactor of `workerThreads` threads (one per core by
|
|
867
|
+
* default). The reactor is the library's: no JavaScript event loop drives
|
|
868
|
+
* it. It shuts down in the background once the context and every client,
|
|
869
|
+
* server and operation made from it are gone, so dropping the context first
|
|
870
|
+
* is fine. A Client or Server made without one owns a reactor of its own;
|
|
871
|
+
* pass one to several to share it.
|
|
872
|
+
*/
|
|
873
|
+
export class Context extends Handle {
|
|
874
|
+
constructor(options = {}) {
|
|
875
|
+
super();
|
|
876
|
+
const o = optionsOf(options, ["workerThreads"], "Context");
|
|
877
|
+
const threads =
|
|
878
|
+
o.workerThreads == null ? defaultThreads() : integer("workerThreads", o.workerThreads, U64, 1);
|
|
879
|
+
init(this, native.contextOwned(threads));
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** The same as the constructor, named. */
|
|
883
|
+
static owned(workerThreads = null) {
|
|
884
|
+
return new Context({ workerThreads });
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/** Always throws kind "Runtime": libweida_http owns its reactor and has no
|
|
888
|
+
* constructor that joins an ambient one. Kept so a caller that tried it
|
|
889
|
+
* learns why. */
|
|
890
|
+
static current() {
|
|
891
|
+
throw failure("ERUNTIME", "there is no ambient reactor: a Context owns its own");
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/** A second context on `other`'s reactor (the same handle: dropping
|
|
895
|
+
* either drops it). */
|
|
896
|
+
static sharing(other) {
|
|
897
|
+
return init(Object.create(Context.prototype), handleOf(other, Context));
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/** Makes `object` the owner of what `make(context handle)` returns, on
|
|
902
|
+
* `context` or, without one, on a reactor of its own: the native object
|
|
903
|
+
* holds the reactor (R13), so the context made here is dropped at once. */
|
|
904
|
+
function onContext(object, context, make) {
|
|
905
|
+
if (context != null && !(context instanceof Context)) {
|
|
906
|
+
throw new TypeError("context is a Context");
|
|
907
|
+
}
|
|
908
|
+
const own = context == null ? new Context() : null;
|
|
909
|
+
try {
|
|
910
|
+
return init(object, make((own ?? context)[HANDLE]));
|
|
911
|
+
} finally {
|
|
912
|
+
own?.drop();
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// ---- bodies ----
|
|
917
|
+
|
|
918
|
+
const BODY = Symbol("weida-http.body");
|
|
919
|
+
|
|
920
|
+
/** The body of a response or an exchange, taken on first use. */
|
|
921
|
+
function bodyOf(owner, take) {
|
|
922
|
+
if (owner[BODY] === undefined) {
|
|
923
|
+
owner[BODY] = adopt(Body, take(owner[HANDLE]));
|
|
924
|
+
}
|
|
925
|
+
return owner[BODY];
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* A body that arrives, a stream of Uint8Array chunks: `for await (const
|
|
930
|
+
* chunk of body)`, `await body.recv()`, or `await body.read(max)` for the
|
|
931
|
+
* rest of it under a cap. The stream ends when the body does, and a failure
|
|
932
|
+
* of the transport or the peer throws the HttpError of it. An aborted
|
|
933
|
+
* receive loses nothing: the next one gets the chunk. A read that fails or
|
|
934
|
+
* is aborted leaves the body unusable.
|
|
935
|
+
*/
|
|
936
|
+
export class Body extends Handle {
|
|
937
|
+
constructor() {
|
|
938
|
+
super();
|
|
939
|
+
noConstructor("Body", "Response.body or Exchange.body");
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/** The next chunk, or null once the body ended. */
|
|
943
|
+
async recv({ signal } = {}) {
|
|
944
|
+
const handle = this[HANDLE];
|
|
945
|
+
return call(
|
|
946
|
+
this,
|
|
947
|
+
() => native.bodyReaderChunk(handle),
|
|
948
|
+
() => native.bodyReaderFd(handle),
|
|
949
|
+
signal,
|
|
950
|
+
);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* The rest of the body, collected under the cap `max` bytes (a number or
|
|
955
|
+
* a BigInt); null asks for no cap by name, and leaving it out is a
|
|
956
|
+
* TypeError. A body that is, or turns out to be, longer throws kind
|
|
957
|
+
* "TooLarge" with `max` the cap, from a declared length before anything
|
|
958
|
+
* is read. The chunks already received are not part of it.
|
|
959
|
+
*/
|
|
960
|
+
async read(max, { signal } = {}) {
|
|
961
|
+
if (max === undefined) {
|
|
962
|
+
throw new TypeError("read takes a cap: a number of bytes, or null for none");
|
|
963
|
+
}
|
|
964
|
+
const cap = max === null ? U64 : integer("max", max, U64);
|
|
965
|
+
const handle = this[HANDLE];
|
|
966
|
+
try {
|
|
967
|
+
return await op(
|
|
968
|
+
this,
|
|
969
|
+
() => native.bodyReaderCollect(handle, cap),
|
|
970
|
+
native.bodyReaderCollectOpWait,
|
|
971
|
+
native.bodyReaderCollectOpFd,
|
|
972
|
+
signal,
|
|
973
|
+
);
|
|
974
|
+
} catch (error) {
|
|
975
|
+
if (error instanceof HttpError && error.kind === "TooLarge") {
|
|
976
|
+
error.max = cap;
|
|
977
|
+
}
|
|
978
|
+
throw error;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/** The length the sender declared, or null where it declared none: a
|
|
983
|
+
* number, or a BigInt past Number.MAX_SAFE_INTEGER. */
|
|
984
|
+
get contentLength() {
|
|
985
|
+
return native.bodyReaderContentLength(this[HANDLE]);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** The trailer fields once the body ended, null before that; a body that
|
|
989
|
+
* ended with none (a chunked one with an empty trailer section) has empty
|
|
990
|
+
* Fields. */
|
|
991
|
+
get trailers() {
|
|
992
|
+
const pairs = native.bodyReaderTrailers(this[HANDLE]);
|
|
993
|
+
return pairs === null ? null : received(pairs);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/** The body as a WHATWG ReadableStream of its chunks; cancelling the
|
|
997
|
+
* stream drops the body. */
|
|
998
|
+
stream() {
|
|
999
|
+
return new ReadableStream({
|
|
1000
|
+
pull: async (controller) => {
|
|
1001
|
+
const chunk = await this.recv();
|
|
1002
|
+
if (chunk === null) {
|
|
1003
|
+
controller.close();
|
|
1004
|
+
} else {
|
|
1005
|
+
controller.enqueue(chunk);
|
|
1006
|
+
}
|
|
1007
|
+
},
|
|
1008
|
+
cancel: () => {
|
|
1009
|
+
this.drop();
|
|
1010
|
+
},
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
async *[Symbol.asyncIterator]() {
|
|
1015
|
+
for (let chunk = await this.recv(); chunk !== null; chunk = await this.recv()) {
|
|
1016
|
+
yield chunk;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/** What a Response and an Exchange share: a body taken once, on first use,
|
|
1022
|
+
* and `read` and iteration over it. */
|
|
1023
|
+
class Message extends Handle {
|
|
1024
|
+
/** The declared length of the body; see `Body.contentLength`. */
|
|
1025
|
+
get contentLength() {
|
|
1026
|
+
return this.body.contentLength;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/** The trailer fields of the body; see `Body.trailers`. */
|
|
1030
|
+
get trailers() {
|
|
1031
|
+
return this.body.trailers;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/** The whole body under the cap `max`; see `Body.read`. */
|
|
1035
|
+
async read(max, options = {}) {
|
|
1036
|
+
return this.body.read(max, options);
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
[Symbol.asyncIterator]() {
|
|
1040
|
+
return this.body[Symbol.asyncIterator]();
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/** Defines the read-only fields of a head on `object`. */
|
|
1045
|
+
function head(object, fields) {
|
|
1046
|
+
for (const [name, value] of Object.entries(fields)) {
|
|
1047
|
+
Object.defineProperty(object, name, { value, enumerable: true });
|
|
1048
|
+
}
|
|
1049
|
+
return object;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// ---- the client ----
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* What a request yields: `status` (a number), `version` (a Version),
|
|
1056
|
+
* `headers` (Fields), copied out when it arrived, and the body, which is
|
|
1057
|
+
* `for await (const chunk of response)` or `await response.read(max)`.
|
|
1058
|
+
* `response.body` is the Body itself, and `contentLength` and `trailers`
|
|
1059
|
+
* are its. Dropping a response whose body was not taken drops the body,
|
|
1060
|
+
* which tells the connection the caller is not reading it.
|
|
1061
|
+
*/
|
|
1062
|
+
export class Response extends Message {
|
|
1063
|
+
constructor() {
|
|
1064
|
+
super();
|
|
1065
|
+
noConstructor("Response", "Client.request()");
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/** The body, a stream of chunks; taken on first use. */
|
|
1069
|
+
get body() {
|
|
1070
|
+
return bodyOf(this, native.responseTakeBody);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function response(handle) {
|
|
1075
|
+
return head(adopt(Response, handle), {
|
|
1076
|
+
status: native.responseStatus(handle),
|
|
1077
|
+
version: VERSIONS.get(native.responseVersion(handle)),
|
|
1078
|
+
headers: received(native.responseFields(handle)),
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/**
|
|
1083
|
+
* A request whose body the caller writes, in parts, then finishes. Writes
|
|
1084
|
+
* run in order. Dropping it unfinished abandons the request; a write or a
|
|
1085
|
+
* finish that fails or is aborted leaves the request unusable.
|
|
1086
|
+
*/
|
|
1087
|
+
export class OpenRequest extends Handle {
|
|
1088
|
+
constructor() {
|
|
1089
|
+
super();
|
|
1090
|
+
noConstructor("OpenRequest", "Client.open()");
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/** Sends `data` (bytes) as the next part of the body, resolving once it
|
|
1094
|
+
* reached the connection, which waits while the connection has no room:
|
|
1095
|
+
* the backpressure. */
|
|
1096
|
+
async write(data, { signal } = {}) {
|
|
1097
|
+
const part = bytes("data", data);
|
|
1098
|
+
const handle = this[HANDLE];
|
|
1099
|
+
await op(
|
|
1100
|
+
this,
|
|
1101
|
+
() => native.openRequestWrite(handle, part),
|
|
1102
|
+
native.openRequestWriteOpWait,
|
|
1103
|
+
native.openRequestWriteOpFd,
|
|
1104
|
+
signal,
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
/** Ends the body, with `trailers` where given, and resolves with the
|
|
1109
|
+
* response. The request is spent. */
|
|
1110
|
+
async finish(options = {}) {
|
|
1111
|
+
const o = callOptions(options, ["trailers", "signal"], "finish");
|
|
1112
|
+
const trailers = fieldsOf("trailers", o.trailers);
|
|
1113
|
+
const handle = this[HANDLE];
|
|
1114
|
+
const done = await op(
|
|
1115
|
+
this,
|
|
1116
|
+
() =>
|
|
1117
|
+
trailers === null
|
|
1118
|
+
? native.openRequestFinish(handle)
|
|
1119
|
+
: withNative(trailers, (t) => native.openRequestFinishWithTrailers(handle, t)),
|
|
1120
|
+
native.openRequestFinishOpWait,
|
|
1121
|
+
native.openRequestFinishOpFd,
|
|
1122
|
+
o.signal,
|
|
1123
|
+
);
|
|
1124
|
+
return response(done);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
/**
|
|
1129
|
+
* An HTTP client: requests to any origin over pooled connections. It
|
|
1130
|
+
* follows no redirects and stores no cookies: a 3xx is returned to the
|
|
1131
|
+
* caller. `new Client()` runs on a reactor of its own; `new Client(options,
|
|
1132
|
+
* { context })` takes ClientOptions and shares a context's reactor.
|
|
1133
|
+
*/
|
|
1134
|
+
export class Client extends Handle {
|
|
1135
|
+
constructor(options = null, how = {}) {
|
|
1136
|
+
super();
|
|
1137
|
+
if (options != null && !(options instanceof ClientOptions)) {
|
|
1138
|
+
throw new TypeError("options is a ClientOptions");
|
|
1139
|
+
}
|
|
1140
|
+
const { context } = optionsOf(how, ["context"], "Client");
|
|
1141
|
+
onContext(this, context, (ctx) =>
|
|
1142
|
+
options == null
|
|
1143
|
+
? native.clientNew(ctx, null)
|
|
1144
|
+
: withBuilt(buildClientOptions, options, (o) => native.clientNew(ctx, o)),
|
|
1145
|
+
);
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/**
|
|
1149
|
+
* Sends a request with a complete body and resolves with the response,
|
|
1150
|
+
* once its head arrived. `method` is a token (`"GET"`, `Method.POST`, any
|
|
1151
|
+
* other), `url` an absolute `http` or `https` URL (a string, a Url or a
|
|
1152
|
+
* URL), `headers` Fields, an object or `[name, value]` pairs, `body` bytes
|
|
1153
|
+
* (null: none; a string is refused).
|
|
1154
|
+
*
|
|
1155
|
+
* A 3xx or a 4xx is a response, not an error. A method that is not a
|
|
1156
|
+
* token is kind "EncodeError", a URL the client cannot request
|
|
1157
|
+
* "InvalidUrl", `https` with no TLS terms in the options "Configuration",
|
|
1158
|
+
* and a connection that cannot be made "Io" or "Timeout".
|
|
1159
|
+
*/
|
|
1160
|
+
async request(method, url, options = {}) {
|
|
1161
|
+
const o = callOptions(options, ["headers", "body", "signal"], "request");
|
|
1162
|
+
text("method", method);
|
|
1163
|
+
const target = urlText(url);
|
|
1164
|
+
const headers = fieldsOf("headers", o.headers);
|
|
1165
|
+
const body = o.body == null ? null : bytes("body", o.body);
|
|
1166
|
+
const handle = this[HANDLE];
|
|
1167
|
+
const done = await op(
|
|
1168
|
+
this,
|
|
1169
|
+
() => withNative(headers, (h) => native.clientRequest(handle, method, target, h, body)),
|
|
1170
|
+
native.clientRequestOpWait,
|
|
1171
|
+
native.clientRequestOpFd,
|
|
1172
|
+
o.signal,
|
|
1173
|
+
);
|
|
1174
|
+
return response(done);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/** Starts a request whose body the caller writes: resolves with an
|
|
1178
|
+
* OpenRequest. Without a `content-length` field the body is chunked on
|
|
1179
|
+
* HTTP/1.1. */
|
|
1180
|
+
async open(method, url, options = {}) {
|
|
1181
|
+
const o = callOptions(options, ["headers", "signal"], "open");
|
|
1182
|
+
text("method", method);
|
|
1183
|
+
const target = urlText(url);
|
|
1184
|
+
const headers = fieldsOf("headers", o.headers);
|
|
1185
|
+
const handle = this[HANDLE];
|
|
1186
|
+
const done = await op(
|
|
1187
|
+
this,
|
|
1188
|
+
() => withNative(headers, (h) => native.clientOpen(handle, method, target, h)),
|
|
1189
|
+
native.clientOpenOpWait,
|
|
1190
|
+
native.clientOpenOpFd,
|
|
1191
|
+
o.signal,
|
|
1192
|
+
);
|
|
1193
|
+
return adopt(OpenRequest, done);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// ---- the server ----
|
|
1198
|
+
|
|
1199
|
+
/**
|
|
1200
|
+
* The body of a response being sent, in parts, then finished. Its
|
|
1201
|
+
* operations run in order. Writing more than a declared `content-length`,
|
|
1202
|
+
* finishing short of it, or dropping the writer unfinished aborts the
|
|
1203
|
+
* message: on HTTP/1.1 the connection is closed, on HTTP/2 and HTTP/3 the
|
|
1204
|
+
* stream is reset, so the peer sees an incomplete message rather than a
|
|
1205
|
+
* complete wrong one.
|
|
1206
|
+
*/
|
|
1207
|
+
export class BodyWriter extends Handle {
|
|
1208
|
+
constructor() {
|
|
1209
|
+
super();
|
|
1210
|
+
noConstructor("BodyWriter", "Exchange.respondStream()");
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
/** Sends `data` (bytes) as the next part of the body, resolving once it
|
|
1214
|
+
* reached the connection (waiting while there is no room or, on HTTP/2
|
|
1215
|
+
* and HTTP/3, no flow-control credit). */
|
|
1216
|
+
async write(data, { signal } = {}) {
|
|
1217
|
+
const part = bytes("data", data);
|
|
1218
|
+
const handle = this[HANDLE];
|
|
1219
|
+
await op(
|
|
1220
|
+
this,
|
|
1221
|
+
() => native.bodyWriterWrite(handle, part),
|
|
1222
|
+
native.bodyWriterWriteOpWait,
|
|
1223
|
+
native.bodyWriterWriteOpFd,
|
|
1224
|
+
signal,
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
/** Ends the body, with `trailers` where given. The writer is spent. */
|
|
1229
|
+
async finish(options = {}) {
|
|
1230
|
+
const o = callOptions(options, ["trailers", "signal"], "finish");
|
|
1231
|
+
const trailers = fieldsOf("trailers", o.trailers);
|
|
1232
|
+
const handle = this[HANDLE];
|
|
1233
|
+
await op(
|
|
1234
|
+
this,
|
|
1235
|
+
() =>
|
|
1236
|
+
trailers === null
|
|
1237
|
+
? native.bodyWriterFinish(handle)
|
|
1238
|
+
: withNative(trailers, (t) => native.bodyWriterFinishWithTrailers(handle, t)),
|
|
1239
|
+
native.bodyWriterFinishOpWait,
|
|
1240
|
+
native.bodyWriterFinishOpFd,
|
|
1241
|
+
o.signal,
|
|
1242
|
+
);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
/** Starts `start(responder)` on the exchange's responder, taken once (kind
|
|
1247
|
+
* "Closed" the second time) and dropped at once: the op holds what it
|
|
1248
|
+
* answers with. */
|
|
1249
|
+
function responding(exchange, start) {
|
|
1250
|
+
const responder = native.exchangeTakeResponder(exchange[HANDLE]);
|
|
1251
|
+
try {
|
|
1252
|
+
return start(responder);
|
|
1253
|
+
} finally {
|
|
1254
|
+
native.drop(responder);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
/**
|
|
1259
|
+
* One request a server accepted, its head copied out when it arrived:
|
|
1260
|
+
* `method`, `scheme` (`"http"` or `"https"`), `authority`, `path` (the path
|
|
1261
|
+
* and query, starting with `/`), `version`, `peer` (the client's address as
|
|
1262
|
+
* `ip:port` text) and `headers` (no pseudo-fields, no `host`). Its body is
|
|
1263
|
+
* taken once and streams; it is answered once. Dropping an exchange that
|
|
1264
|
+
* was not answered answers `500 Internal Server Error` and, on HTTP/1.1,
|
|
1265
|
+
* closes the connection.
|
|
1266
|
+
*/
|
|
1267
|
+
export class Exchange extends Message {
|
|
1268
|
+
constructor() {
|
|
1269
|
+
super();
|
|
1270
|
+
noConstructor("Exchange", "Server.accept()");
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/** The request body, a stream of chunks; taken on first use. */
|
|
1274
|
+
get body() {
|
|
1275
|
+
return bodyOf(this, native.exchangeTakeBody);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/** Answers with a whole response: `content-length` is set from `body`
|
|
1279
|
+
* (bytes; null is empty), and this resolves once the response reached the
|
|
1280
|
+
* connection. A status the library refuses (kind "ProtocolError") fails
|
|
1281
|
+
* the call and spends the exchange, as does a body on a 204 or 304. */
|
|
1282
|
+
async respond(status, options = {}) {
|
|
1283
|
+
const o = callOptions(options, ["headers", "body", "signal"], "respond");
|
|
1284
|
+
const code = integer("status", status, U16);
|
|
1285
|
+
const headers = fieldsOf("headers", o.headers);
|
|
1286
|
+
const body = o.body == null ? null : bytes("body", o.body);
|
|
1287
|
+
await op(
|
|
1288
|
+
this,
|
|
1289
|
+
() =>
|
|
1290
|
+
responding(this, (r) => withNative(headers, (h) => native.responderRespondBytes(r, code, h, body))),
|
|
1291
|
+
native.responderRespondBytesOpWait,
|
|
1292
|
+
native.responderRespondBytesOpFd,
|
|
1293
|
+
o.signal,
|
|
1294
|
+
);
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/** Sends the response head and resolves with a BodyWriter for the body.
|
|
1298
|
+
* With a `content-length` field the body must be exactly that long;
|
|
1299
|
+
* without one it is chunked, and may end with trailers. */
|
|
1300
|
+
async respondStream(status, options = {}) {
|
|
1301
|
+
const o = callOptions(options, ["headers", "signal"], "respondStream");
|
|
1302
|
+
const code = integer("status", status, U16);
|
|
1303
|
+
const headers = fieldsOf("headers", o.headers);
|
|
1304
|
+
const writer = await op(
|
|
1305
|
+
this,
|
|
1306
|
+
() => responding(this, (r) => withNative(headers, (h) => native.responderRespond(r, code, h))),
|
|
1307
|
+
native.responderRespondOpWait,
|
|
1308
|
+
native.responderRespondOpFd,
|
|
1309
|
+
o.signal,
|
|
1310
|
+
);
|
|
1311
|
+
return adopt(BodyWriter, writer);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
function exchange(handle) {
|
|
1316
|
+
return head(adopt(Exchange, handle), {
|
|
1317
|
+
method: native.exchangeMethod(handle),
|
|
1318
|
+
scheme: schemeOf(native.exchangeScheme(handle)),
|
|
1319
|
+
authority: native.exchangeAuthority(handle),
|
|
1320
|
+
path: native.exchangePath(handle),
|
|
1321
|
+
version: VERSIONS.get(native.exchangeVersion(handle)),
|
|
1322
|
+
peer: native.exchangePeer(handle),
|
|
1323
|
+
headers: received(native.exchangeFields(handle)),
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* An HTTP server: bound to listeners, it hands out one Exchange per
|
|
1329
|
+
* request, pulled with `accept()` or `for await (const exchange of
|
|
1330
|
+
* server)`, which ends once `close()` has been called. `new Server()` runs
|
|
1331
|
+
* on a reactor of its own; `new Server(options, { context })` takes
|
|
1332
|
+
* ServerOptions and shares a context's reactor. Dropping it drops this
|
|
1333
|
+
* reference: listeners and connections end with the last one, so `close()`
|
|
1334
|
+
* first to let exchanges in flight finish.
|
|
1335
|
+
*/
|
|
1336
|
+
export class Server extends Handle {
|
|
1337
|
+
constructor(options = null, how = {}) {
|
|
1338
|
+
super();
|
|
1339
|
+
if (options != null && !(options instanceof ServerOptions)) {
|
|
1340
|
+
throw new TypeError("options is a ServerOptions");
|
|
1341
|
+
}
|
|
1342
|
+
const { context } = optionsOf(how, ["context"], "Server");
|
|
1343
|
+
onContext(this, context, (ctx) =>
|
|
1344
|
+
options == null
|
|
1345
|
+
? native.serverNew(ctx, null)
|
|
1346
|
+
: withBuilt(buildServerOptions, options, (o) => native.serverNew(ctx, o)),
|
|
1347
|
+
);
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/** Serves plain HTTP/1.1 on `address` (`"ip:port"` text or an Address;
|
|
1351
|
+
* port 0 picks one) and resolves with the Address bound. A name that is
|
|
1352
|
+
* not an IP address is kind "InvalidArgument". */
|
|
1353
|
+
async bindTcp(address, { signal } = {}) {
|
|
1354
|
+
const where = addressText(address);
|
|
1355
|
+
const handle = this[HANDLE];
|
|
1356
|
+
return bound(
|
|
1357
|
+
await op(
|
|
1358
|
+
this,
|
|
1359
|
+
() => native.serverBindTcp(handle, where),
|
|
1360
|
+
native.serverBindTcpOpWait,
|
|
1361
|
+
native.serverBindTcpOpFd,
|
|
1362
|
+
signal,
|
|
1363
|
+
),
|
|
1364
|
+
);
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
/** Serves HTTPS on `address`: HTTP/1.1 and HTTP/2 by ALPN. */
|
|
1368
|
+
async bindTls(address, tls, { signal } = {}) {
|
|
1369
|
+
return this.#bindSecured(address, tls, native.serverBindTls, native.serverBindTlsOpWait, native.serverBindTlsOpFd, signal);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/** Serves HTTP/3 on UDP `address` (TLS 1.3 only). */
|
|
1373
|
+
async bindQuic(address, tls, { signal } = {}) {
|
|
1374
|
+
return this.#bindSecured(address, tls, native.serverBindQuic, native.serverBindQuicOpWait, native.serverBindQuicOpFd, signal);
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
async #bindSecured(address, tls, start, waitOf, fdOf, signal) {
|
|
1378
|
+
const where = addressText(address);
|
|
1379
|
+
if (!(tls instanceof ServerTls)) {
|
|
1380
|
+
throw new TypeError("tls is a ServerTls");
|
|
1381
|
+
}
|
|
1382
|
+
const handle = this[HANDLE];
|
|
1383
|
+
return bound(
|
|
1384
|
+
await op(
|
|
1385
|
+
this,
|
|
1386
|
+
() => withBuilt(buildServerTls, tls, (t) => start(handle, where, t)),
|
|
1387
|
+
waitOf,
|
|
1388
|
+
fdOf,
|
|
1389
|
+
signal,
|
|
1390
|
+
),
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
/** The next exchange. Throws kind "ConnectionClosed" once `close` began.
|
|
1395
|
+
* An aborted accept loses nothing: the next one gets the exchange. */
|
|
1396
|
+
async accept({ signal } = {}) {
|
|
1397
|
+
const handle = this[HANDLE];
|
|
1398
|
+
return exchange(
|
|
1399
|
+
await call(
|
|
1400
|
+
this,
|
|
1401
|
+
() => native.serverAccept(handle),
|
|
1402
|
+
() => native.serverFd(handle),
|
|
1403
|
+
signal,
|
|
1404
|
+
),
|
|
1405
|
+
);
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
/** Stops accepting, lets the exchanges in flight finish within the
|
|
1409
|
+
* options' `closeTimeoutMs`, then drops the rest. */
|
|
1410
|
+
async close({ signal } = {}) {
|
|
1411
|
+
const handle = this[HANDLE];
|
|
1412
|
+
await op(this, () => native.serverClose(handle), native.serverCloseOpWait, native.serverCloseOpFd, signal);
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
async *[Symbol.asyncIterator]() {
|
|
1416
|
+
for (;;) {
|
|
1417
|
+
let next;
|
|
1418
|
+
try {
|
|
1419
|
+
next = await this.accept();
|
|
1420
|
+
} catch (error) {
|
|
1421
|
+
if (error instanceof HttpError && error.kind === "ConnectionClosed") {
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
throw error;
|
|
1425
|
+
}
|
|
1426
|
+
yield next;
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
}
|