@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
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// src/http/answers.ts
|
|
2
|
+
const marked = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
const watchers = /* @__PURE__ */ new Set();
|
|
4
|
+
/**
|
|
5
|
+
* This function marks a response that waits for the end of its request. `owner` is the lifecycle
|
|
6
|
+
* that made the stream, or null. It gives the function that removes the mark.
|
|
7
|
+
*/
|
|
8
|
+
const markAnswer = (res, owner) => {
|
|
9
|
+
marked.set(res, owner);
|
|
10
|
+
return () => {
|
|
11
|
+
if (!marked.delete(res)) return;
|
|
12
|
+
for (const watcher of [...watchers]) watcher();
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* This function gives the mark of a response: the lifecycle that made its stream. It gives null for a
|
|
17
|
+
* stream outside each lifecycle, and undefined for a response with no mark.
|
|
18
|
+
*/
|
|
19
|
+
const answerOwner = (res) => marked.get(res);
|
|
20
|
+
/** This function starts `watcher` after each removal of a mark. It gives the function that stops it. */
|
|
21
|
+
const watchAnswers = (watcher) => {
|
|
22
|
+
watchers.add(watcher);
|
|
23
|
+
return () => {
|
|
24
|
+
watchers.delete(watcher);
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
export { answerOwner, markAnswer, watchAnswers };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=answers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"answers.js","names":[],"sources":["../../src/http/answers.ts"],"sourcesContent":["// The answers that the request tracking still writes (SYS-29). `writeOutcome` marks each response\n// while it waits for the end of its request, with the lifecycle that made the stream. At the deadline\n// of its drain, the transport waits for each response of its own lifecycle: the cut of the drain gives\n// that end at the same time. A stream of another lifecycle, or of none, does not hold the drain.\n\nconst marked = new WeakMap<object, object | null>();\nconst watchers = new Set<() => void>();\n\n/**\n * This function marks a response that waits for the end of its request. `owner` is the lifecycle\n * that made the stream, or null. It gives the function that removes the mark.\n */\nexport const markAnswer = (res: object, owner: object | null): (() => void) => {\n marked.set(res, owner);\n return () => {\n if (!marked.delete(res)) return;\n for (const watcher of [...watchers]) watcher();\n };\n};\n\n/**\n * This function gives the mark of a response: the lifecycle that made its stream. It gives null for a\n * stream outside each lifecycle, and undefined for a response with no mark.\n */\nexport const answerOwner = (res: object): object | null | undefined => marked.get(res);\n\n/** This function starts `watcher` after each removal of a mark. It gives the function that stops it. */\nexport const watchAnswers = (watcher: () => void): (() => void) => {\n watchers.add(watcher);\n return () => {\n watchers.delete(watcher);\n };\n};\n"],"mappings":";AAKA,MAAM,yBAAS,IAAI,QAA+B;AAClD,MAAM,2BAAW,IAAI,IAAgB;;;;;AAMrC,MAAa,cAAc,KAAa,UAAuC;CAC7E,OAAO,IAAI,KAAK,KAAK;CACrB,aAAa;EACX,IAAI,CAAC,OAAO,OAAO,GAAG,GAAG;EACzB,KAAK,MAAM,WAAW,CAAC,GAAG,QAAQ,GAAG,QAAQ;CAC/C;AACF;;;;;AAMA,MAAa,eAAe,QAA2C,OAAO,IAAI,GAAG;;AAGrF,MAAa,gBAAgB,YAAsC;CACjE,SAAS,IAAI,OAAO;CACpB,aAAa;EACX,SAAS,OAAO,OAAO;CACzB;AACF"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import "node:events";
|
|
2
|
+
// src/http/fake-server.ts
|
|
3
|
+
/** This function makes a pushed source, a stream of a work for the tests of a stream. */
|
|
4
|
+
const pushedSource = () => {
|
|
5
|
+
const queue = [];
|
|
6
|
+
let wake = null;
|
|
7
|
+
let failure = null;
|
|
8
|
+
let returned = false;
|
|
9
|
+
const poke = () => {
|
|
10
|
+
wake?.();
|
|
11
|
+
wake = null;
|
|
12
|
+
};
|
|
13
|
+
return {
|
|
14
|
+
iterable: { [Symbol.asyncIterator]: () => ({
|
|
15
|
+
async next() {
|
|
16
|
+
for (;;) {
|
|
17
|
+
if (failure !== null) throw failure;
|
|
18
|
+
if (returned) return {
|
|
19
|
+
value: void 0,
|
|
20
|
+
done: true
|
|
21
|
+
};
|
|
22
|
+
const step = queue.shift();
|
|
23
|
+
if (step !== void 0) return step;
|
|
24
|
+
await new Promise((resolve) => wake = resolve);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
async return() {
|
|
28
|
+
returned = true;
|
|
29
|
+
poke();
|
|
30
|
+
return {
|
|
31
|
+
value: void 0,
|
|
32
|
+
done: true
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
}) },
|
|
36
|
+
push: (value) => {
|
|
37
|
+
queue.push({
|
|
38
|
+
value,
|
|
39
|
+
done: false
|
|
40
|
+
});
|
|
41
|
+
poke();
|
|
42
|
+
},
|
|
43
|
+
finish: () => {
|
|
44
|
+
queue.push({
|
|
45
|
+
value: void 0,
|
|
46
|
+
done: true
|
|
47
|
+
});
|
|
48
|
+
poke();
|
|
49
|
+
},
|
|
50
|
+
fail: (error) => {
|
|
51
|
+
failure = error;
|
|
52
|
+
poke();
|
|
53
|
+
},
|
|
54
|
+
get returned() {
|
|
55
|
+
return returned;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
export { pushedSource };
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=fake-server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fake-server.js","names":[],"sources":["../../src/http/fake-server.ts"],"sourcesContent":["// A fake server of node:http for the unit tests: no socket and no port. It gives the events and the\n// methods that the transport and the probe server use, as Node gives them. The tests that use real\n// sockets run in CI only (HTTP_IT=1).\n\nimport { EventEmitter } from \"node:events\";\nimport type { Server } from \"node:http\";\n\n/** A fake socket is the stream of one fake connection. Its close comes on the next tick, as in Node. */\nexport class FakeSocket extends EventEmitter {\n destroyed = false;\n readonly written: string[] = [];\n /** This flag tells if the client stopped its reads. Then the bytes of an ended response do not go. */\n paused = false;\n private readonly reads: Array<() => void> = [];\n /** This method stops the reads of the client, as a client that does not read its socket. */\n pause(): this {\n this.paused = true;\n return this;\n }\n /** This method starts the reads of the client again: each ended response finishes. */\n resume(): this {\n this.paused = false;\n for (const read of this.reads.splice(0)) read();\n return this;\n }\n /** This method starts `read` when the client reads the bytes: at once, or at the next `resume()`. */\n whenRead(read: () => void): void {\n if (this.paused) this.reads.push(read);\n else read();\n }\n write(data: string): boolean {\n if (!this.destroyed) this.written.push(data);\n return true;\n }\n end(data?: string): this {\n if (data !== undefined) this.write(data);\n this.destroy();\n return this;\n }\n destroy(): this {\n if (this.destroyed) return this;\n this.destroyed = true;\n process.nextTick(() => this.emit(\"close\", false));\n return this;\n }\n}\n\n/** A fake response answers one fake request. It uses its own `writeHead` for implicit headers, as Node does. */\nexport class FakeResponse extends EventEmitter {\n statusCode = 200;\n headersSent = false;\n writableEnded = false;\n writableFinished = false;\n /** This flag is the flag of Node that `closeIdleConnections` reads: true from the `end()` of the response. */\n finished = false;\n shouldKeepAlive = true;\n readonly headers: Map<string, string> = new Map();\n readonly chunks: string[] = [];\n constructor(readonly socket: FakeSocket) {\n super();\n }\n setHeader(name: string, value: string | number): this {\n this.headers.set(name.toLowerCase(), String(value));\n return this;\n }\n getHeader(name: string): string | undefined {\n return this.headers.get(name.toLowerCase());\n }\n hasHeader(name: string): boolean {\n return this.headers.has(name.toLowerCase());\n }\n removeHeader(name: string): void {\n this.headers.delete(name.toLowerCase());\n }\n /** This method takes the forms of Node: a status, a status message or not, and the headers as an object or a flat list. */\n writeHead(status: number, message?: string | Readonly<Record<string, string>> | readonly string[], given?: Readonly<Record<string, string>> | readonly string[]): this {\n if (this.headersSent) throw new Error(\"the headers went already\");\n this.statusCode = status;\n const headers = typeof message === \"string\" ? given : message;\n if (Array.isArray(headers)) for (let at = 0; at + 1 < headers.length; at += 2) this.setHeader(headers[at]!, headers[at + 1]!);\n else for (const [name, value] of Object.entries(headers ?? {})) this.setHeader(name, value as string);\n // Node closes the connection after the response when it cannot keep it\n if (!this.shouldKeepAlive) this.setHeader(\"connection\", \"close\");\n this.headersSent = true;\n return this;\n }\n write(chunk: string | Uint8Array): boolean {\n if (!this.headersSent) this.writeHead(this.statusCode);\n this.chunks.push(typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString());\n return true;\n }\n /**\n * This method ends the response. Its bytes go when the client reads them, and then `finish` comes.\n * A destroyed socket takes no bytes, thus the client does not get the answer, as in Node.\n */\n end(chunk?: string | Uint8Array): this {\n if (this.writableEnded) return this;\n if (chunk !== undefined) this.write(chunk);\n else if (!this.headersSent) this.writeHead(this.statusCode);\n this.writableEnded = true;\n this.finished = true;\n this.socket.whenRead(() => {\n if (this.socket.destroyed) return;\n this.writableFinished = true;\n this.emit(\"finish\");\n process.nextTick(() => this.emit(\"close\"));\n });\n return this;\n }\n destroy(): this {\n this.socket.destroy();\n return this;\n }\n /** This flag tells if the socket of the response is destroyed. */\n get destroyed(): boolean {\n return this.socket.destroyed;\n }\n /** This flag tells if the connection closes after the response. */\n get last(): boolean {\n return !this.shouldKeepAlive || this.getHeader(\"connection\") === \"close\";\n }\n}\n\n/** A fake answer is what the client of a fake request gets. */\nexport interface FakeAnswer {\n readonly status: number;\n readonly headers: ReadonlyMap<string, string>;\n readonly body: string;\n}\n\n/** A fake connection is one client connection to the fake server. */\nexport class FakeConnection {\n idle = true;\n upgraded = false;\n /** This response is the response of the last request on the connection, for a test that reads a stream as it comes. */\n response: FakeResponse | null = null;\n constructor(\n readonly server: FakeServer,\n readonly socket: FakeSocket,\n ) {}\n /** This method sends a request on the connection, and gives the answer, or an error when the connection closes first. */\n request(url: string, method = \"GET\", headers: Readonly<Record<string, string>> = {}): Promise<FakeAnswer> {\n if (this.socket.destroyed) return Promise.reject(new Error(\"ECONNRESET: the connection is closed\"));\n this.idle = false;\n const req = Object.assign(new EventEmitter(), { url, method, headers });\n const res = new FakeResponse(this.socket);\n this.response = res;\n return new Promise<FakeAnswer>((resolve, reject) => {\n const lost = (): void => reject(new Error(\"ECONNRESET: the connection closed before the answer\"));\n this.socket.once(\"close\", lost);\n res.once(\"finish\", () => {\n this.socket.off(\"close\", lost);\n resolve({ status: res.statusCode, headers: new Map(res.headers), body: res.chunks.join(\"\") });\n if (res.last) this.socket.destroy();\n else this.idle = true;\n });\n // a socket that closes before the bytes of the response went closes the response too\n this.socket.once(\"close\", () => {\n if (!res.writableFinished) res.emit(\"close\");\n });\n this.server.emit(\"request\", req, res);\n });\n }\n /** This method sends an upgrade request on the connection. The server then owns the socket. */\n upgrade(url: string): FakeSocket {\n this.idle = false;\n this.upgraded = true;\n const req = Object.assign(new EventEmitter(), { url, method: \"GET\", headers: { upgrade: \"websocket\" } });\n this.server.emit(\"upgrade\", req, this.socket, Buffer.alloc(0));\n return this.socket;\n }\n}\n\n/** A fake server is a server of `node:http` with no socket. A test connects to it and sends requests. */\nexport class FakeServer extends EventEmitter {\n listening = false;\n keepAliveTimeout = 5000;\n keepAliveTimeoutBuffer = 1000;\n readonly listens: unknown[] = [];\n readonly connections: Set<FakeConnection> = new Set();\n failListen: Error | null = null;\n private closing = false;\n listen(options: unknown): this {\n this.listens.push(options);\n process.nextTick(() => {\n if (this.failListen !== null) {\n this.emit(\"error\", this.failListen);\n return;\n }\n this.listening = true;\n this.closing = false;\n this.emit(\"listening\");\n });\n return this;\n }\n close(done?: (error?: Error) => void): this {\n if (done !== undefined) this.once(\"close\", () => done());\n this.listening = false;\n this.closing = true;\n this.closeIdleConnections();\n this.closeIfDrained();\n return this;\n }\n /**\n * This method destroys each idle connection, as Node does. A connection is idle before its first\n * request, and from the `end()` of its response, also while the bytes of the response still go.\n */\n closeIdleConnections(): void {\n for (const connection of this.connections)\n if (!connection.upgraded && (connection.idle || connection.response?.finished === true)) connection.socket.destroy();\n }\n /** This method destroys each connection of HTTP. As in Node, an upgraded connection is not in the list. */\n closeAllConnections(): void {\n for (const connection of this.connections) if (!connection.upgraded) connection.socket.destroy();\n }\n /** This method opens a connection, or it throws a refusal when the listener is closed. */\n connect(): FakeConnection {\n if (!this.listening) throw Object.assign(new Error(\"ECONNREFUSED: the listener is closed\"), { code: \"ECONNREFUSED\" });\n const socket = new FakeSocket();\n const connection = new FakeConnection(this, socket);\n this.connections.add(connection);\n socket.once(\"close\", () => {\n this.connections.delete(connection);\n this.closeIfDrained();\n });\n this.emit(\"connection\", socket);\n return connection;\n }\n /** This method sends one request on a new connection. */\n async request(url: string, method = \"GET\", headers: Readonly<Record<string, string>> = {}): Promise<FakeAnswer> {\n return this.connect().request(url, method, headers);\n }\n private closeIfDrained(): void {\n if (!this.closing || this.listening || this.connections.size > 0) return;\n this.closing = false;\n process.nextTick(() => this.emit(\"close\"));\n }\n /** This value is the fake server with the type of a server of `node:http`, for the code under test. */\n get asServer(): Server {\n return this as unknown as Server;\n }\n}\n\n/** A pushed source is an async iterable whose items, end and failure a test gives. Its `return()` ends it. */\nexport interface PushedSource<T> {\n readonly iterable: AsyncIterable<T>;\n push(value: T): void;\n finish(): void;\n fail(error: unknown): void;\n /** This flag tells if a reader stopped the source through `return()`. */\n readonly returned: boolean;\n}\n\n/** This function makes a pushed source, a stream of a work for the tests of a stream. */\nexport const pushedSource = <T>(): PushedSource<T> => {\n const queue: Array<IteratorResult<T>> = [];\n let wake: (() => void) | null = null;\n let failure: unknown = null;\n let returned = false;\n const poke = (): void => {\n wake?.();\n wake = null;\n };\n const iterable: AsyncIterable<T> = {\n [Symbol.asyncIterator]: () => ({\n async next(): Promise<IteratorResult<T>> {\n for (;;) {\n if (failure !== null) throw failure;\n if (returned) return { value: undefined, done: true };\n const step = queue.shift();\n if (step !== undefined) return step;\n await new Promise<void>((resolve) => (wake = resolve));\n }\n },\n async return(): Promise<IteratorResult<T>> {\n returned = true;\n poke();\n return { value: undefined, done: true };\n },\n }),\n };\n return {\n iterable,\n push: (value) => {\n queue.push({ value, done: false });\n poke();\n },\n finish: () => {\n queue.push({ value: undefined, done: true });\n poke();\n },\n fail: (error) => {\n failure = error;\n poke();\n },\n get returned() {\n return returned;\n },\n };\n};\n"],"mappings":";;;AA8PA,MAAa,qBAAyC;CACpD,MAAM,QAAkC,CAAC;CACzC,IAAI,OAA4B;CAChC,IAAI,UAAmB;CACvB,IAAI,WAAW;CACf,MAAM,aAAmB;EACvB,OAAO;EACP,OAAO;CACT;CAmBA,OAAO;EACL,UAAA,GAlBC,OAAO,uBAAuB;GAC7B,MAAM,OAAmC;IACvC,SAAS;KACP,IAAI,YAAY,MAAM,MAAM;KAC5B,IAAI,UAAU,OAAO;MAAE,OAAO,KAAA;MAAW,MAAM;KAAK;KACpD,MAAM,OAAO,MAAM,MAAM;KACzB,IAAI,SAAS,KAAA,GAAW,OAAO;KAC/B,MAAM,IAAI,SAAe,YAAa,OAAO,OAAQ;IACvD;GACF;GACA,MAAM,SAAqC;IACzC,WAAW;IACX,KAAK;IACL,OAAO;KAAE,OAAO,KAAA;KAAW,MAAM;IAAK;GACxC;EACF,GAGO;EACP,OAAO,UAAU;GACf,MAAM,KAAK;IAAE;IAAO,MAAM;GAAM,CAAC;GACjC,KAAK;EACP;EACA,cAAc;GACZ,MAAM,KAAK;IAAE,OAAO,KAAA;IAAW,MAAM;GAAK,CAAC;GAC3C,KAAK;EACP;EACA,OAAO,UAAU;GACf,UAAU;GACV,KAAK;EACP;EACA,IAAI,WAAW;GACb,OAAO;EACT;CACF;AACF"}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { Refused } from "../limiter/policy.js";
|
|
2
|
+
import { RequestEnd, RequestStream, RequestWork } from "../requests.js";
|
|
3
|
+
import { RequestHandler } from "./transport.js";
|
|
4
|
+
import { Quantity } from "@mark1russell7/quantity";
|
|
5
|
+
import { IncomingMessage, ServerResponse } from "node:http";
|
|
6
|
+
/** An outcome response is the status, the headers and the body of a request, for any HTTP framework or none. */
|
|
7
|
+
export interface OutcomeResponse {
|
|
8
|
+
readonly status: number;
|
|
9
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
10
|
+
readonly body: string | Uint8Array;
|
|
11
|
+
}
|
|
12
|
+
/** A response part is what a hook gives for one value or one failure. The parts that it does not give keep the values of the mapping. */
|
|
13
|
+
export interface ResponsePart {
|
|
14
|
+
readonly status?: number | undefined;
|
|
15
|
+
readonly headers?: Readonly<Record<string, string>> | undefined;
|
|
16
|
+
readonly body?: string | Uint8Array | undefined;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A stream format writes the items of a stream and its end in the body, as they come. An end after
|
|
20
|
+
* the first item goes in the body, because the status went with the first item.
|
|
21
|
+
*/
|
|
22
|
+
export interface StreamFormat<T = unknown> {
|
|
23
|
+
readonly contentType: string;
|
|
24
|
+
/** This function gives the bytes of one item. */
|
|
25
|
+
item(value: T): string | Uint8Array;
|
|
26
|
+
/** This function gives the bytes of the end, the last part of the body. */
|
|
27
|
+
end(end: RequestEnd): string | Uint8Array;
|
|
28
|
+
}
|
|
29
|
+
/** These options map a request to a response. */
|
|
30
|
+
export interface OutcomeOptions<T> {
|
|
31
|
+
/**
|
|
32
|
+
* This value tells if the response can keep its connection open, as `life.keepAlive()` does. False
|
|
33
|
+
* gives `Connection: close`. A function is read when the headers go.
|
|
34
|
+
*/
|
|
35
|
+
readonly keepAlive: boolean | (() => boolean);
|
|
36
|
+
/** This time goes in the `Retry-After` of each 503, in whole seconds, rounded up. It is the knob `server_retry_after`. */
|
|
37
|
+
readonly retryAfter: Quantity;
|
|
38
|
+
/**
|
|
39
|
+
* This function gives the response of the value of a unary request. Without it, the mapping gives
|
|
40
|
+
* 200 and the value as JSON, or 204 for no value.
|
|
41
|
+
*/
|
|
42
|
+
readonly done?: ((value: T) => ResponsePart) | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* This function gives the response of a failure of the route before the first byte. Without it,
|
|
45
|
+
* the mapping gives 500 with no detail, because an error can hold private data.
|
|
46
|
+
*/
|
|
47
|
+
readonly failed?: ((error: unknown) => ResponsePart) | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* This format makes the response a stream: the status and each item go as they come, and the end
|
|
50
|
+
* goes in the body. Without it, the response is unary: one status and the one value.
|
|
51
|
+
*/
|
|
52
|
+
readonly stream?: StreamFormat<T> | undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* This function gives an end as a record for a body: its kind and the count of its items. A cut and
|
|
56
|
+
* a refusal also give their cause, and if the caller can send the request again. A failure gives
|
|
57
|
+
* no detail.
|
|
58
|
+
*/
|
|
59
|
+
export declare const endRecord: (end: RequestEnd) => Readonly<Record<string, unknown>>;
|
|
60
|
+
/** This format writes each item and the end as one line of JSON (NDJSON). */
|
|
61
|
+
export declare const ndjson: StreamFormat;
|
|
62
|
+
/** This format writes each item as an event of server-sent events, and the end as the event `end`. */
|
|
63
|
+
export declare const sse: StreamFormat;
|
|
64
|
+
/**
|
|
65
|
+
* This function maps a unary request to its response, from its items and its end (S6 A12 and A13).
|
|
66
|
+
* - One value and the end `done`: 200 with the value, or the response of the `done` hook.
|
|
67
|
+
* - No value and the end `done`: 204. More than one value: 500, because the route is not a stream.
|
|
68
|
+
* - `refused`: 503. The work did not start, thus the caller can send it again. The service did not
|
|
69
|
+
* start, it stopped its intake, or a controller is not ready.
|
|
70
|
+
* - `cut`: 503 for a route whose callers can send it again (S6 A12), and 500 for each other route.
|
|
71
|
+
* - `failed`: 500 with no detail, or the response of the `failed` hook. A failure of the route is not a 503.
|
|
72
|
+
*
|
|
73
|
+
* Each 503 gets `Retry-After` (RFC 9110), and a 500 gets none. Each response gets `Connection: close`
|
|
74
|
+
* while the service cannot keep the connection.
|
|
75
|
+
*/
|
|
76
|
+
export declare const outcomeResponse: <T>(items: readonly T[], end: RequestEnd, options: OutcomeOptions<T>) => OutcomeResponse;
|
|
77
|
+
/**
|
|
78
|
+
* This function gives the response of a take that a keyed limiter refused. The work did not start.
|
|
79
|
+
* - A wait refusal (`limit`, `cap` or `store`) gives 429 (RFC 6585), with `Retry-After` in whole
|
|
80
|
+
* seconds, rounded up (RFC 9110). The body tells the cause and the same whole seconds, but not the
|
|
81
|
+
* failure of a store. The caller can send the request again.
|
|
82
|
+
* - A capacity refusal gives 413 (RFC 9110) with no `Retry-After`, because no wait lets the take in.
|
|
83
|
+
* The body tells the units and the capacity, thus the caller can split the request into parts.
|
|
84
|
+
*/
|
|
85
|
+
export declare const limitedResponse: (refused: Refused) => OutcomeResponse;
|
|
86
|
+
/**
|
|
87
|
+
* This function writes the stream of a request to a response of `node:http`, and gives its end. It
|
|
88
|
+
* gives null when the client closed the connection first. Then the work stops through `return()`.
|
|
89
|
+
* - Unary (no format): it waits for the end, and it writes the status and the body of `outcomeResponse`.
|
|
90
|
+
* - Stream: the status 200 goes with the first item, then each item goes as it comes, then the end
|
|
91
|
+
* goes in the body (in-band). The next item waits until the client reads, thus a slow client
|
|
92
|
+
* slows the work. An end before the first item gets a status, as a unary end does.
|
|
93
|
+
* - The answer to come: until it writes the end, the response holds the drain of `httpTransport` past
|
|
94
|
+
* its deadline. The cut of the drain gives that end, and the drain waits until the end goes out.
|
|
95
|
+
* Only a stream of `life.request` of the lifecycle of the transport holds the drain.
|
|
96
|
+
*/
|
|
97
|
+
export declare const writeOutcome: <T>(res: ServerResponse, stream: RequestStream<T>, options: OutcomeOptions<T>) => Promise<RequestEnd | null>;
|
|
98
|
+
/** A route of a handler is the name of the route that a controller declares, or a function that gives it from the request. */
|
|
99
|
+
export type HandledRoute = string | ((req: IncomingMessage) => string | null);
|
|
100
|
+
/** A handled work does the work of one request of `node:http`. Its signal aborts when the shutdown or the client stops the request. */
|
|
101
|
+
export type HandledWork<T> = (req: IncomingMessage, signal: AbortSignal) => RequestWork<T>;
|
|
102
|
+
/** These options bind a request of `node:http` to the request tracking of the service. */
|
|
103
|
+
export interface HandleOptions<T> extends Omit<OutcomeOptions<T>, "keepAlive" | "retryAfter"> {
|
|
104
|
+
/** This function gives the detail of a request, for the function of a route pattern. */
|
|
105
|
+
readonly detail?: ((req: IncomingMessage) => unknown) | undefined;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* This function gives a request handler that does each request of a route through `life.request`
|
|
109
|
+
* (S6 A12 and A13). The transport gives the lifecycle and `server_retry_after` through the context.
|
|
110
|
+
* - A route name takes a request whose method and path are that name, for example `POST /orders`.
|
|
111
|
+
* A function gives the name of a route or of a pattern, or null for a request of another handler.
|
|
112
|
+
* - Before the start of the transport, each request gets a retryable 503.
|
|
113
|
+
* - The response is unary, or a stream with the option `stream`, as `writeOutcome` writes it.
|
|
114
|
+
*/
|
|
115
|
+
export declare const handle: <T>(controller: string, route: HandledRoute, work: HandledWork<T>, options?: HandleOptions<T>) => RequestHandler;
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { ownStream, ownerOf } from "../drains.js";
|
|
2
|
+
import { retryAfterSeconds } from "../limiter/policy.js";
|
|
3
|
+
import { markAnswer } from "./answers.js";
|
|
4
|
+
import { pathOf } from "./transport.js";
|
|
5
|
+
import { valueIn } from "@mark1russell7/quantity";
|
|
6
|
+
// src/http/outcome.ts
|
|
7
|
+
const JSON_TYPE = "application/json; charset=utf-8";
|
|
8
|
+
/**
|
|
9
|
+
* This function gives an end as a record for a body: its kind and the count of its items. A cut and
|
|
10
|
+
* a refusal also give their cause, and if the caller can send the request again. A failure gives
|
|
11
|
+
* no detail.
|
|
12
|
+
*/
|
|
13
|
+
const endRecord = (end) => {
|
|
14
|
+
if (end.kind === "refused" || end.kind === "cut") return {
|
|
15
|
+
end: end.kind,
|
|
16
|
+
delivered: end.delivered,
|
|
17
|
+
retryable: end.retryable,
|
|
18
|
+
cause: end.cause
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
end: end.kind,
|
|
22
|
+
delivered: end.delivered
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/** This format writes each item and the end as one line of JSON (NDJSON). */
|
|
26
|
+
const ndjson = {
|
|
27
|
+
contentType: "application/x-ndjson; charset=utf-8",
|
|
28
|
+
item: (value) => `${JSON.stringify(value)}\n`,
|
|
29
|
+
end: (end) => `${JSON.stringify(endRecord(end))}\n`
|
|
30
|
+
};
|
|
31
|
+
/** This format writes each item as an event of server-sent events, and the end as the event `end`. */
|
|
32
|
+
const sse = {
|
|
33
|
+
contentType: "text/event-stream; charset=utf-8",
|
|
34
|
+
item: (value) => `data: ${JSON.stringify(value)}\n\n`,
|
|
35
|
+
end: (end) => `event: end\ndata: ${JSON.stringify(endRecord(end))}\n\n`
|
|
36
|
+
};
|
|
37
|
+
const valueResponse = (value) => {
|
|
38
|
+
if (value === void 0) return {
|
|
39
|
+
status: 204,
|
|
40
|
+
headers: {},
|
|
41
|
+
body: ""
|
|
42
|
+
};
|
|
43
|
+
if (typeof value === "string") return {
|
|
44
|
+
status: 200,
|
|
45
|
+
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
46
|
+
body: value
|
|
47
|
+
};
|
|
48
|
+
if (value instanceof Uint8Array) return {
|
|
49
|
+
status: 200,
|
|
50
|
+
headers: { "content-type": "application/octet-stream" },
|
|
51
|
+
body: value
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
status: 200,
|
|
55
|
+
headers: { "content-type": JSON_TYPE },
|
|
56
|
+
body: JSON.stringify(value)
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
const merge = (base, part) => part === void 0 ? base : {
|
|
60
|
+
status: part.status ?? base.status,
|
|
61
|
+
headers: {
|
|
62
|
+
...base.headers,
|
|
63
|
+
...part.headers
|
|
64
|
+
},
|
|
65
|
+
body: part.body ?? base.body
|
|
66
|
+
};
|
|
67
|
+
const keeps = (keepAlive) => typeof keepAlive === "function" ? keepAlive() : keepAlive;
|
|
68
|
+
/**
|
|
69
|
+
* This function applies the rules of the headers to a response. Each 503 gets `Retry-After`, and a
|
|
70
|
+
* 500 gets none. The response closes its connection while the service cannot keep it.
|
|
71
|
+
*/
|
|
72
|
+
const ruled = (response, retryAfter, keepAlive) => {
|
|
73
|
+
const headers = { ...response.headers };
|
|
74
|
+
if (response.status === 503 && headers["retry-after"] === void 0) headers["retry-after"] = String(Math.max(0, Math.ceil(valueIn(retryAfter, "s"))));
|
|
75
|
+
if (response.status === 500) delete headers["retry-after"];
|
|
76
|
+
if (!keeps(keepAlive)) headers["connection"] = "close";
|
|
77
|
+
return {
|
|
78
|
+
...response,
|
|
79
|
+
headers
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
/** This function gives the status response of an end before the first byte of the body. */
|
|
83
|
+
const endStatus = (end, options) => {
|
|
84
|
+
const body = JSON.stringify(endRecord(end));
|
|
85
|
+
switch (end.kind) {
|
|
86
|
+
case "refused": return {
|
|
87
|
+
status: 503,
|
|
88
|
+
headers: { "content-type": JSON_TYPE },
|
|
89
|
+
body
|
|
90
|
+
};
|
|
91
|
+
case "cut": return {
|
|
92
|
+
status: end.status ?? (end.retryable ? 503 : 500),
|
|
93
|
+
headers: { "content-type": JSON_TYPE },
|
|
94
|
+
body
|
|
95
|
+
};
|
|
96
|
+
case "failed": return merge({
|
|
97
|
+
status: 500,
|
|
98
|
+
headers: { "content-type": JSON_TYPE },
|
|
99
|
+
body
|
|
100
|
+
}, options.failed?.(end.error));
|
|
101
|
+
case "done": return {
|
|
102
|
+
status: 204,
|
|
103
|
+
headers: {},
|
|
104
|
+
body: ""
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* This function maps a unary request to its response, from its items and its end (S6 A12 and A13).
|
|
110
|
+
* - One value and the end `done`: 200 with the value, or the response of the `done` hook.
|
|
111
|
+
* - No value and the end `done`: 204. More than one value: 500, because the route is not a stream.
|
|
112
|
+
* - `refused`: 503. The work did not start, thus the caller can send it again. The service did not
|
|
113
|
+
* start, it stopped its intake, or a controller is not ready.
|
|
114
|
+
* - `cut`: 503 for a route whose callers can send it again (S6 A12), and 500 for each other route.
|
|
115
|
+
* - `failed`: 500 with no detail, or the response of the `failed` hook. A failure of the route is not a 503.
|
|
116
|
+
*
|
|
117
|
+
* Each 503 gets `Retry-After` (RFC 9110), and a 500 gets none. Each response gets `Connection: close`
|
|
118
|
+
* while the service cannot keep the connection.
|
|
119
|
+
*/
|
|
120
|
+
const outcomeResponse = (items, end, options) => {
|
|
121
|
+
let response;
|
|
122
|
+
if (end.kind !== "done") response = endStatus(end, options);
|
|
123
|
+
else if (items.length === 1) response = merge(valueResponse(items[0]), options.done?.(items[0]));
|
|
124
|
+
else if (items.length === 0) response = endStatus(end, options);
|
|
125
|
+
else response = endStatus({
|
|
126
|
+
kind: "failed",
|
|
127
|
+
error: /* @__PURE__ */ new Error(`the work gave ${items.length} values, and a unary response has one`),
|
|
128
|
+
delivered: items.length
|
|
129
|
+
}, options);
|
|
130
|
+
return ruled(response, options.retryAfter, options.keepAlive);
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* This function gives the response of a take that a keyed limiter refused. The work did not start.
|
|
134
|
+
* - A wait refusal (`limit`, `cap` or `store`) gives 429 (RFC 6585), with `Retry-After` in whole
|
|
135
|
+
* seconds, rounded up (RFC 9110). The body tells the cause and the same whole seconds, but not the
|
|
136
|
+
* failure of a store. The caller can send the request again.
|
|
137
|
+
* - A capacity refusal gives 413 (RFC 9110) with no `Retry-After`, because no wait lets the take in.
|
|
138
|
+
* The body tells the units and the capacity, thus the caller can split the request into parts.
|
|
139
|
+
*/
|
|
140
|
+
const limitedResponse = (refused) => {
|
|
141
|
+
if (refused.cause === "capacity") return {
|
|
142
|
+
status: 413,
|
|
143
|
+
headers: { "content-type": JSON_TYPE },
|
|
144
|
+
body: JSON.stringify({
|
|
145
|
+
end: "refused",
|
|
146
|
+
delivered: 0,
|
|
147
|
+
retryable: false,
|
|
148
|
+
cause: `the limiter refused the take: capacity, ${refused.units} units over a capacity of ${refused.capacity}`,
|
|
149
|
+
units: refused.units,
|
|
150
|
+
capacity: refused.capacity
|
|
151
|
+
})
|
|
152
|
+
};
|
|
153
|
+
const seconds = retryAfterSeconds(refused.retryAfter);
|
|
154
|
+
return {
|
|
155
|
+
status: 429,
|
|
156
|
+
headers: {
|
|
157
|
+
"content-type": JSON_TYPE,
|
|
158
|
+
"retry-after": String(seconds)
|
|
159
|
+
},
|
|
160
|
+
body: JSON.stringify({
|
|
161
|
+
end: "refused",
|
|
162
|
+
delivered: 0,
|
|
163
|
+
retryable: true,
|
|
164
|
+
cause: `the limiter refused the take: ${refused.cause}`,
|
|
165
|
+
retryAfter: seconds
|
|
166
|
+
})
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
/** This function writes a whole response of `node:http`. A response whose headers went gets no second status: it is destroyed. */
|
|
170
|
+
const writeWhole = (res, response) => {
|
|
171
|
+
if (res.headersSent) {
|
|
172
|
+
res.destroy();
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (response.headers["connection"] === "close") res.shouldKeepAlive = false;
|
|
176
|
+
if (response.status === 204) {
|
|
177
|
+
res.writeHead(204, response.headers);
|
|
178
|
+
res.end();
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
const length = typeof response.body === "string" ? Buffer.byteLength(response.body) : response.body.byteLength;
|
|
182
|
+
res.writeHead(response.status, {
|
|
183
|
+
...response.headers,
|
|
184
|
+
"content-length": String(length)
|
|
185
|
+
});
|
|
186
|
+
res.end(response.body);
|
|
187
|
+
};
|
|
188
|
+
/**
|
|
189
|
+
* This function writes the stream of a request to a response of `node:http`, and gives its end. It
|
|
190
|
+
* gives null when the client closed the connection first. Then the work stops through `return()`.
|
|
191
|
+
* - Unary (no format): it waits for the end, and it writes the status and the body of `outcomeResponse`.
|
|
192
|
+
* - Stream: the status 200 goes with the first item, then each item goes as it comes, then the end
|
|
193
|
+
* goes in the body (in-band). The next item waits until the client reads, thus a slow client
|
|
194
|
+
* slows the work. An end before the first item gets a status, as a unary end does.
|
|
195
|
+
* - The answer to come: until it writes the end, the response holds the drain of `httpTransport` past
|
|
196
|
+
* its deadline. The cut of the drain gives that end, and the drain waits until the end goes out.
|
|
197
|
+
* Only a stream of `life.request` of the lifecycle of the transport holds the drain.
|
|
198
|
+
*/
|
|
199
|
+
const writeOutcome = async (res, stream, options) => {
|
|
200
|
+
const iterator = stream[Symbol.asyncIterator]();
|
|
201
|
+
let gone = () => {};
|
|
202
|
+
const closed = new Promise((resolve) => {
|
|
203
|
+
gone = () => resolve("gone");
|
|
204
|
+
});
|
|
205
|
+
const onClose = () => {
|
|
206
|
+
if (!res.writableFinished) gone();
|
|
207
|
+
};
|
|
208
|
+
res.once("close", onClose);
|
|
209
|
+
if (res.destroyed) gone();
|
|
210
|
+
const leave = async () => {
|
|
211
|
+
await iterator.return?.();
|
|
212
|
+
return null;
|
|
213
|
+
};
|
|
214
|
+
const next = async () => {
|
|
215
|
+
const step = await Promise.race([iterator.next(), closed]);
|
|
216
|
+
if (step === "gone") return step;
|
|
217
|
+
if (step.done === true) throw new Error("the stream of the request ended without its end");
|
|
218
|
+
return step.value;
|
|
219
|
+
};
|
|
220
|
+
/** This function writes one part of the body, and waits while the client reads slower than the work. */
|
|
221
|
+
const send = async (chunk) => {
|
|
222
|
+
if (res.write(chunk)) return true;
|
|
223
|
+
const drained = new Promise((resolve) => res.once("drain", () => resolve("drained")));
|
|
224
|
+
return await Promise.race([drained, closed]) === "drained";
|
|
225
|
+
};
|
|
226
|
+
const answered = markAnswer(res, ownerOf(stream));
|
|
227
|
+
try {
|
|
228
|
+
const format = options.stream;
|
|
229
|
+
if (format === void 0) {
|
|
230
|
+
const items = [];
|
|
231
|
+
for (;;) {
|
|
232
|
+
const event = await next();
|
|
233
|
+
if (event === "gone") return await leave();
|
|
234
|
+
if (event.kind === "item") {
|
|
235
|
+
items.push(event.value);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
writeWhole(res, outcomeResponse(items, event, options));
|
|
239
|
+
return event;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const first = await next();
|
|
243
|
+
if (first === "gone") return await leave();
|
|
244
|
+
if (first.kind !== "item") {
|
|
245
|
+
if (first.kind === "done") writeWhole(res, ruled({
|
|
246
|
+
status: 200,
|
|
247
|
+
headers: {
|
|
248
|
+
"content-type": format.contentType,
|
|
249
|
+
"cache-control": "no-store"
|
|
250
|
+
},
|
|
251
|
+
body: format.end(first)
|
|
252
|
+
}, options.retryAfter, options.keepAlive));
|
|
253
|
+
else writeWhole(res, outcomeResponse([], first, options));
|
|
254
|
+
return first;
|
|
255
|
+
}
|
|
256
|
+
if (res.headersSent) {
|
|
257
|
+
res.destroy();
|
|
258
|
+
return await leave();
|
|
259
|
+
}
|
|
260
|
+
const head = ruled({
|
|
261
|
+
status: 200,
|
|
262
|
+
headers: {
|
|
263
|
+
"content-type": format.contentType,
|
|
264
|
+
"cache-control": "no-store"
|
|
265
|
+
},
|
|
266
|
+
body: ""
|
|
267
|
+
}, options.retryAfter, options.keepAlive);
|
|
268
|
+
if (head.headers["connection"] === "close") res.shouldKeepAlive = false;
|
|
269
|
+
res.writeHead(200, head.headers);
|
|
270
|
+
if (!await send(format.item(first.value))) return await leave();
|
|
271
|
+
for (;;) {
|
|
272
|
+
const event = await next();
|
|
273
|
+
if (event === "gone") return await leave();
|
|
274
|
+
if (event.kind === "item") {
|
|
275
|
+
if (!await send(format.item(event.value))) return await leave();
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
res.end(format.end(event));
|
|
279
|
+
return event;
|
|
280
|
+
}
|
|
281
|
+
} finally {
|
|
282
|
+
res.off("close", onClose);
|
|
283
|
+
answered();
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
/**
|
|
287
|
+
* This function gives a request handler that does each request of a route through `life.request`
|
|
288
|
+
* (S6 A12 and A13). The transport gives the lifecycle and `server_retry_after` through the context.
|
|
289
|
+
* - A route name takes a request whose method and path are that name, for example `POST /orders`.
|
|
290
|
+
* A function gives the name of a route or of a pattern, or null for a request of another handler.
|
|
291
|
+
* - Before the start of the transport, each request gets a retryable 503.
|
|
292
|
+
* - The response is unary, or a stream with the option `stream`, as `writeOutcome` writes it.
|
|
293
|
+
*/
|
|
294
|
+
const handle = (controller, route, work, options = {}) => {
|
|
295
|
+
const nameOf = (req) => {
|
|
296
|
+
if (typeof route === "function") return route(req);
|
|
297
|
+
return `${req.method ?? "GET"} ${pathOf(req.url)}` === route ? route : null;
|
|
298
|
+
};
|
|
299
|
+
return async (req, res, context) => {
|
|
300
|
+
const name = nameOf(req);
|
|
301
|
+
if (name === null) return false;
|
|
302
|
+
const life = context.life;
|
|
303
|
+
const written = {
|
|
304
|
+
...options,
|
|
305
|
+
keepAlive: () => life !== null && (context.keepAlive?.() ?? life.keepAlive()),
|
|
306
|
+
retryAfter: context.retryAfter
|
|
307
|
+
};
|
|
308
|
+
if (life === null) {
|
|
309
|
+
writeWhole(res, outcomeResponse([], {
|
|
310
|
+
kind: "refused",
|
|
311
|
+
status: 503,
|
|
312
|
+
retryable: true,
|
|
313
|
+
cause: "the transport has not started",
|
|
314
|
+
delivered: 0
|
|
315
|
+
}, written));
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
const given = options.detail === void 0 ? {} : { detail: options.detail(req) };
|
|
319
|
+
await writeOutcome(res, ownStream(life.request(controller, name, (signal) => work(req, signal), given), life), written);
|
|
320
|
+
return true;
|
|
321
|
+
};
|
|
322
|
+
};
|
|
323
|
+
export { endRecord, handle, limitedResponse, ndjson, outcomeResponse, sse, writeOutcome };
|
|
324
|
+
|
|
325
|
+
//# sourceMappingURL=outcome.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"outcome.js","names":[],"sources":["../../src/http/outcome.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { ownerOf, ownStream } from \"../drains.ts\";\nimport type { Refused } from \"../limiter/policy.ts\";\nimport { retryAfterSeconds } from \"../limiter/policy.ts\";\nimport type { RequestEnd, RequestEvent, RequestOptions, RequestStream, RequestWork } from \"../requests.ts\";\nimport { markAnswer } from \"./answers.ts\";\nimport type { MountContext, RequestHandler } from \"./transport.ts\";\nimport { pathOf } from \"./transport.ts\";\n\n/** An outcome response is the status, the headers and the body of a request, for any HTTP framework or none. */\nexport interface OutcomeResponse {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string | Uint8Array;\n}\n\n/** A response part is what a hook gives for one value or one failure. The parts that it does not give keep the values of the mapping. */\nexport interface ResponsePart {\n readonly status?: number | undefined;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly body?: string | Uint8Array | undefined;\n}\n\n/**\n * A stream format writes the items of a stream and its end in the body, as they come. An end after\n * the first item goes in the body, because the status went with the first item.\n */\nexport interface StreamFormat<T = unknown> {\n readonly contentType: string;\n /** This function gives the bytes of one item. */\n item(value: T): string | Uint8Array;\n /** This function gives the bytes of the end, the last part of the body. */\n end(end: RequestEnd): string | Uint8Array;\n}\n\n/** These options map a request to a response. */\nexport interface OutcomeOptions<T> {\n /**\n * This value tells if the response can keep its connection open, as `life.keepAlive()` does. False\n * gives `Connection: close`. A function is read when the headers go.\n */\n readonly keepAlive: boolean | (() => boolean);\n /** This time goes in the `Retry-After` of each 503, in whole seconds, rounded up. It is the knob `server_retry_after`. */\n readonly retryAfter: Quantity;\n /**\n * This function gives the response of the value of a unary request. Without it, the mapping gives\n * 200 and the value as JSON, or 204 for no value.\n */\n readonly done?: ((value: T) => ResponsePart) | undefined;\n /**\n * This function gives the response of a failure of the route before the first byte. Without it,\n * the mapping gives 500 with no detail, because an error can hold private data.\n */\n readonly failed?: ((error: unknown) => ResponsePart) | undefined;\n /**\n * This format makes the response a stream: the status and each item go as they come, and the end\n * goes in the body. Without it, the response is unary: one status and the one value.\n */\n readonly stream?: StreamFormat<T> | undefined;\n}\n\nconst JSON_TYPE = \"application/json; charset=utf-8\";\n\n/**\n * This function gives an end as a record for a body: its kind and the count of its items. A cut and\n * a refusal also give their cause, and if the caller can send the request again. A failure gives\n * no detail.\n */\nexport const endRecord = (end: RequestEnd): Readonly<Record<string, unknown>> => {\n if (end.kind === \"refused\" || end.kind === \"cut\")\n return { end: end.kind, delivered: end.delivered, retryable: end.retryable, cause: end.cause };\n return { end: end.kind, delivered: end.delivered };\n};\n\n/** This format writes each item and the end as one line of JSON (NDJSON). */\nexport const ndjson: StreamFormat = {\n contentType: \"application/x-ndjson; charset=utf-8\",\n item: (value) => `${JSON.stringify(value)}\\n`,\n end: (end) => `${JSON.stringify(endRecord(end))}\\n`,\n};\n\n/** This format writes each item as an event of server-sent events, and the end as the event `end`. */\nexport const sse: StreamFormat = {\n contentType: \"text/event-stream; charset=utf-8\",\n item: (value) => `data: ${JSON.stringify(value)}\\n\\n`,\n end: (end) => `event: end\\ndata: ${JSON.stringify(endRecord(end))}\\n\\n`,\n};\n\nconst valueResponse = (value: unknown): OutcomeResponse => {\n if (value === undefined) return { status: 204, headers: {}, body: \"\" };\n if (typeof value === \"string\") return { status: 200, headers: { \"content-type\": \"text/plain; charset=utf-8\" }, body: value };\n if (value instanceof Uint8Array) return { status: 200, headers: { \"content-type\": \"application/octet-stream\" }, body: value };\n return { status: 200, headers: { \"content-type\": JSON_TYPE }, body: JSON.stringify(value) };\n};\n\nconst merge = (base: OutcomeResponse, part: ResponsePart | undefined): OutcomeResponse =>\n part === undefined\n ? base\n : { status: part.status ?? base.status, headers: { ...base.headers, ...part.headers }, body: part.body ?? base.body };\n\nconst keeps = (keepAlive: boolean | (() => boolean)): boolean => (typeof keepAlive === \"function\" ? keepAlive() : keepAlive);\n\n/**\n * This function applies the rules of the headers to a response. Each 503 gets `Retry-After`, and a\n * 500 gets none. The response closes its connection while the service cannot keep it.\n */\nconst ruled = (response: OutcomeResponse, retryAfter: Quantity, keepAlive: boolean | (() => boolean)): OutcomeResponse => {\n const headers: Record<string, string> = { ...response.headers };\n if (response.status === 503 && headers[\"retry-after\"] === undefined)\n headers[\"retry-after\"] = String(Math.max(0, Math.ceil(valueIn(retryAfter, \"s\"))));\n if (response.status === 500) delete headers[\"retry-after\"];\n if (!keeps(keepAlive)) headers[\"connection\"] = \"close\";\n return { ...response, headers };\n};\n\n/** This function gives the status response of an end before the first byte of the body. */\nconst endStatus = <T>(end: RequestEnd, options: OutcomeOptions<T>): OutcomeResponse => {\n const body = JSON.stringify(endRecord(end));\n switch (end.kind) {\n case \"refused\":\n return { status: 503, headers: { \"content-type\": JSON_TYPE }, body };\n case \"cut\":\n // a cut after the first item has no status of its own, but no byte went: its route decides\n return { status: end.status ?? (end.retryable ? 503 : 500), headers: { \"content-type\": JSON_TYPE }, body };\n case \"failed\":\n return merge({ status: 500, headers: { \"content-type\": JSON_TYPE }, body }, options.failed?.(end.error));\n case \"done\":\n return { status: 204, headers: {}, body: \"\" };\n }\n};\n\n/**\n * This function maps a unary request to its response, from its items and its end (S6 A12 and A13).\n * - One value and the end `done`: 200 with the value, or the response of the `done` hook.\n * - No value and the end `done`: 204. More than one value: 500, because the route is not a stream.\n * - `refused`: 503. The work did not start, thus the caller can send it again. The service did not\n * start, it stopped its intake, or a controller is not ready.\n * - `cut`: 503 for a route whose callers can send it again (S6 A12), and 500 for each other route.\n * - `failed`: 500 with no detail, or the response of the `failed` hook. A failure of the route is not a 503.\n *\n * Each 503 gets `Retry-After` (RFC 9110), and a 500 gets none. Each response gets `Connection: close`\n * while the service cannot keep the connection.\n */\nexport const outcomeResponse = <T>(items: readonly T[], end: RequestEnd, options: OutcomeOptions<T>): OutcomeResponse => {\n let response: OutcomeResponse;\n if (end.kind !== \"done\") response = endStatus(end, options);\n else if (items.length === 1) response = merge(valueResponse(items[0]), options.done?.(items[0]!));\n else if (items.length === 0) response = endStatus(end, options);\n else\n response = endStatus(\n { kind: \"failed\", error: new Error(`the work gave ${items.length} values, and a unary response has one`), delivered: items.length },\n options,\n );\n return ruled(response, options.retryAfter, options.keepAlive);\n};\n\n/**\n * This function gives the response of a take that a keyed limiter refused. The work did not start.\n * - A wait refusal (`limit`, `cap` or `store`) gives 429 (RFC 6585), with `Retry-After` in whole\n * seconds, rounded up (RFC 9110). The body tells the cause and the same whole seconds, but not the\n * failure of a store. The caller can send the request again.\n * - A capacity refusal gives 413 (RFC 9110) with no `Retry-After`, because no wait lets the take in.\n * The body tells the units and the capacity, thus the caller can split the request into parts.\n */\nexport const limitedResponse = (refused: Refused): OutcomeResponse => {\n if (refused.cause === \"capacity\")\n return {\n status: 413,\n headers: { \"content-type\": JSON_TYPE },\n body: JSON.stringify({\n end: \"refused\",\n delivered: 0,\n retryable: false,\n cause: `the limiter refused the take: capacity, ${refused.units} units over a capacity of ${refused.capacity}`,\n units: refused.units,\n capacity: refused.capacity,\n }),\n };\n const seconds = retryAfterSeconds(refused.retryAfter);\n return {\n status: 429,\n headers: { \"content-type\": JSON_TYPE, \"retry-after\": String(seconds) },\n body: JSON.stringify({ end: \"refused\", delivered: 0, retryable: true, cause: `the limiter refused the take: ${refused.cause}`, retryAfter: seconds }),\n };\n};\n\n/** This function writes a whole response of `node:http`. A response whose headers went gets no second status: it is destroyed. */\nconst writeWhole = (res: ServerResponse, response: OutcomeResponse): void => {\n if (res.headersSent) {\n res.destroy();\n return;\n }\n if (response.headers[\"connection\"] === \"close\") res.shouldKeepAlive = false;\n // a 204 has no body, thus no length\n if (response.status === 204) {\n res.writeHead(204, response.headers);\n res.end();\n return;\n }\n const length = typeof response.body === \"string\" ? Buffer.byteLength(response.body) : response.body.byteLength;\n res.writeHead(response.status, { ...response.headers, \"content-length\": String(length) });\n res.end(response.body);\n};\n\n/**\n * This function writes the stream of a request to a response of `node:http`, and gives its end. It\n * gives null when the client closed the connection first. Then the work stops through `return()`.\n * - Unary (no format): it waits for the end, and it writes the status and the body of `outcomeResponse`.\n * - Stream: the status 200 goes with the first item, then each item goes as it comes, then the end\n * goes in the body (in-band). The next item waits until the client reads, thus a slow client\n * slows the work. An end before the first item gets a status, as a unary end does.\n * - The answer to come: until it writes the end, the response holds the drain of `httpTransport` past\n * its deadline. The cut of the drain gives that end, and the drain waits until the end goes out.\n * Only a stream of `life.request` of the lifecycle of the transport holds the drain.\n */\nexport const writeOutcome = async <T>(res: ServerResponse, stream: RequestStream<T>, options: OutcomeOptions<T>): Promise<RequestEnd | null> => {\n const iterator = stream[Symbol.asyncIterator]();\n let gone: () => void = () => {};\n const closed = new Promise<\"gone\">((resolve) => {\n gone = () => resolve(\"gone\");\n });\n // a close before the end of the response is a client that went away\n const onClose = (): void => {\n if (!res.writableFinished) gone();\n };\n res.once(\"close\", onClose);\n if (res.destroyed) gone();\n const leave = async (): Promise<null> => {\n await iterator.return?.();\n return null;\n };\n const next = async (): Promise<RequestEvent<T> | \"gone\"> => {\n const step = await Promise.race([iterator.next(), closed]);\n if (step === \"gone\") return step;\n if (step.done === true) throw new Error(\"the stream of the request ended without its end\");\n return step.value;\n };\n /** This function writes one part of the body, and waits while the client reads slower than the work. */\n const send = async (chunk: string | Uint8Array): Promise<boolean> => {\n if (res.write(chunk)) return true;\n const drained = new Promise<\"drained\">((resolve) => res.once(\"drain\", () => resolve(\"drained\")));\n return (await Promise.race([drained, closed])) === \"drained\";\n };\n const answered = markAnswer(res, ownerOf(stream));\n try {\n const format = options.stream;\n if (format === undefined) {\n const items: T[] = [];\n for (;;) {\n const event = await next();\n if (event === \"gone\") return await leave();\n if (event.kind === \"item\") {\n items.push(event.value);\n continue;\n }\n writeWhole(res, outcomeResponse(items, event, options));\n return event;\n }\n }\n const first = await next();\n if (first === \"gone\") return await leave();\n if (first.kind !== \"item\") {\n // an empty stream that ended well gives 200 and its end. Each other end before the first item gets a status\n if (first.kind === \"done\")\n writeWhole(res, ruled({ status: 200, headers: { \"content-type\": format.contentType, \"cache-control\": \"no-store\" }, body: format.end(first) }, options.retryAfter, options.keepAlive));\n else writeWhole(res, outcomeResponse([], first, options));\n return first;\n }\n if (res.headersSent) {\n res.destroy();\n return await leave();\n }\n const head = ruled({ status: 200, headers: { \"content-type\": format.contentType, \"cache-control\": \"no-store\" }, body: \"\" }, options.retryAfter, options.keepAlive);\n if (head.headers[\"connection\"] === \"close\") res.shouldKeepAlive = false;\n res.writeHead(200, head.headers);\n if (!(await send(format.item(first.value)))) return await leave();\n for (;;) {\n const event = await next();\n if (event === \"gone\") return await leave();\n if (event.kind === \"item\") {\n if (!(await send(format.item(event.value)))) return await leave();\n continue;\n }\n // the end after the first item is in-band: the status went with the first item\n res.end(format.end(event));\n return event;\n }\n } finally {\n res.off(\"close\", onClose);\n answered();\n }\n};\n\n/** A route of a handler is the name of the route that a controller declares, or a function that gives it from the request. */\nexport type HandledRoute = string | ((req: IncomingMessage) => string | null);\n\n/** A handled work does the work of one request of `node:http`. Its signal aborts when the shutdown or the client stops the request. */\nexport type HandledWork<T> = (req: IncomingMessage, signal: AbortSignal) => RequestWork<T>;\n\n/** These options bind a request of `node:http` to the request tracking of the service. */\nexport interface HandleOptions<T> extends Omit<OutcomeOptions<T>, \"keepAlive\" | \"retryAfter\"> {\n /** This function gives the detail of a request, for the function of a route pattern. */\n readonly detail?: ((req: IncomingMessage) => unknown) | undefined;\n}\n\n/**\n * This function gives a request handler that does each request of a route through `life.request`\n * (S6 A12 and A13). The transport gives the lifecycle and `server_retry_after` through the context.\n * - A route name takes a request whose method and path are that name, for example `POST /orders`.\n * A function gives the name of a route or of a pattern, or null for a request of another handler.\n * - Before the start of the transport, each request gets a retryable 503.\n * - The response is unary, or a stream with the option `stream`, as `writeOutcome` writes it.\n */\nexport const handle = <T>(controller: string, route: HandledRoute, work: HandledWork<T>, options: HandleOptions<T> = {}): RequestHandler => {\n const nameOf = (req: IncomingMessage): string | null => {\n if (typeof route === \"function\") return route(req);\n return `${req.method ?? \"GET\"} ${pathOf(req.url)}` === route ? route : null;\n };\n return async (req: IncomingMessage, res: ServerResponse, context: MountContext): Promise<boolean> => {\n const name = nameOf(req);\n if (name === null) return false;\n const life = context.life;\n const written: OutcomeOptions<T> = {\n ...options,\n // the transport decides, with its option keepAlive. Before the start, no response keeps its connection\n keepAlive: () => life !== null && (context.keepAlive?.() ?? life.keepAlive()),\n retryAfter: context.retryAfter,\n };\n if (life === null) {\n const refused: RequestEnd = { kind: \"refused\", status: 503, retryable: true, cause: \"the transport has not started\", delivered: 0 };\n writeWhole(res, outcomeResponse<T>([], refused, written));\n return true;\n }\n const given: RequestOptions = options.detail === undefined ? {} : { detail: options.detail(req) };\n // the stream comes from the lifecycle of the transport, thus the drain of the transport can cut it\n await writeOutcome(res, ownStream(life.request(controller, name, (signal) => work(req, signal), given), life), written);\n return true;\n };\n};\n"],"mappings":";;;;;;AA+DA,MAAM,YAAY;;;;;;AAOlB,MAAa,aAAa,QAAuD;CAC/E,IAAI,IAAI,SAAS,aAAa,IAAI,SAAS,OACzC,OAAO;EAAE,KAAK,IAAI;EAAM,WAAW,IAAI;EAAW,WAAW,IAAI;EAAW,OAAO,IAAI;CAAM;CAC/F,OAAO;EAAE,KAAK,IAAI;EAAM,WAAW,IAAI;CAAU;AACnD;;AAGA,MAAa,SAAuB;CAClC,aAAa;CACb,OAAO,UAAU,GAAG,KAAK,UAAU,KAAK,EAAE;CAC1C,MAAM,QAAQ,GAAG,KAAK,UAAU,UAAU,GAAG,CAAC,EA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