@mark1russell7/service 0.8.19 → 0.8.20
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/build/backoff.d.ts +44 -2
- package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
- package/build/builder.js +499 -0
- package/build/builder.js.map +1 -0
- package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
- package/build/channel.d.ts +1 -1
- package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
- package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
- package/build/client/core.js.map +1 -0
- package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
- package/build/client/dial.js +52 -0
- package/build/client/dial.js.map +1 -0
- package/build/client/machine.js +29 -0
- package/build/client/machine.js.map +1 -0
- package/build/client/meets.d.ts +35 -0
- package/build/client/meets.js +78 -0
- package/build/client/meets.js.map +1 -0
- package/build/clock.d.ts +1 -1
- package/build/conformance.d.ts +122 -0
- package/build/conformance.js +470 -0
- package/build/conformance.js.map +1 -0
- package/build/contract.d.ts +28 -0
- package/build/contract.js +184 -0
- package/build/contract.js.map +1 -0
- package/build/description.d.ts +161 -0
- package/build/description.js +11 -0
- package/build/description.js.map +1 -0
- package/build/drains.js +35 -0
- package/build/drains.js.map +1 -0
- package/build/events.d.ts +25 -0
- package/build/fakes.d.ts +43 -0
- package/build/fakes.js +93 -0
- package/build/fakes.js.map +1 -0
- package/build/grpc/client.d.ts +153 -0
- package/build/grpc/client.js +474 -0
- package/build/grpc/client.js.map +1 -0
- package/build/grpc/connection.d.ts +97 -0
- package/build/grpc/connection.js +59 -0
- package/build/grpc/connection.js.map +1 -0
- package/build/grpc/machine.d.ts +12 -0
- package/build/grpc/machine.js +149 -0
- package/build/grpc/machine.js.map +1 -0
- package/build/grpc/meets.d.ts +14 -0
- package/build/grpc/meets.js +105 -0
- package/build/grpc/meets.js.map +1 -0
- package/build/grpc/starting.d.ts +33 -0
- package/build/grpc/starting.js +89 -0
- package/build/grpc/starting.js.map +1 -0
- package/build/grpc.d.ts +9 -303
- package/build/grpc.js +7 -854
- package/build/health.d.ts +93 -0
- package/build/health.js +223 -0
- package/build/health.js.map +1 -0
- package/build/heartbeat.d.ts +1 -1
- package/build/host/discovery.d.ts +61 -0
- package/build/host/discovery.js +113 -0
- package/build/host/discovery.js.map +1 -0
- package/build/host/env.d.ts +14 -0
- package/build/host/env.js +57 -0
- package/build/host/env.js.map +1 -0
- package/build/host/fakes.d.ts +82 -0
- package/build/host/fakes.js +239 -0
- package/build/host/fakes.js.map +1 -0
- package/build/host/group.d.ts +142 -0
- package/build/host/group.js +517 -0
- package/build/host/group.js.map +1 -0
- package/build/host/install.d.ts +96 -0
- package/build/host/install.js +330 -0
- package/build/host/install.js.map +1 -0
- package/build/host/lock.d.ts +78 -0
- package/build/host/lock.js +190 -0
- package/build/host/lock.js.map +1 -0
- package/build/host/logs.d.ts +26 -0
- package/build/host/logs.js +48 -0
- package/build/host/logs.js.map +1 -0
- package/build/host/node.d.ts +14 -0
- package/build/host/node.js +309 -0
- package/build/host/node.js.map +1 -0
- package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
- package/build/host/ports.js +17 -0
- package/build/host/ports.js.map +1 -0
- package/build/host/probes.d.ts +51 -0
- package/build/host/probes.js +139 -0
- package/build/host/probes.js.map +1 -0
- package/build/host/processes.d.ts +32 -0
- package/build/host/processes.js +63 -0
- package/build/host/processes.js.map +1 -0
- package/build/host/render.d.ts +84 -0
- package/build/host/render.js +235 -0
- package/build/host/render.js.map +1 -0
- package/build/host/watch.d.ts +90 -0
- package/build/host/watch.js +165 -0
- package/build/host/watch.js.map +1 -0
- package/build/host.d.ts +13 -671
- package/build/host.js +12 -2126
- package/build/http/answers.js +29 -0
- package/build/http/answers.js.map +1 -0
- package/build/http/fake-server.js +61 -0
- package/build/http/fake-server.js.map +1 -0
- package/build/http/outcome.d.ts +115 -0
- package/build/http/outcome.js +325 -0
- package/build/http/outcome.js.map +1 -0
- package/build/http/probes.d.ts +83 -0
- package/build/http/probes.js +232 -0
- package/build/http/probes.js.map +1 -0
- package/build/http/transport.d.ts +165 -0
- package/build/http/transport.js +517 -0
- package/build/http/transport.js.map +1 -0
- package/build/http-client/client.d.ts +121 -0
- package/build/http-client/client.js +330 -0
- package/build/http-client/client.js.map +1 -0
- package/build/http-client/connection.d.ts +78 -0
- package/build/http-client/connection.js +54 -0
- package/build/http-client/connection.js.map +1 -0
- package/build/http-client/machine.d.ts +14 -0
- package/build/http-client/machine.js +109 -0
- package/build/http-client/machine.js.map +1 -0
- package/build/http-client/meets.d.ts +11 -0
- package/build/http-client/meets.js +74 -0
- package/build/http-client/meets.js.map +1 -0
- package/build/http-client/session.d.ts +87 -0
- package/build/http-client/session.js +99 -0
- package/build/http-client/session.js.map +1 -0
- package/build/http-client/starting.d.ts +25 -0
- package/build/http-client/starting.js +65 -0
- package/build/http-client/starting.js.map +1 -0
- package/build/http-client.d.ts +9 -330
- package/build/http-client.js +8 -707
- package/build/http.d.ts +5 -353
- package/build/http.js +3 -1086
- package/build/identity.d.ts +16 -0
- package/build/identity.js +44 -0
- package/build/identity.js.map +1 -0
- package/build/index.d.ts +35 -412
- package/build/index.js +24 -3277
- package/build/knobs.d.ts +1 -0
- package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
- package/build/knobs.js.map +1 -0
- package/build/latch.d.ts +29 -0
- package/build/latch.js +122 -0
- package/build/latch.js.map +1 -0
- package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
- package/build/law.js +149 -0
- package/build/law.js.map +1 -0
- package/build/lifecycle.d.ts +144 -0
- package/build/lifecycle.js +411 -0
- package/build/lifecycle.js.map +1 -0
- package/build/limiter/machine.d.ts +40 -0
- package/build/limiter/machine.js +279 -0
- package/build/limiter/machine.js.map +1 -0
- package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
- package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
- package/build/limiter/policy.js.map +1 -0
- package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
- package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
- package/build/limiter/quota.js.map +1 -0
- package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
- package/build/limiter/store.js +145 -0
- package/build/limiter/store.js.map +1 -0
- package/build/limiter.d.ts +4 -3
- package/build/limiter.js +4 -2
- package/build/lint.d.ts +152 -0
- package/build/lint.js +576 -0
- package/build/lint.js.map +1 -0
- package/build/logger.d.ts +71 -0
- package/build/logger.js +183 -0
- package/build/logger.js.map +1 -0
- package/build/machines.d.ts +41 -0
- package/build/machines.js +451 -0
- package/build/machines.js.map +1 -0
- package/build/metrics.d.ts +53 -0
- package/build/metrics.js +111 -0
- package/build/metrics.js.map +1 -0
- package/build/mongodb/client.d.ts +131 -0
- package/build/mongodb/client.js +388 -0
- package/build/mongodb/client.js.map +1 -0
- package/build/mongodb/connection.d.ts +112 -0
- package/build/mongodb/connection.js +12 -0
- package/build/mongodb/connection.js.map +1 -0
- package/build/mongodb/machine.d.ts +14 -0
- package/build/mongodb/machine.js +122 -0
- package/build/mongodb/machine.js.map +1 -0
- package/build/mongodb/meets.d.ts +15 -0
- package/build/mongodb/meets.js +103 -0
- package/build/mongodb/meets.js.map +1 -0
- package/build/mongodb/starting.d.ts +29 -0
- package/build/mongodb/starting.js +77 -0
- package/build/mongodb/starting.js.map +1 -0
- package/build/mongodb.d.ts +8 -296
- package/build/mongodb.js +7 -682
- package/build/operation.d.ts +27 -0
- package/build/{operation-DF73RZOI.js → operation.js} +2 -2
- package/build/operation.js.map +1 -0
- package/build/otel.d.ts +2 -2
- package/build/pg/client.d.ts +96 -0
- package/build/pg/client.js +277 -0
- package/build/pg/client.js.map +1 -0
- package/build/pg/connection.d.ts +75 -0
- package/build/pg/connection.js +11 -0
- package/build/pg/connection.js.map +1 -0
- package/build/pg/machine.d.ts +13 -0
- package/build/pg/machine.js +111 -0
- package/build/pg/machine.js.map +1 -0
- package/build/pg/meets.d.ts +14 -0
- package/build/pg/meets.js +83 -0
- package/build/pg/meets.js.map +1 -0
- package/build/pg/starting.d.ts +26 -0
- package/build/pg/starting.js +62 -0
- package/build/pg/starting.js.map +1 -0
- package/build/pg.d.ts +8 -219
- package/build/pg.js +7 -525
- package/build/poller.d.ts +9 -0
- package/build/poller.js +152 -0
- package/build/poller.js.map +1 -0
- package/build/process.d.ts +114 -0
- package/build/process.js +170 -0
- package/build/process.js.map +1 -0
- package/build/profiles.d.ts +68 -0
- package/build/profiles.js +120 -0
- package/build/profiles.js.map +1 -0
- package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
- package/build/queue.js +279 -0
- package/build/queue.js.map +1 -0
- package/build/rabbitmq/client.d.ts +144 -0
- package/build/rabbitmq/client.js +426 -0
- package/build/rabbitmq/client.js.map +1 -0
- package/build/rabbitmq/connection.d.ts +91 -0
- package/build/rabbitmq/connection.js +15 -0
- package/build/rabbitmq/connection.js.map +1 -0
- package/build/rabbitmq/machine.d.ts +13 -0
- package/build/rabbitmq/machine.js +159 -0
- package/build/rabbitmq/machine.js.map +1 -0
- package/build/rabbitmq/meets.d.ts +12 -0
- package/build/rabbitmq/meets.js +96 -0
- package/build/rabbitmq/meets.js.map +1 -0
- package/build/rabbitmq/starting.d.ts +27 -0
- package/build/rabbitmq/starting.js +67 -0
- package/build/rabbitmq/starting.js.map +1 -0
- package/build/rabbitmq.d.ts +8 -283
- package/build/rabbitmq.js +7 -742
- package/build/redis/client.d.ts +86 -0
- package/build/redis/client.js +285 -0
- package/build/redis/client.js.map +1 -0
- package/build/redis/connection.d.ts +57 -0
- package/build/redis/connection.js +11 -0
- package/build/redis/connection.js.map +1 -0
- package/build/redis/limiter.d.ts +43 -0
- package/build/redis/limiter.js +164 -0
- package/build/redis/limiter.js.map +1 -0
- package/build/redis/machine.d.ts +12 -0
- package/build/redis/machine.js +144 -0
- package/build/redis/machine.js.map +1 -0
- package/build/redis/meets.d.ts +11 -0
- package/build/redis/meets.js +75 -0
- package/build/redis/meets.js.map +1 -0
- package/build/redis/operations.d.ts +5 -0
- package/build/redis/operations.js +114 -0
- package/build/redis/operations.js.map +1 -0
- package/build/redis.d.ts +10 -207
- package/build/redis.js +9 -771
- package/build/requests.d.ts +66 -0
- package/build/requests.js +279 -0
- package/build/requests.js.map +1 -0
- package/build/retrier.d.ts +62 -0
- package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
- package/build/retrier.js.map +1 -0
- package/build/routes.d.ts +35 -0
- package/build/routes.js +77 -0
- package/build/routes.js.map +1 -0
- package/build/rules.d.ts +19 -2
- package/build/stops.d.ts +51 -0
- package/build/stops.js +86 -0
- package/build/stops.js.map +1 -0
- package/build/testing.d.ts +8 -270
- package/build/testing.js +4 -1027
- package/build/testing.js.map +1 -1
- package/build/timing.d.ts +63 -0
- package/build/{timing-DZl36uXs.js → timing.js} +2 -2
- package/build/timing.js.map +1 -0
- package/build/units.d.ts +17 -0
- package/build/units.js +236 -0
- package/build/units.js.map +1 -0
- package/build/watchdog.d.ts +34 -0
- package/build/watchdog.js +53 -0
- package/build/watchdog.js.map +1 -0
- package/build/websocket/client.d.ts +136 -0
- package/build/websocket/client.js +422 -0
- package/build/websocket/client.js.map +1 -0
- package/build/websocket/connection.d.ts +83 -0
- package/build/websocket/connection.js +57 -0
- package/build/websocket/connection.js.map +1 -0
- package/build/websocket/machine.d.ts +12 -0
- package/build/websocket/machine.js +155 -0
- package/build/websocket/machine.js.map +1 -0
- package/build/websocket/meets.d.ts +14 -0
- package/build/websocket/meets.js +92 -0
- package/build/websocket/meets.js.map +1 -0
- package/build/websocket/starting.d.ts +25 -0
- package/build/websocket/starting.js +69 -0
- package/build/websocket/starting.js.map +1 -0
- package/build/websocket.d.ts +9 -264
- package/build/websocket.js +8 -774
- package/build/worker.d.ts +92 -0
- package/build/worker.js +153 -0
- package/build/worker.js.map +1 -0
- package/package.json +4 -3
- package/build/backoff-QTRGfkEK.d.ts +0 -45
- package/build/clock-DpVgpY4h.d.ts +0 -2
- package/build/grpc.js.map +0 -1
- package/build/host.js.map +0 -1
- package/build/http-client.js.map +0 -1
- package/build/http.js.map +0 -1
- package/build/index.js.map +0 -1
- package/build/knobs-BJcz6m01.js.map +0 -1
- package/build/lifecycle-D0J-zwZF.d.ts +0 -374
- package/build/limiter-DrM0PQV9.js.map +0 -1
- package/build/logger-B6drv9w0.d.ts +0 -488
- package/build/machine-BhVeHr_m.js.map +0 -1
- package/build/mongodb.js.map +0 -1
- package/build/operation-DF73RZOI.js.map +0 -1
- package/build/pg.js.map +0 -1
- package/build/policy-UYALkqVq.js.map +0 -1
- package/build/process-7R9M29wN.js +0 -437
- package/build/process-7R9M29wN.js.map +0 -1
- package/build/rabbitmq.js.map +0 -1
- package/build/redis.js.map +0 -1
- package/build/requests-DD2ALv0_.js +0 -583
- package/build/requests-DD2ALv0_.js.map +0 -1
- package/build/retrier-Dnjhvxol.js.map +0 -1
- package/build/timing-DZl36uXs.js.map +0 -1
- package/build/websocket.js.map +0 -1
package/build/http.js
CHANGED
|
@@ -1,1087 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { convertible, valueIn } from "@mark1russell7/quantity";
|
|
5
|
-
import { createServer } from "node:http";
|
|
6
|
-
// src/http/answers.ts
|
|
7
|
-
const marked = /* @__PURE__ */ new WeakMap();
|
|
8
|
-
const watchers = /* @__PURE__ */ new Set();
|
|
9
|
-
/**
|
|
10
|
-
* This function marks a response that waits for the end of its request. `owner` is the lifecycle
|
|
11
|
-
* that made the stream, or null. It gives the function that removes the mark.
|
|
12
|
-
*/
|
|
13
|
-
const markAnswer = (res, owner) => {
|
|
14
|
-
marked.set(res, owner);
|
|
15
|
-
return () => {
|
|
16
|
-
if (!marked.delete(res)) return;
|
|
17
|
-
for (const watcher of [...watchers]) watcher();
|
|
18
|
-
};
|
|
19
|
-
};
|
|
20
|
-
/**
|
|
21
|
-
* This function gives the mark of a response: the lifecycle that made its stream. It gives null for a
|
|
22
|
-
* stream outside each lifecycle, and undefined for a response with no mark.
|
|
23
|
-
*/
|
|
24
|
-
const answerOwner = (res) => marked.get(res);
|
|
25
|
-
/** This function starts `watcher` after each removal of a mark. It gives the function that stops it. */
|
|
26
|
-
const watchAnswers = (watcher) => {
|
|
27
|
-
watchers.add(watcher);
|
|
28
|
-
return () => {
|
|
29
|
-
watchers.delete(watcher);
|
|
30
|
-
};
|
|
31
|
-
};
|
|
32
|
-
// src/http/transport.ts
|
|
33
|
-
/** This function gives the path of a request target, without its query and fragment. */
|
|
34
|
-
const pathOf = (url) => {
|
|
35
|
-
const raw = url ?? "/";
|
|
36
|
-
const end = raw.search(/[?#]/);
|
|
37
|
-
const path = end === -1 ? raw : raw.slice(0, end);
|
|
38
|
-
if (path.startsWith("/")) return path;
|
|
39
|
-
try {
|
|
40
|
-
return new URL(raw).pathname;
|
|
41
|
-
} catch {
|
|
42
|
-
return path;
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
/** This function gives a knob in milliseconds, or infinity for a time without a bound. */
|
|
46
|
-
const millisecondsOf = (knobs, name, owner = "httpTransport") => millisecondsOf$1(knobs, name, owner);
|
|
47
|
-
/**
|
|
48
|
-
* This function gives the `Retry-After` of the knob `server_retry_after`, in whole seconds, rounded
|
|
49
|
-
* up. The knob is necessary, and it has a bound.
|
|
50
|
-
*/
|
|
51
|
-
const retryAfterOf = (knobs, owner) => {
|
|
52
|
-
const retryAfter = millisecondsOf(knobs, "server_retry_after", owner);
|
|
53
|
-
if (!Number.isFinite(retryAfter)) throw new Error("the knob server_retry_after has no bound: a Retry-After needs a time");
|
|
54
|
-
return String(Math.ceil(retryAfter / 1e3));
|
|
55
|
-
};
|
|
56
|
-
/**
|
|
57
|
-
* This function gives the backlog of listen(2) from the knob `server_listen_backlog`, or undefined without the
|
|
58
|
-
* knob. The backlog is a whole count of 0 or more. A backlog of 0 is valid: the queue then holds one connection.
|
|
59
|
-
*/
|
|
60
|
-
const backlogOf = (knobs, owner) => {
|
|
61
|
-
const amount = knobs["server_listen_backlog"];
|
|
62
|
-
if (amount === void 0) return void 0;
|
|
63
|
-
if (!convertible(amount.unit, "count")) throw new Error("the knob server_listen_backlog is not a count");
|
|
64
|
-
if (amount.value === "infinite") throw new Error(`the knob server_listen_backlog of ${owner} has no bound: listen(2) takes a whole count`);
|
|
65
|
-
const value = valueIn(amount, "count");
|
|
66
|
-
if (!(Number.isInteger(value) && value >= 0)) throw new Error(`the knob server_listen_backlog is ${value}, not a whole count of 0 or more`);
|
|
67
|
-
if (value === 0) throw new Error(`the knob server_listen_backlog of ${owner} is 0, and Node gives listen(2) 511 for 0: the transport cannot ask for 0`);
|
|
68
|
-
return value;
|
|
69
|
-
};
|
|
70
|
-
/** This function tells if the headers of a call of `writeHead` name a header, an object or a flat list of names and values. */
|
|
71
|
-
const names = (headers, name) => {
|
|
72
|
-
if (Array.isArray(headers)) return headers.some((each, at) => at % 2 === 0 && String(each).toLowerCase() === name);
|
|
73
|
-
return typeof headers === "object" && headers !== null && Object.keys(headers).some((key) => key.toLowerCase() === name);
|
|
74
|
-
};
|
|
75
|
-
/** This function gives the headers of a call of `writeHead` without one header. */
|
|
76
|
-
const without = (headers, name) => {
|
|
77
|
-
if (Array.isArray(headers)) {
|
|
78
|
-
const kept = [];
|
|
79
|
-
for (let at = 0; at + 1 < headers.length; at += 2) if (String(headers[at]).toLowerCase() !== name) kept.push(headers[at], headers[at + 1]);
|
|
80
|
-
return kept;
|
|
81
|
-
}
|
|
82
|
-
if (typeof headers !== "object" || headers === null) return headers;
|
|
83
|
-
return Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== name));
|
|
84
|
-
};
|
|
85
|
-
/**
|
|
86
|
-
* This function applies the rule of `Retry-After` to a call of `writeHead`, and gives its arguments.
|
|
87
|
-
* A 503 without `Retry-After` gets the time of `server_retry_after` (RFC 9110). A 500 loses each
|
|
88
|
-
* `Retry-After`, from the call and from the response.
|
|
89
|
-
*/
|
|
90
|
-
const retryRule = (res, args, retryAfter) => {
|
|
91
|
-
const status = typeof args[0] === "number" ? args[0] : res.statusCode;
|
|
92
|
-
const at = typeof args[1] === "string" ? 2 : 1;
|
|
93
|
-
if (status === 503 && !res.hasHeader("retry-after") && !names(args[at], "retry-after")) res.setHeader("retry-after", retryAfter);
|
|
94
|
-
if (status !== 500) return args;
|
|
95
|
-
res.removeHeader("retry-after");
|
|
96
|
-
if (!names(args[at], "retry-after")) return args;
|
|
97
|
-
const given = [...args];
|
|
98
|
-
given[at] = without(args[at], "retry-after");
|
|
99
|
-
return given;
|
|
100
|
-
};
|
|
101
|
-
const STATUS_TEXT = {
|
|
102
|
-
404: "Not Found",
|
|
103
|
-
500: "Internal Server Error",
|
|
104
|
-
503: "Service Unavailable"
|
|
105
|
-
};
|
|
106
|
-
/** This function tells if an edge server is a server of `node:http2`. A server of `node:http` has `closeIdleConnections`, and one of HTTP/2 has none. */
|
|
107
|
-
const isHttp2 = (server) => typeof server.closeIdleConnections !== "function";
|
|
108
|
-
/** This function gives the session of HTTP/2 of a response, or undefined for a response of HTTP/1.1. */
|
|
109
|
-
const sessionOf = (res) => res.stream?.session;
|
|
110
|
-
/** This function tells if a response is destroyed. A response of HTTP/2 tells it through its stream. */
|
|
111
|
-
const destroyed = (res) => res.destroyed === true || res.stream?.destroyed === true;
|
|
112
|
-
/** This function tells if the headers of a call of `writeHead` give `Connection: close`. */
|
|
113
|
-
const closes = (headers) => {
|
|
114
|
-
if (Array.isArray(headers)) return headers.some((each, at) => at % 2 === 0 && String(each).toLowerCase() === "connection" && String(headers[at + 1]).toLowerCase() === "close");
|
|
115
|
-
if (typeof headers !== "object" || headers === null) return false;
|
|
116
|
-
return Object.entries(headers).some(([key, value]) => key.toLowerCase() === "connection" && String(value).toLowerCase() === "close");
|
|
117
|
-
};
|
|
118
|
-
/**
|
|
119
|
-
* This function sends GOAWAY on a session of HTTP/2, once. `close()` of Node sends it with the last
|
|
120
|
-
* stream that the server took. Each stream up to that one ends as usual. Then the session closes.
|
|
121
|
-
* The client sends each later stream again on a new connection, because the server did not take it.
|
|
122
|
-
*/
|
|
123
|
-
const goaway = (session) => {
|
|
124
|
-
if (!session.closed && !session.destroyed) session.close();
|
|
125
|
-
};
|
|
126
|
-
/**
|
|
127
|
-
* This function makes a server of `node:http` or `node:http2` a transport of the lifecycle (S6 A8 and
|
|
128
|
-
* A13). It is not a framework: it has no routes, no body parser and no middleware.
|
|
129
|
-
* - The count of work in flight comes from events: each response until its `close`, and each upgraded
|
|
130
|
-
* connection until its `close`.
|
|
131
|
-
* - `stopIntake` closes the listener, and new connections get a refusal. It closes the idle connections
|
|
132
|
-
* at once and at each `server_idle_sweep_interval`. Each later response gets `Connection: close`.
|
|
133
|
-
* A connection is not idle while the bytes of its answer go (SYS-33).
|
|
134
|
-
* - `drain` waits until no work is in flight, or until the deadline. It gives the cooperative abort to
|
|
135
|
-
* the handlers through their context. At the deadline, it also waits for each answer that is to come
|
|
136
|
-
* or to go out (SYS-29). The cap of the phase bounds that wait. Answers that did not go out by the
|
|
137
|
-
* cap are not a failure of the phase. A stream outside the lifecycle of the transport does not hold it.
|
|
138
|
-
* - `close` destroys each connection. A second close gives the same promise.
|
|
139
|
-
* - The mounts share one port. The first request handler that gives true answers. After the stop of
|
|
140
|
-
* the intake, only the mounts until `close transports` answer, and each other request gets a 503.
|
|
141
|
-
* - HTTP/2 has no `Connection` header (RFC 9113, section 8.2.2). Thus a close of a connection is a
|
|
142
|
-
* GOAWAY on its session. Each handler gets the request and the response of the compatibility API of
|
|
143
|
-
* `node:http2`. They have the parts of the API that the handlers of this entry use. A handler that
|
|
144
|
-
* gives `Connection: close` gets a GOAWAY. The stop of the intake sends GOAWAY on each session, and
|
|
145
|
-
* the close destroys each session.
|
|
146
|
-
*/
|
|
147
|
-
const httpTransport = (edge, knobs, options = {}) => {
|
|
148
|
-
const server = edge;
|
|
149
|
-
const h2 = isHttp2(edge) ? edge : null;
|
|
150
|
-
const clock = options.clock ?? realClock;
|
|
151
|
-
const idleClose = millisecondsOf(knobs, "server_idle_close");
|
|
152
|
-
const sweepEvery = millisecondsOf(knobs, "server_idle_sweep_interval");
|
|
153
|
-
if (sweepEvery === 0) throw new Error("the knob server_idle_sweep_interval is zero: a sweep needs an interval above zero");
|
|
154
|
-
const retryAfterHeader = retryAfterOf(knobs, "httpTransport");
|
|
155
|
-
const backlog = backlogOf(knobs, "httpTransport");
|
|
156
|
-
if (backlog !== void 0 && (options.listen === void 0 || typeof options.listen === "function")) throw new Error("the knob server_listen_backlog needs the listen options of the transport: the transport does not make this server listen");
|
|
157
|
-
if (backlog !== void 0 && typeof options.listen === "object" && options.listen.backlog !== void 0) throw new Error("the backlog is in the knob server_listen_backlog and in the listen options: give it once, as the knob");
|
|
158
|
-
for (const derived of ["server_idle_close_hint", "server_idle_close_buffer"]) if (knobs[derived] !== void 0) throw new Error(`the knob ${derived} comes from the transport: give only server_idle_close`);
|
|
159
|
-
if (server.listenerCount("request") > 0 || server.listenerCount("upgrade") > 0) throw new Error("the server has a request or upgrade listener of its own: mount it as a handler");
|
|
160
|
-
const buffer = h2 === null ? server.keepAliveTimeoutBuffer ?? 0 : 0;
|
|
161
|
-
if (h2 !== null && idleClose === 0) throw new Error("the knob server_idle_close is 0 ms: the timeout of a session of HTTP/2 needs a time above zero");
|
|
162
|
-
if (h2 === null && Number.isFinite(idleClose) && idleClose <= buffer) throw new Error(`the knob server_idle_close is ${idleClose} ms, at or below the keepAliveTimeoutBuffer of the server, ${buffer} ms: the server closes an idle connection at keepAliveTimeout + keepAliveTimeoutBuffer`);
|
|
163
|
-
if (h2 === null) server.keepAliveTimeout = Number.isFinite(idleClose) ? idleClose - buffer : 0;
|
|
164
|
-
else h2.setTimeout(Number.isFinite(idleClose) ? idleClose : 0);
|
|
165
|
-
const declared = {
|
|
166
|
-
...knobs,
|
|
167
|
-
server_idle_close_hint: h2 === null && Number.isFinite(idleClose) ? {
|
|
168
|
-
value: Math.floor(server.keepAliveTimeout / 1e3),
|
|
169
|
-
unit: "s"
|
|
170
|
-
} : {
|
|
171
|
-
value: "infinite",
|
|
172
|
-
unit: "s"
|
|
173
|
-
},
|
|
174
|
-
server_idle_close_buffer: {
|
|
175
|
-
value: buffer,
|
|
176
|
-
unit: "ms"
|
|
177
|
-
}
|
|
178
|
-
};
|
|
179
|
-
const requestMounts = [];
|
|
180
|
-
const upgradeMounts = [];
|
|
181
|
-
const responses = /* @__PURE__ */ new Set();
|
|
182
|
-
const upgraded = /* @__PURE__ */ new Set();
|
|
183
|
-
const sockets = /* @__PURE__ */ new Set();
|
|
184
|
-
const sessions = /* @__PURE__ */ new Set();
|
|
185
|
-
const drainers = /* @__PURE__ */ new Set();
|
|
186
|
-
const closedWaiters = /* @__PURE__ */ new Set();
|
|
187
|
-
const intake = new AbortController();
|
|
188
|
-
const cooperative = new AbortController();
|
|
189
|
-
let life = null;
|
|
190
|
-
const context = {
|
|
191
|
-
intake: intake.signal,
|
|
192
|
-
signal: cooperative.signal,
|
|
193
|
-
get life() {
|
|
194
|
-
return life;
|
|
195
|
-
},
|
|
196
|
-
retryAfter: knobs.server_retry_after,
|
|
197
|
-
keepAlive: () => keepsAlive()
|
|
198
|
-
};
|
|
199
|
-
let intakeOpen = true;
|
|
200
|
-
let listenerOpen = server.listening;
|
|
201
|
-
let serverClosed = !server.listening;
|
|
202
|
-
let sweep = null;
|
|
203
|
-
let closing = null;
|
|
204
|
-
const inFlight = () => responses.size + upgraded.size;
|
|
205
|
-
/**
|
|
206
|
-
* This function gives what holds a drain after its deadline. An answer is unflushed when its handler
|
|
207
|
-
* ended it and its bytes did not all go. It is unflushed too while `writeOutcome` waits for a client
|
|
208
|
-
* that does not read. A call runs while `writeOutcome` waits for the end of its request, which the
|
|
209
|
-
* cut of the drain gives. Only a stream of the lifecycle of the transport counts, because only its
|
|
210
|
-
* cut ends the stream. A response that is open for another reason does not hold the drain.
|
|
211
|
-
*/
|
|
212
|
-
const lateHold = () => {
|
|
213
|
-
let running = 0;
|
|
214
|
-
let unflushed = 0;
|
|
215
|
-
let outside = 0;
|
|
216
|
-
for (const res of responses) {
|
|
217
|
-
if (destroyed(res)) continue;
|
|
218
|
-
if (res.writableEnded) {
|
|
219
|
-
if (!res.writableFinished) unflushed += 1;
|
|
220
|
-
continue;
|
|
221
|
-
}
|
|
222
|
-
const owner = answerOwner(res);
|
|
223
|
-
if (owner === void 0) continue;
|
|
224
|
-
if (life === null || owner !== life) outside += 1;
|
|
225
|
-
else if (res.writableNeedDrain) unflushed += 1;
|
|
226
|
-
else running += 1;
|
|
227
|
-
}
|
|
228
|
-
return {
|
|
229
|
-
running,
|
|
230
|
-
unflushed,
|
|
231
|
-
outside
|
|
232
|
-
};
|
|
233
|
-
};
|
|
234
|
-
const answering = () => {
|
|
235
|
-
const hold = lateHold();
|
|
236
|
-
return hold.running + hold.unflushed > 0;
|
|
237
|
-
};
|
|
238
|
-
const report = (error, req) => {
|
|
239
|
-
try {
|
|
240
|
-
options.onError?.(error, req);
|
|
241
|
-
} catch {}
|
|
242
|
-
};
|
|
243
|
-
const settled = () => {
|
|
244
|
-
for (const check of [...drainers]) check();
|
|
245
|
-
if (closing !== null && inFlight() === 0 && sockets.size === 0 && serverClosed) for (const done of [...closedWaiters]) done();
|
|
246
|
-
};
|
|
247
|
-
const keepsAlive = () => intakeOpen && (options.keepAlive?.() ?? life?.keepAlive() ?? true);
|
|
248
|
-
const live = (mounts) => intakeOpen ? [...mounts] : mounts.filter((mount) => mount.until === "close transports");
|
|
249
|
-
const throughDrain = () => requestMounts.some((mount) => mount.until === "close transports") || upgradeMounts.some((mount) => mount.until === "close transports");
|
|
250
|
-
const closeListener = () => {
|
|
251
|
-
if (!listenerOpen) return;
|
|
252
|
-
listenerOpen = false;
|
|
253
|
-
server.close();
|
|
254
|
-
};
|
|
255
|
-
const closeIdleConnections = () => {
|
|
256
|
-
if (h2 === null) server.closeIdleConnections();
|
|
257
|
-
else for (const session of sessions) goaway(session);
|
|
258
|
-
};
|
|
259
|
-
const startSweep = () => {
|
|
260
|
-
if (!Number.isFinite(sweepEvery) || closing !== null) return;
|
|
261
|
-
sweep = clock.after(sweepEvery, () => {
|
|
262
|
-
sweep = null;
|
|
263
|
-
if (closing !== null) return;
|
|
264
|
-
closeIdleConnections();
|
|
265
|
-
startSweep();
|
|
266
|
-
});
|
|
267
|
-
};
|
|
268
|
-
/**
|
|
269
|
-
* This function watches the headers of each response when they go, whatever wrote them. Each 503
|
|
270
|
-
* gets `Retry-After`, and a 500 gets none. The response closes its connection while the transport
|
|
271
|
-
* cannot keep it. On HTTP/2, the `Connection` header goes away, and a close is a GOAWAY on the session.
|
|
272
|
-
*/
|
|
273
|
-
const watchHeaders = (res) => {
|
|
274
|
-
const writeHead = res.writeHead;
|
|
275
|
-
res.writeHead = ((...args) => {
|
|
276
|
-
if (res.headersSent) return writeHead.apply(res, args);
|
|
277
|
-
const session = sessionOf(res);
|
|
278
|
-
if (session !== void 0) {
|
|
279
|
-
const at = typeof args[1] === "string" ? 2 : 1;
|
|
280
|
-
const asked = String(res.getHeader("connection") ?? "").toLowerCase() === "close" || closes(args[at]);
|
|
281
|
-
res.removeHeader("connection");
|
|
282
|
-
const given = [...args];
|
|
283
|
-
if (names(args[at], "connection")) given[at] = without(args[at], "connection");
|
|
284
|
-
if (asked || !keepsAlive()) goaway(session);
|
|
285
|
-
return writeHead.apply(res, retryRule(res, given, retryAfterHeader));
|
|
286
|
-
}
|
|
287
|
-
if (!keepsAlive()) {
|
|
288
|
-
res.shouldKeepAlive = false;
|
|
289
|
-
res.setHeader("connection", "close");
|
|
290
|
-
}
|
|
291
|
-
return writeHead.apply(res, retryRule(res, args, retryAfterHeader));
|
|
292
|
-
});
|
|
293
|
-
};
|
|
294
|
-
const answer = (res, status, headers = {}) => {
|
|
295
|
-
if (res.headersSent) {
|
|
296
|
-
res.destroy();
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
const body = STATUS_TEXT[status] ?? "";
|
|
300
|
-
res.writeHead(status, {
|
|
301
|
-
"content-type": "text/plain; charset=utf-8",
|
|
302
|
-
"content-length": String(Buffer.byteLength(body)),
|
|
303
|
-
...headers
|
|
304
|
-
});
|
|
305
|
-
res.end(body);
|
|
306
|
-
};
|
|
307
|
-
const refuse = (res) => answer(res, 503, {
|
|
308
|
-
"retry-after": retryAfterHeader,
|
|
309
|
-
connection: "close"
|
|
310
|
-
});
|
|
311
|
-
const route = async (req, res) => {
|
|
312
|
-
const mounts = live(requestMounts);
|
|
313
|
-
try {
|
|
314
|
-
for (const mount of mounts) {
|
|
315
|
-
const given = mount.handler(req, res, context);
|
|
316
|
-
if ((typeof given === "boolean" ? given : await given) || res.headersSent || res.writableEnded) return;
|
|
317
|
-
}
|
|
318
|
-
} catch (error) {
|
|
319
|
-
report(error, req);
|
|
320
|
-
if (!res.writableEnded) answer(res, 500);
|
|
321
|
-
return;
|
|
322
|
-
}
|
|
323
|
-
if (intakeOpen) answer(res, 404);
|
|
324
|
-
else refuse(res);
|
|
325
|
-
};
|
|
326
|
-
const callContext = options.callContext;
|
|
327
|
-
const trustBaggage = options.trustBaggage ?? (() => false);
|
|
328
|
-
const inCall = (req, fn) => callContext === void 0 ? fn() : callContext.run(req.headers, trustBaggage(req), fn);
|
|
329
|
-
const onRequest = (req, res) => {
|
|
330
|
-
responses.add(res);
|
|
331
|
-
res.once("finish", settled);
|
|
332
|
-
res.once("close", () => {
|
|
333
|
-
responses.delete(res);
|
|
334
|
-
settled();
|
|
335
|
-
});
|
|
336
|
-
watchHeaders(res);
|
|
337
|
-
inCall(req, () => route(req, res));
|
|
338
|
-
};
|
|
339
|
-
const onUpgrade = (req, socket, head) => {
|
|
340
|
-
socket.on("error", () => {});
|
|
341
|
-
const mount = live(upgradeMounts).find((each) => each.matches(req));
|
|
342
|
-
if (mount === void 0) {
|
|
343
|
-
const status = intakeOpen ? 404 : 503;
|
|
344
|
-
const extra = intakeOpen ? "" : `Retry-After: ${retryAfterHeader}\r\n`;
|
|
345
|
-
socket.end(`HTTP/1.1 ${status} ${STATUS_TEXT[status]}\r\nConnection: close\r\nContent-Length: 0\r\n${extra}\r\n`);
|
|
346
|
-
return;
|
|
347
|
-
}
|
|
348
|
-
if (socket.destroyed) return;
|
|
349
|
-
upgraded.add(socket);
|
|
350
|
-
socket.once("close", () => {
|
|
351
|
-
upgraded.delete(socket);
|
|
352
|
-
settled();
|
|
353
|
-
});
|
|
354
|
-
try {
|
|
355
|
-
inCall(req, () => mount.handler(req, socket, head, context));
|
|
356
|
-
} catch (error) {
|
|
357
|
-
report(error, req);
|
|
358
|
-
socket.destroy();
|
|
359
|
-
}
|
|
360
|
-
};
|
|
361
|
-
const onConnection = (socket) => {
|
|
362
|
-
sockets.add(socket);
|
|
363
|
-
socket.once("close", () => {
|
|
364
|
-
sockets.delete(socket);
|
|
365
|
-
settled();
|
|
366
|
-
});
|
|
367
|
-
};
|
|
368
|
-
/**
|
|
369
|
-
* Node counts a connection idle at the `end()` of its response, also while the bytes of the body
|
|
370
|
-
* still go. Then `closeIdleConnections` destroys the socket and cuts the answer (SYS-33). This
|
|
371
|
-
* method replaces it on the server, thus `server.close()` uses it too. Node keeps the socket of
|
|
372
|
-
* a response that did not end. Thus the method shows each answer whose bytes did not go as not
|
|
373
|
-
* ended, for the time of the call.
|
|
374
|
-
*/
|
|
375
|
-
if (h2 === null) {
|
|
376
|
-
const closeIdle = server.closeIdleConnections;
|
|
377
|
-
server.closeIdleConnections = function closeIdleConnections() {
|
|
378
|
-
const going = [...responses].filter((res) => res.writableEnded && !res.writableFinished && !res.destroyed);
|
|
379
|
-
for (const res of going) res.finished = false;
|
|
380
|
-
try {
|
|
381
|
-
closeIdle.call(this);
|
|
382
|
-
} finally {
|
|
383
|
-
for (const res of going) res.finished = true;
|
|
384
|
-
}
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
server.on("request", onRequest);
|
|
388
|
-
if (h2 === null) server.on("upgrade", onUpgrade);
|
|
389
|
-
else h2.on("session", (session) => {
|
|
390
|
-
sessions.add(session);
|
|
391
|
-
session.once("close", () => {
|
|
392
|
-
sessions.delete(session);
|
|
393
|
-
settled();
|
|
394
|
-
});
|
|
395
|
-
});
|
|
396
|
-
server.on("connection", onConnection);
|
|
397
|
-
server.on("listening", () => {
|
|
398
|
-
listenerOpen = true;
|
|
399
|
-
serverClosed = false;
|
|
400
|
-
});
|
|
401
|
-
server.on("close", () => {
|
|
402
|
-
listenerOpen = false;
|
|
403
|
-
serverClosed = true;
|
|
404
|
-
settled();
|
|
405
|
-
});
|
|
406
|
-
const remover = (list, entry) => () => {
|
|
407
|
-
const at = list.indexOf(entry);
|
|
408
|
-
if (at >= 0) list.splice(at, 1);
|
|
409
|
-
if (!intakeOpen && closing === null && !throughDrain()) closeListener();
|
|
410
|
-
};
|
|
411
|
-
return {
|
|
412
|
-
server: edge,
|
|
413
|
-
knobs: declared,
|
|
414
|
-
get connections() {
|
|
415
|
-
return sockets.size;
|
|
416
|
-
},
|
|
417
|
-
get intakeStopped() {
|
|
418
|
-
return !intakeOpen;
|
|
419
|
-
},
|
|
420
|
-
mount(handler, mountOptions = {}) {
|
|
421
|
-
const entry = {
|
|
422
|
-
handler,
|
|
423
|
-
until: mountOptions.until ?? handler.until ?? "stop intake"
|
|
424
|
-
};
|
|
425
|
-
requestMounts.push(entry);
|
|
426
|
-
return remover(requestMounts, entry);
|
|
427
|
-
},
|
|
428
|
-
upgrade(match, handler, mountOptions = {}) {
|
|
429
|
-
if (h2 !== null) throw new Error("a server of HTTP/2 has no upgrade: mount a request handler");
|
|
430
|
-
const entry = {
|
|
431
|
-
matches: typeof match === "string" ? (req) => pathOf(req.url) === match : match,
|
|
432
|
-
handler,
|
|
433
|
-
until: mountOptions.until ?? handler.until ?? "stop intake"
|
|
434
|
-
};
|
|
435
|
-
upgradeMounts.push(entry);
|
|
436
|
-
return remover(upgradeMounts, entry);
|
|
437
|
-
},
|
|
438
|
-
async start(_signal, given) {
|
|
439
|
-
life = given;
|
|
440
|
-
if (closing !== null) throw new Error("the transport closed: a closed transport does not start again");
|
|
441
|
-
if (server.listenerCount("request") > 1 || server.listenerCount("upgrade") > 1) throw new Error("the server has a request or upgrade listener of its own: mount it as a handler");
|
|
442
|
-
if (server.listening) return;
|
|
443
|
-
const listen = options.listen;
|
|
444
|
-
if (listen === void 0) throw new Error("the server does not listen, and the transport has no listen options");
|
|
445
|
-
if (typeof listen === "function") {
|
|
446
|
-
await listen(edge);
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
await new Promise((resolve, reject) => {
|
|
450
|
-
const failed = (error) => {
|
|
451
|
-
server.off("listening", listened);
|
|
452
|
-
reject(error);
|
|
453
|
-
};
|
|
454
|
-
const listened = () => {
|
|
455
|
-
server.off("error", failed);
|
|
456
|
-
resolve();
|
|
457
|
-
};
|
|
458
|
-
server.once("error", failed);
|
|
459
|
-
server.once("listening", listened);
|
|
460
|
-
server.listen(backlog === void 0 ? listen : {
|
|
461
|
-
...listen,
|
|
462
|
-
backlog
|
|
463
|
-
});
|
|
464
|
-
});
|
|
465
|
-
},
|
|
466
|
-
stopIntake() {
|
|
467
|
-
if (!intakeOpen) return;
|
|
468
|
-
intakeOpen = false;
|
|
469
|
-
intake.abort(/* @__PURE__ */ new Error("the transport stopped its intake"));
|
|
470
|
-
if (!throughDrain()) closeListener();
|
|
471
|
-
closeIdleConnections();
|
|
472
|
-
startSweep();
|
|
473
|
-
},
|
|
474
|
-
drain(deadline, signal) {
|
|
475
|
-
const abort = () => {
|
|
476
|
-
if (!cooperative.signal.aborted) cooperative.abort(signal.reason);
|
|
477
|
-
};
|
|
478
|
-
if (signal.aborted) abort();
|
|
479
|
-
else signal.addEventListener("abort", abort, { once: true });
|
|
480
|
-
if (inFlight() === 0) {
|
|
481
|
-
signal.removeEventListener("abort", abort);
|
|
482
|
-
return Promise.resolve();
|
|
483
|
-
}
|
|
484
|
-
return new Promise((resolve) => {
|
|
485
|
-
let cancel = () => {};
|
|
486
|
-
let unwatch = () => {};
|
|
487
|
-
let unhold = () => {};
|
|
488
|
-
let late = false;
|
|
489
|
-
let ended = false;
|
|
490
|
-
const check = () => {
|
|
491
|
-
if (ended || inFlight() > 0 && (!late || answering())) return;
|
|
492
|
-
ended = true;
|
|
493
|
-
drainers.delete(check);
|
|
494
|
-
cancel();
|
|
495
|
-
unwatch();
|
|
496
|
-
unhold();
|
|
497
|
-
signal.removeEventListener("abort", abort);
|
|
498
|
-
resolve();
|
|
499
|
-
};
|
|
500
|
-
const reached = () => {
|
|
501
|
-
late = true;
|
|
502
|
-
unwatch = watchAnswers(check);
|
|
503
|
-
if (life !== null) {
|
|
504
|
-
unhold = holdLate(life, () => {
|
|
505
|
-
const { running, unflushed } = lateHold();
|
|
506
|
-
return {
|
|
507
|
-
running,
|
|
508
|
-
unflushed
|
|
509
|
-
};
|
|
510
|
-
});
|
|
511
|
-
noteOutside(life, lateHold().outside);
|
|
512
|
-
}
|
|
513
|
-
check();
|
|
514
|
-
};
|
|
515
|
-
drainers.add(check);
|
|
516
|
-
if (deadline <= clock.now()) reached();
|
|
517
|
-
else cancel = clock.after(deadline - clock.now(), reached);
|
|
518
|
-
});
|
|
519
|
-
},
|
|
520
|
-
inFlight,
|
|
521
|
-
close() {
|
|
522
|
-
if (closing !== null) return closing;
|
|
523
|
-
intakeOpen = false;
|
|
524
|
-
if (!intake.signal.aborted) intake.abort(/* @__PURE__ */ new Error("the transport closed"));
|
|
525
|
-
if (!cooperative.signal.aborted) cooperative.abort(/* @__PURE__ */ new Error("the transport closed"));
|
|
526
|
-
sweep?.();
|
|
527
|
-
sweep = null;
|
|
528
|
-
closing = new Promise((resolve) => {
|
|
529
|
-
closedWaiters.add(resolve);
|
|
530
|
-
});
|
|
531
|
-
closeListener();
|
|
532
|
-
if (h2 === null) server.closeAllConnections();
|
|
533
|
-
else for (const session of [...sessions]) session.destroy();
|
|
534
|
-
for (const socket of [...upgraded]) socket.destroy();
|
|
535
|
-
for (const socket of [...sockets]) socket.destroy();
|
|
536
|
-
settled();
|
|
537
|
-
return closing;
|
|
538
|
-
}
|
|
539
|
-
};
|
|
540
|
-
};
|
|
541
|
-
// src/http/probes.ts
|
|
542
|
-
/**
|
|
543
|
-
* These are the four probe kinds, in the sequence of their paths. A probe server and a probe handler
|
|
544
|
-
* answer all four, unless their option `kinds` names fewer.
|
|
545
|
-
*/
|
|
546
|
-
const PROBE_KINDS = Object.freeze([
|
|
547
|
-
"startup",
|
|
548
|
-
"readiness",
|
|
549
|
-
"liveness",
|
|
550
|
-
"report"
|
|
551
|
-
]);
|
|
552
|
-
const named = PROBE_KINDS.map((kind) => `"${kind}"`).join(", ");
|
|
553
|
-
/**
|
|
554
|
-
* This function gives the probe kinds of an option `kinds`: all four when it is undefined, or else a
|
|
555
|
-
* frozen copy. It refuses a value that is not a list, an empty list, an unknown kind and a kind two times.
|
|
556
|
-
*/
|
|
557
|
-
const kindsOf = (kinds) => {
|
|
558
|
-
if (kinds === void 0) return PROBE_KINDS;
|
|
559
|
-
if (!Array.isArray(kinds)) throw new Error(`the probe kinds ${JSON.stringify(kinds)} are not a list of ${named}`);
|
|
560
|
-
if (kinds.length === 0) throw new Error(`the probe kinds are an empty list: name one or more of ${named}`);
|
|
561
|
-
const seen = /* @__PURE__ */ new Set();
|
|
562
|
-
for (const kind of kinds) {
|
|
563
|
-
if (!PROBE_KINDS.includes(kind)) throw new Error(`the probe kind ${JSON.stringify(kind)} is not one of ${named}`);
|
|
564
|
-
if (seen.has(kind)) throw new Error(`the probe kind "${kind}" is two times in the probe kinds`);
|
|
565
|
-
seen.add(kind);
|
|
566
|
-
}
|
|
567
|
-
return Object.freeze([...kinds]);
|
|
568
|
-
};
|
|
569
|
-
const NO_ALIASES = /* @__PURE__ */ new Map();
|
|
570
|
-
/**
|
|
571
|
-
* This function gives the probe kind of each more path of an option `paths`. It refuses a key that is
|
|
572
|
-
* not a probe kind, and a kind that `kinds` does not name. It refuses a path that does not start
|
|
573
|
-
* with `/`, or ends with `/`. It also refuses a path two times, and a path of `PROBE_KINDS` after the prefix.
|
|
574
|
-
*/
|
|
575
|
-
const aliasesOf = (paths, kinds, prefix) => {
|
|
576
|
-
if (paths === void 0) return NO_ALIASES;
|
|
577
|
-
if (paths === null || typeof paths !== "object" || Array.isArray(paths)) throw new Error(`the probe paths ${JSON.stringify(paths)} are not an object of probe kinds`);
|
|
578
|
-
const aliases = /* @__PURE__ */ new Map();
|
|
579
|
-
for (const [key, list] of Object.entries(paths)) {
|
|
580
|
-
const kind = key;
|
|
581
|
-
if (!PROBE_KINDS.includes(kind)) throw new Error(`the probe paths name ${JSON.stringify(key)}, which is not one of ${named}`);
|
|
582
|
-
if (!kinds.includes(kind)) throw new Error(`the probe paths name "${kind}", but the probe kinds do not`);
|
|
583
|
-
if (!Array.isArray(list)) throw new Error(`the probe paths of "${kind}" are not a list`);
|
|
584
|
-
for (const path of list) {
|
|
585
|
-
if (typeof path !== "string" || !path.startsWith("/") || path.length < 2 || path.endsWith("/") || /[?#]/.test(path)) throw new Error(`the probe path ${JSON.stringify(path)} of "${kind}" does not start with "/", ends with "/", or has a query`);
|
|
586
|
-
if (aliases.has(path)) throw new Error(`the probe path "${path}" is two times in the probe paths`);
|
|
587
|
-
if (PROBE_KINDS.some((each) => path === `${prefix}/${each}` || path.startsWith(`${prefix}/${each}/`))) throw new Error(`the probe path "${path}" is a path of a probe kind after the prefix "${prefix}"`);
|
|
588
|
-
aliases.set(path, kind);
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
return aliases;
|
|
592
|
-
};
|
|
593
|
-
/** This function gives the probe kind and the controller of a path, or null for a path that is not a probe. */
|
|
594
|
-
const probeTarget = (path, prefix, kinds, aliases) => {
|
|
595
|
-
const alias = aliases.get(path);
|
|
596
|
-
if (alias !== void 0) return {
|
|
597
|
-
kind: alias,
|
|
598
|
-
controller: void 0
|
|
599
|
-
};
|
|
600
|
-
if (!path.startsWith(`${prefix}/`)) return null;
|
|
601
|
-
const parts = path.slice(prefix.length + 1).split("/");
|
|
602
|
-
const kind = PROBE_KINDS.find((each) => each === parts[0] && kinds.includes(each));
|
|
603
|
-
if (kind === void 0) return null;
|
|
604
|
-
const controller = parts[1];
|
|
605
|
-
if (parts.length > 2 || controller !== void 0 && (kind !== "readiness" || controller === "")) return null;
|
|
606
|
-
return {
|
|
607
|
-
kind,
|
|
608
|
-
controller
|
|
609
|
-
};
|
|
610
|
-
};
|
|
611
|
-
const prefixProblem = (prefix) => prefix === "" || prefix.startsWith("/") && !prefix.endsWith("/") ? null : `the probe prefix "${prefix}" does not start with "/", or it ends with "/"`;
|
|
612
|
-
/** These escapes replace `<`, `>` and `&` in a JSON body. The JSON stays valid, with the same value, and no part of it is markup. */
|
|
613
|
-
const ESCAPES = {
|
|
614
|
-
"<": "\\u003c",
|
|
615
|
-
">": "\\u003e",
|
|
616
|
-
"&": "\\u0026"
|
|
617
|
-
};
|
|
618
|
-
/**
|
|
619
|
-
* This function gives a JSON answer, and its body escapes `<`, `>` and `&`. A body can repeat a part
|
|
620
|
-
* of the path. An example is the name of a controller that the service does not have.
|
|
621
|
-
*/
|
|
622
|
-
const json = (status, body) => ({
|
|
623
|
-
status,
|
|
624
|
-
headers: {
|
|
625
|
-
"content-type": "application/health+json",
|
|
626
|
-
"cache-control": "no-store"
|
|
627
|
-
},
|
|
628
|
-
body: JSON.stringify(body).replace(/[<>&]/g, (char) => ESCAPES[char])
|
|
629
|
-
});
|
|
630
|
-
/**
|
|
631
|
-
* This function gives the response of a probe path from the cache of the health runtime. For a path
|
|
632
|
-
* that is not a probe, it gives null. The paths are `/startup`, `/readiness`, `/liveness` and
|
|
633
|
-
* `/report` after the prefix. `/readiness/<controller>` gives the readiness of one controller.
|
|
634
|
-
* `kinds` names the probes that answer. The path of a kind that it does not name is not a probe.
|
|
635
|
-
*
|
|
636
|
-
* `aliases` gives the probe kind of each more path. A more path of readiness has no controller.
|
|
637
|
-
*/
|
|
638
|
-
const probeResponse = (health, method, path, prefix = "", kinds = PROBE_KINDS, aliases = NO_ALIASES) => {
|
|
639
|
-
const target = probeTarget(path, prefix, kinds, aliases);
|
|
640
|
-
if (target === null) return null;
|
|
641
|
-
const { kind, controller } = target;
|
|
642
|
-
if (method !== "GET" && method !== "HEAD") return {
|
|
643
|
-
status: 405,
|
|
644
|
-
headers: {
|
|
645
|
-
allow: "GET, HEAD",
|
|
646
|
-
"content-length": "0"
|
|
647
|
-
},
|
|
648
|
-
body: ""
|
|
649
|
-
};
|
|
650
|
-
if (health === null || health === void 0) return json(503, {
|
|
651
|
-
status: "fail",
|
|
652
|
-
probe: kind
|
|
653
|
-
});
|
|
654
|
-
try {
|
|
655
|
-
const answer = health.probe(kind, controller === void 0 ? void 0 : decodeURIComponent(controller));
|
|
656
|
-
return {
|
|
657
|
-
...json(answer.status, answer.body),
|
|
658
|
-
headers: {
|
|
659
|
-
"content-type": answer.contentType,
|
|
660
|
-
"cache-control": "no-store"
|
|
661
|
-
}
|
|
662
|
-
};
|
|
663
|
-
} catch {
|
|
664
|
-
return json(404, {
|
|
665
|
-
status: "fail",
|
|
666
|
-
probe: kind,
|
|
667
|
-
controller
|
|
668
|
-
});
|
|
669
|
-
}
|
|
670
|
-
};
|
|
671
|
-
/**
|
|
672
|
-
* This function writes a probe response. Each response gets `X-Content-Type-Options: nosniff`, thus a
|
|
673
|
-
* browser does not read it as a different type. A 503 gets `Retry-After`, when the writer has the time of a retry.
|
|
674
|
-
*/
|
|
675
|
-
const write = (req, res, response, retryAfter) => {
|
|
676
|
-
const retry = response.status === 503 && retryAfter !== void 0 ? { "retry-after": retryAfter } : {};
|
|
677
|
-
const length = String(Buffer.byteLength(response.body));
|
|
678
|
-
res.writeHead(response.status, {
|
|
679
|
-
...response.headers,
|
|
680
|
-
...retry,
|
|
681
|
-
"x-content-type-options": "nosniff",
|
|
682
|
-
"content-length": length
|
|
683
|
-
});
|
|
684
|
-
res.end(req.method === "HEAD" ? void 0 : response.body);
|
|
685
|
-
};
|
|
686
|
-
/**
|
|
687
|
-
* This function gives a request handler that answers the probes on the port of the application. It
|
|
688
|
-
* answers until `close transports`, thus its mount keeps the listener open through the drain. A path
|
|
689
|
-
* that is not a probe goes to the next handler. Each 503 gets the `Retry-After` of the context.
|
|
690
|
-
*/
|
|
691
|
-
const probeHandler = (health, options) => {
|
|
692
|
-
const problem = prefixProblem(options.prefix);
|
|
693
|
-
if (problem !== null) throw new Error(problem);
|
|
694
|
-
const kinds = kindsOf(options.kinds);
|
|
695
|
-
const aliases = aliasesOf(options.paths, kinds, options.prefix);
|
|
696
|
-
const handler = (req, res, context) => {
|
|
697
|
-
const runtime = typeof health === "function" ? health() : health;
|
|
698
|
-
const response = probeResponse(runtime, req.method, pathOf(req.url), options.prefix, kinds, aliases);
|
|
699
|
-
if (response === null) return false;
|
|
700
|
-
const retryAfter = context?.retryAfter === void 0 ? void 0 : retryAfterOf({ server_retry_after: context.retryAfter }, "probeHandler");
|
|
701
|
-
write(req, res, response, retryAfter);
|
|
702
|
-
return true;
|
|
703
|
-
};
|
|
704
|
-
return Object.assign(handler, { until: "close transports" });
|
|
705
|
-
};
|
|
706
|
-
/**
|
|
707
|
-
* This function makes a health server on a port of its own (S6 decision D5). It starts first and
|
|
708
|
-
* closes last, thus the probes answer through the whole drain. Each probe answers from the cache, and
|
|
709
|
-
* each 503 gets the `Retry-After` of `server_retry_after`.
|
|
710
|
-
*/
|
|
711
|
-
const probeServer = (options) => {
|
|
712
|
-
const { prefix = "", server = createServer(), server_retry_after, kinds: chosen, paths, ...listen } = options;
|
|
713
|
-
const retryAfter = retryAfterOf({ server_retry_after }, "probeServer");
|
|
714
|
-
const problem = prefixProblem(prefix);
|
|
715
|
-
if (problem !== null) throw new Error(problem);
|
|
716
|
-
const kinds = kindsOf(chosen);
|
|
717
|
-
const aliases = aliasesOf(paths, kinds, prefix);
|
|
718
|
-
if (server.listenerCount("request") > 0) throw new Error("the probe server has a request listener of its own");
|
|
719
|
-
let health = null;
|
|
720
|
-
let closing = null;
|
|
721
|
-
const sockets = /* @__PURE__ */ new Set();
|
|
722
|
-
server.on("connection", (socket) => {
|
|
723
|
-
sockets.add(socket);
|
|
724
|
-
socket.once("close", () => sockets.delete(socket));
|
|
725
|
-
});
|
|
726
|
-
server.on("request", (req, res) => {
|
|
727
|
-
const response = probeResponse(health, req.method, pathOf(req.url), prefix, kinds, aliases);
|
|
728
|
-
write(req, res, response ?? {
|
|
729
|
-
status: 404,
|
|
730
|
-
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
731
|
-
body: "Not Found"
|
|
732
|
-
}, retryAfter);
|
|
733
|
-
});
|
|
734
|
-
return {
|
|
735
|
-
server,
|
|
736
|
-
listen(runtime) {
|
|
737
|
-
health = runtime;
|
|
738
|
-
if (server.listening) return Promise.resolve();
|
|
739
|
-
return new Promise((resolve, reject) => {
|
|
740
|
-
const failed = (error) => {
|
|
741
|
-
server.off("listening", listened);
|
|
742
|
-
reject(error);
|
|
743
|
-
};
|
|
744
|
-
const listened = () => {
|
|
745
|
-
server.off("error", failed);
|
|
746
|
-
resolve();
|
|
747
|
-
};
|
|
748
|
-
server.once("error", failed);
|
|
749
|
-
server.once("listening", listened);
|
|
750
|
-
server.listen(listen);
|
|
751
|
-
});
|
|
752
|
-
},
|
|
753
|
-
close() {
|
|
754
|
-
if (closing !== null) return closing;
|
|
755
|
-
closing = new Promise((resolve) => {
|
|
756
|
-
if (!server.listening) {
|
|
757
|
-
resolve();
|
|
758
|
-
return;
|
|
759
|
-
}
|
|
760
|
-
server.close(() => resolve());
|
|
761
|
-
server.closeAllConnections();
|
|
762
|
-
for (const socket of [...sockets]) socket.destroy();
|
|
763
|
-
});
|
|
764
|
-
return closing;
|
|
765
|
-
}
|
|
766
|
-
};
|
|
767
|
-
};
|
|
768
|
-
// src/http/outcome.ts
|
|
769
|
-
const JSON_TYPE = "application/json; charset=utf-8";
|
|
770
|
-
/**
|
|
771
|
-
* This function gives an end as a record for a body: its kind and the count of its items. A cut and
|
|
772
|
-
* a refusal also give their cause, and if the caller can send the request again. A failure gives
|
|
773
|
-
* no detail.
|
|
774
|
-
*/
|
|
775
|
-
const endRecord = (end) => {
|
|
776
|
-
if (end.kind === "refused" || end.kind === "cut") return {
|
|
777
|
-
end: end.kind,
|
|
778
|
-
delivered: end.delivered,
|
|
779
|
-
retryable: end.retryable,
|
|
780
|
-
cause: end.cause
|
|
781
|
-
};
|
|
782
|
-
return {
|
|
783
|
-
end: end.kind,
|
|
784
|
-
delivered: end.delivered
|
|
785
|
-
};
|
|
786
|
-
};
|
|
787
|
-
/** This format writes each item and the end as one line of JSON (NDJSON). */
|
|
788
|
-
const ndjson = {
|
|
789
|
-
contentType: "application/x-ndjson; charset=utf-8",
|
|
790
|
-
item: (value) => `${JSON.stringify(value)}\n`,
|
|
791
|
-
end: (end) => `${JSON.stringify(endRecord(end))}\n`
|
|
792
|
-
};
|
|
793
|
-
/** This format writes each item as an event of server-sent events, and the end as the event `end`. */
|
|
794
|
-
const sse = {
|
|
795
|
-
contentType: "text/event-stream; charset=utf-8",
|
|
796
|
-
item: (value) => `data: ${JSON.stringify(value)}\n\n`,
|
|
797
|
-
end: (end) => `event: end\ndata: ${JSON.stringify(endRecord(end))}\n\n`
|
|
798
|
-
};
|
|
799
|
-
const valueResponse = (value) => {
|
|
800
|
-
if (value === void 0) return {
|
|
801
|
-
status: 204,
|
|
802
|
-
headers: {},
|
|
803
|
-
body: ""
|
|
804
|
-
};
|
|
805
|
-
if (typeof value === "string") return {
|
|
806
|
-
status: 200,
|
|
807
|
-
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
808
|
-
body: value
|
|
809
|
-
};
|
|
810
|
-
if (value instanceof Uint8Array) return {
|
|
811
|
-
status: 200,
|
|
812
|
-
headers: { "content-type": "application/octet-stream" },
|
|
813
|
-
body: value
|
|
814
|
-
};
|
|
815
|
-
return {
|
|
816
|
-
status: 200,
|
|
817
|
-
headers: { "content-type": JSON_TYPE },
|
|
818
|
-
body: JSON.stringify(value)
|
|
819
|
-
};
|
|
820
|
-
};
|
|
821
|
-
const merge = (base, part) => part === void 0 ? base : {
|
|
822
|
-
status: part.status ?? base.status,
|
|
823
|
-
headers: {
|
|
824
|
-
...base.headers,
|
|
825
|
-
...part.headers
|
|
826
|
-
},
|
|
827
|
-
body: part.body ?? base.body
|
|
828
|
-
};
|
|
829
|
-
const keeps = (keepAlive) => typeof keepAlive === "function" ? keepAlive() : keepAlive;
|
|
830
|
-
/**
|
|
831
|
-
* This function applies the rules of the headers to a response. Each 503 gets `Retry-After`, and a
|
|
832
|
-
* 500 gets none. The response closes its connection while the service cannot keep it.
|
|
833
|
-
*/
|
|
834
|
-
const ruled = (response, retryAfter, keepAlive) => {
|
|
835
|
-
const headers = { ...response.headers };
|
|
836
|
-
if (response.status === 503 && headers["retry-after"] === void 0) headers["retry-after"] = String(Math.max(0, Math.ceil(valueIn(retryAfter, "s"))));
|
|
837
|
-
if (response.status === 500) delete headers["retry-after"];
|
|
838
|
-
if (!keeps(keepAlive)) headers["connection"] = "close";
|
|
839
|
-
return {
|
|
840
|
-
...response,
|
|
841
|
-
headers
|
|
842
|
-
};
|
|
843
|
-
};
|
|
844
|
-
/** This function gives the status response of an end before the first byte of the body. */
|
|
845
|
-
const endStatus = (end, options) => {
|
|
846
|
-
const body = JSON.stringify(endRecord(end));
|
|
847
|
-
switch (end.kind) {
|
|
848
|
-
case "refused": return {
|
|
849
|
-
status: 503,
|
|
850
|
-
headers: { "content-type": JSON_TYPE },
|
|
851
|
-
body
|
|
852
|
-
};
|
|
853
|
-
case "cut": return {
|
|
854
|
-
status: end.status ?? (end.retryable ? 503 : 500),
|
|
855
|
-
headers: { "content-type": JSON_TYPE },
|
|
856
|
-
body
|
|
857
|
-
};
|
|
858
|
-
case "failed": return merge({
|
|
859
|
-
status: 500,
|
|
860
|
-
headers: { "content-type": JSON_TYPE },
|
|
861
|
-
body
|
|
862
|
-
}, options.failed?.(end.error));
|
|
863
|
-
case "done": return {
|
|
864
|
-
status: 204,
|
|
865
|
-
headers: {},
|
|
866
|
-
body: ""
|
|
867
|
-
};
|
|
868
|
-
}
|
|
869
|
-
};
|
|
870
|
-
/**
|
|
871
|
-
* This function maps a unary request to its response, from its items and its end (S6 A12 and A13).
|
|
872
|
-
* - One value and the end `done`: 200 with the value, or the response of the `done` hook.
|
|
873
|
-
* - No value and the end `done`: 204. More than one value: 500, because the route is not a stream.
|
|
874
|
-
* - `refused`: 503. The work did not start, thus the caller can send it again. The service did not
|
|
875
|
-
* start, it stopped its intake, or a controller is not ready.
|
|
876
|
-
* - `cut`: 503 for a route whose callers can send it again (S6 A12), and 500 for each other route.
|
|
877
|
-
* - `failed`: 500 with no detail, or the response of the `failed` hook. A failure of the route is not a 503.
|
|
878
|
-
*
|
|
879
|
-
* Each 503 gets `Retry-After` (RFC 9110), and a 500 gets none. Each response gets `Connection: close`
|
|
880
|
-
* while the service cannot keep the connection.
|
|
881
|
-
*/
|
|
882
|
-
const outcomeResponse = (items, end, options) => {
|
|
883
|
-
let response;
|
|
884
|
-
if (end.kind !== "done") response = endStatus(end, options);
|
|
885
|
-
else if (items.length === 1) response = merge(valueResponse(items[0]), options.done?.(items[0]));
|
|
886
|
-
else if (items.length === 0) response = endStatus(end, options);
|
|
887
|
-
else response = endStatus({
|
|
888
|
-
kind: "failed",
|
|
889
|
-
error: /* @__PURE__ */ new Error(`the work gave ${items.length} values, and a unary response has one`),
|
|
890
|
-
delivered: items.length
|
|
891
|
-
}, options);
|
|
892
|
-
return ruled(response, options.retryAfter, options.keepAlive);
|
|
893
|
-
};
|
|
894
|
-
/**
|
|
895
|
-
* This function gives the response of a take that a keyed limiter refused. The work did not start.
|
|
896
|
-
* - A wait refusal (`limit`, `cap` or `store`) gives 429 (RFC 6585), with `Retry-After` in whole
|
|
897
|
-
* seconds, rounded up (RFC 9110). The body tells the cause and the same whole seconds, but not the
|
|
898
|
-
* failure of a store. The caller can send the request again.
|
|
899
|
-
* - A capacity refusal gives 413 (RFC 9110) with no `Retry-After`, because no wait lets the take in.
|
|
900
|
-
* The body tells the units and the capacity, thus the caller can split the request into parts.
|
|
901
|
-
*/
|
|
902
|
-
const limitedResponse = (refused) => {
|
|
903
|
-
if (refused.cause === "capacity") return {
|
|
904
|
-
status: 413,
|
|
905
|
-
headers: { "content-type": JSON_TYPE },
|
|
906
|
-
body: JSON.stringify({
|
|
907
|
-
end: "refused",
|
|
908
|
-
delivered: 0,
|
|
909
|
-
retryable: false,
|
|
910
|
-
cause: `the limiter refused the take: capacity, ${refused.units} units over a capacity of ${refused.capacity}`,
|
|
911
|
-
units: refused.units,
|
|
912
|
-
capacity: refused.capacity
|
|
913
|
-
})
|
|
914
|
-
};
|
|
915
|
-
const seconds = retryAfterSeconds(refused.retryAfter);
|
|
916
|
-
return {
|
|
917
|
-
status: 429,
|
|
918
|
-
headers: {
|
|
919
|
-
"content-type": JSON_TYPE,
|
|
920
|
-
"retry-after": String(seconds)
|
|
921
|
-
},
|
|
922
|
-
body: JSON.stringify({
|
|
923
|
-
end: "refused",
|
|
924
|
-
delivered: 0,
|
|
925
|
-
retryable: true,
|
|
926
|
-
cause: `the limiter refused the take: ${refused.cause}`,
|
|
927
|
-
retryAfter: seconds
|
|
928
|
-
})
|
|
929
|
-
};
|
|
930
|
-
};
|
|
931
|
-
/** This function writes a whole response of `node:http`. A response whose headers went gets no second status: it is destroyed. */
|
|
932
|
-
const writeWhole = (res, response) => {
|
|
933
|
-
if (res.headersSent) {
|
|
934
|
-
res.destroy();
|
|
935
|
-
return;
|
|
936
|
-
}
|
|
937
|
-
if (response.headers["connection"] === "close") res.shouldKeepAlive = false;
|
|
938
|
-
if (response.status === 204) {
|
|
939
|
-
res.writeHead(204, response.headers);
|
|
940
|
-
res.end();
|
|
941
|
-
return;
|
|
942
|
-
}
|
|
943
|
-
const length = typeof response.body === "string" ? Buffer.byteLength(response.body) : response.body.byteLength;
|
|
944
|
-
res.writeHead(response.status, {
|
|
945
|
-
...response.headers,
|
|
946
|
-
"content-length": String(length)
|
|
947
|
-
});
|
|
948
|
-
res.end(response.body);
|
|
949
|
-
};
|
|
950
|
-
/**
|
|
951
|
-
* This function writes the stream of a request to a response of `node:http`, and gives its end. It
|
|
952
|
-
* gives null when the client closed the connection first. Then the work stops through `return()`.
|
|
953
|
-
* - Unary (no format): it waits for the end, and it writes the status and the body of `outcomeResponse`.
|
|
954
|
-
* - Stream: the status 200 goes with the first item, then each item goes as it comes, then the end
|
|
955
|
-
* goes in the body (in-band). The next item waits until the client reads, thus a slow client
|
|
956
|
-
* slows the work. An end before the first item gets a status, as a unary end does.
|
|
957
|
-
* - The answer to come: until it writes the end, the response holds the drain of `httpTransport` past
|
|
958
|
-
* its deadline. The cut of the drain gives that end, and the drain waits until the end goes out.
|
|
959
|
-
* Only a stream of `life.request` of the lifecycle of the transport holds the drain.
|
|
960
|
-
*/
|
|
961
|
-
const writeOutcome = async (res, stream, options) => {
|
|
962
|
-
const iterator = stream[Symbol.asyncIterator]();
|
|
963
|
-
let gone = () => {};
|
|
964
|
-
const closed = new Promise((resolve) => {
|
|
965
|
-
gone = () => resolve("gone");
|
|
966
|
-
});
|
|
967
|
-
const onClose = () => {
|
|
968
|
-
if (!res.writableFinished) gone();
|
|
969
|
-
};
|
|
970
|
-
res.once("close", onClose);
|
|
971
|
-
if (res.destroyed) gone();
|
|
972
|
-
const leave = async () => {
|
|
973
|
-
await iterator.return?.();
|
|
974
|
-
return null;
|
|
975
|
-
};
|
|
976
|
-
const next = async () => {
|
|
977
|
-
const step = await Promise.race([iterator.next(), closed]);
|
|
978
|
-
if (step === "gone") return step;
|
|
979
|
-
if (step.done === true) throw new Error("the stream of the request ended without its end");
|
|
980
|
-
return step.value;
|
|
981
|
-
};
|
|
982
|
-
/** This function writes one part of the body, and waits while the client reads slower than the work. */
|
|
983
|
-
const send = async (chunk) => {
|
|
984
|
-
if (res.write(chunk)) return true;
|
|
985
|
-
const drained = new Promise((resolve) => res.once("drain", () => resolve("drained")));
|
|
986
|
-
return await Promise.race([drained, closed]) === "drained";
|
|
987
|
-
};
|
|
988
|
-
const answered = markAnswer(res, ownerOf(stream));
|
|
989
|
-
try {
|
|
990
|
-
const format = options.stream;
|
|
991
|
-
if (format === void 0) {
|
|
992
|
-
const items = [];
|
|
993
|
-
for (;;) {
|
|
994
|
-
const event = await next();
|
|
995
|
-
if (event === "gone") return await leave();
|
|
996
|
-
if (event.kind === "item") {
|
|
997
|
-
items.push(event.value);
|
|
998
|
-
continue;
|
|
999
|
-
}
|
|
1000
|
-
writeWhole(res, outcomeResponse(items, event, options));
|
|
1001
|
-
return event;
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
const first = await next();
|
|
1005
|
-
if (first === "gone") return await leave();
|
|
1006
|
-
if (first.kind !== "item") {
|
|
1007
|
-
if (first.kind === "done") writeWhole(res, ruled({
|
|
1008
|
-
status: 200,
|
|
1009
|
-
headers: {
|
|
1010
|
-
"content-type": format.contentType,
|
|
1011
|
-
"cache-control": "no-store"
|
|
1012
|
-
},
|
|
1013
|
-
body: format.end(first)
|
|
1014
|
-
}, options.retryAfter, options.keepAlive));
|
|
1015
|
-
else writeWhole(res, outcomeResponse([], first, options));
|
|
1016
|
-
return first;
|
|
1017
|
-
}
|
|
1018
|
-
if (res.headersSent) {
|
|
1019
|
-
res.destroy();
|
|
1020
|
-
return await leave();
|
|
1021
|
-
}
|
|
1022
|
-
const head = ruled({
|
|
1023
|
-
status: 200,
|
|
1024
|
-
headers: {
|
|
1025
|
-
"content-type": format.contentType,
|
|
1026
|
-
"cache-control": "no-store"
|
|
1027
|
-
},
|
|
1028
|
-
body: ""
|
|
1029
|
-
}, options.retryAfter, options.keepAlive);
|
|
1030
|
-
if (head.headers["connection"] === "close") res.shouldKeepAlive = false;
|
|
1031
|
-
res.writeHead(200, head.headers);
|
|
1032
|
-
if (!await send(format.item(first.value))) return await leave();
|
|
1033
|
-
for (;;) {
|
|
1034
|
-
const event = await next();
|
|
1035
|
-
if (event === "gone") return await leave();
|
|
1036
|
-
if (event.kind === "item") {
|
|
1037
|
-
if (!await send(format.item(event.value))) return await leave();
|
|
1038
|
-
continue;
|
|
1039
|
-
}
|
|
1040
|
-
res.end(format.end(event));
|
|
1041
|
-
return event;
|
|
1042
|
-
}
|
|
1043
|
-
} finally {
|
|
1044
|
-
res.off("close", onClose);
|
|
1045
|
-
answered();
|
|
1046
|
-
}
|
|
1047
|
-
};
|
|
1048
|
-
/**
|
|
1049
|
-
* This function gives a request handler that does each request of a route through `life.request`
|
|
1050
|
-
* (S6 A12 and A13). The transport gives the lifecycle and `server_retry_after` through the context.
|
|
1051
|
-
* - A route name takes a request whose method and path are that name, for example `POST /orders`.
|
|
1052
|
-
* A function gives the name of a route or of a pattern, or null for a request of another handler.
|
|
1053
|
-
* - Before the start of the transport, each request gets a retryable 503.
|
|
1054
|
-
* - The response is unary, or a stream with the option `stream`, as `writeOutcome` writes it.
|
|
1055
|
-
*/
|
|
1056
|
-
const handle = (controller, route, work, options = {}) => {
|
|
1057
|
-
const nameOf = (req) => {
|
|
1058
|
-
if (typeof route === "function") return route(req);
|
|
1059
|
-
return `${req.method ?? "GET"} ${pathOf(req.url)}` === route ? route : null;
|
|
1060
|
-
};
|
|
1061
|
-
return async (req, res, context) => {
|
|
1062
|
-
const name = nameOf(req);
|
|
1063
|
-
if (name === null) return false;
|
|
1064
|
-
const life = context.life;
|
|
1065
|
-
const written = {
|
|
1066
|
-
...options,
|
|
1067
|
-
keepAlive: () => life !== null && (context.keepAlive?.() ?? life.keepAlive()),
|
|
1068
|
-
retryAfter: context.retryAfter
|
|
1069
|
-
};
|
|
1070
|
-
if (life === null) {
|
|
1071
|
-
writeWhole(res, outcomeResponse([], {
|
|
1072
|
-
kind: "refused",
|
|
1073
|
-
status: 503,
|
|
1074
|
-
retryable: true,
|
|
1075
|
-
cause: "the transport has not started",
|
|
1076
|
-
delivered: 0
|
|
1077
|
-
}, written));
|
|
1078
|
-
return true;
|
|
1079
|
-
}
|
|
1080
|
-
const given = options.detail === void 0 ? {} : { detail: options.detail(req) };
|
|
1081
|
-
await writeOutcome(res, ownStream(life.request(controller, name, (signal) => work(req, signal), given), life), written);
|
|
1082
|
-
return true;
|
|
1083
|
-
};
|
|
1084
|
-
};
|
|
1
|
+
import { httpTransport, pathOf } from "./http/transport.js";
|
|
2
|
+
import { PROBE_KINDS, probeHandler, probeResponse, probeServer } from "./http/probes.js";
|
|
3
|
+
import { endRecord, handle, limitedResponse, ndjson, outcomeResponse, sse, writeOutcome } from "./http/outcome.js";
|
|
1085
4
|
export { PROBE_KINDS, endRecord, handle, httpTransport, limitedResponse, ndjson, outcomeResponse, pathOf, probeHandler, probeResponse, probeServer, sse, writeOutcome };
|
|
1086
|
-
|
|
1087
|
-
//# sourceMappingURL=http.js.map
|