@syntropika/tembra-sdk 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -17
- package/dist/authoring/types.d.ts +64 -3
- package/dist/authoring/wit.d.ts +6 -0
- package/dist/bridge/commands.d.ts +1190 -0
- package/dist/bridge/identifiers.d.ts +2 -0
- package/dist/bridge/kernel.d.ts +18 -107
- package/dist/bridge/protocol.d.ts +3 -138
- package/dist/browser.d.ts +14 -1
- package/dist/browser.js +141 -3298
- package/dist/chunks/browser-b8jamxw2.js +3399 -0
- package/dist/chunks/execution-nsqc6nrt.js +1419 -0
- package/dist/chunks/index-01zk0xqx.js +160 -0
- package/dist/chunks/index-3fjdfdfd.js +152 -0
- package/dist/chunks/index-aaymjn7v.js +787 -0
- package/dist/chunks/index-c1w7z9hx.js +356 -0
- package/dist/chunks/index-h8t0n42q.js +738 -0
- package/dist/chunks/index-hfds9mzp.js +308 -0
- package/dist/chunks/index-kr4x67wt.js +177 -0
- package/dist/chunks/index-kr6bnh34.js +117 -0
- package/dist/chunks/index-kyt9dj0a.js +1421 -0
- package/dist/chunks/index-n1wxzc9w.js +830 -0
- package/dist/chunks/index-pvac426d.js +74 -0
- package/dist/chunks/index-smyds5ce.js +3234 -0
- package/dist/chunks/index-sse8aapb.js +121 -0
- package/dist/chunks/index-v6heph77.js +643 -0
- package/dist/chunks/index-xrdvnv37.js +3448 -0
- package/dist/chunks/index-za4mg94e.js +26 -0
- package/dist/chunks/index-zkqmnjj8.js +167 -0
- package/dist/coordinator.js +9 -500
- package/dist/error.d.ts +2 -0
- package/dist/errors.d.ts +3 -0
- package/dist/guest.d.ts +173 -0
- package/dist/guest.js +26 -0
- package/dist/host.d.ts +36 -30
- package/dist/host.js +37 -3276
- package/dist/http/bytes.d.ts +8 -0
- package/dist/http/events.d.ts +7 -0
- package/dist/http.d.ts +45 -0
- package/dist/http.js +291 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +49 -862
- package/dist/infrastructure/rpc/client.d.ts +2 -1
- package/dist/infrastructure/rpc/resources.d.ts +28 -0
- package/dist/interpreter/abi.d.ts +54 -0
- package/dist/interpreter/acquire.d.ts +18 -0
- package/dist/interpreter/browser-network.d.ts +52 -0
- package/dist/interpreter/browser-port.d.ts +55 -0
- package/dist/interpreter/browser.d.ts +79 -0
- package/dist/interpreter/cli.d.ts +5 -0
- package/dist/interpreter/codec.d.ts +42 -0
- package/dist/interpreter/component/execution.d.ts +42 -0
- package/dist/interpreter/component/host.d.ts +69 -0
- package/dist/interpreter/component/instance.d.ts +40 -0
- package/dist/interpreter/component/kernel.d.ts +120 -0
- package/dist/interpreter/component/names.d.ts +5 -0
- package/dist/interpreter/component/port.d.ts +85 -0
- package/dist/interpreter/component/prepared.d.ts +97 -0
- package/dist/interpreter/component/resources.d.ts +45 -0
- package/dist/interpreter/component/revision.d.ts +87 -0
- package/dist/interpreter/component/scope.d.ts +116 -0
- package/dist/interpreter/component/streams.d.ts +28 -0
- package/dist/interpreter/component/values.d.ts +79 -0
- package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
- package/dist/interpreter/component/wasi-host.d.ts +64 -0
- package/dist/interpreter/component/wasi-http.d.ts +33 -0
- package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
- package/dist/interpreter/component/wasi.d.ts +41 -0
- package/dist/interpreter/core.d.ts +64 -0
- package/dist/interpreter/fetch-http-provider.d.ts +17 -0
- package/dist/interpreter/filesystem/contract.d.ts +85 -0
- package/dist/interpreter/filesystem/memory.d.ts +3 -0
- package/dist/interpreter/filesystem/opfs.d.ts +3 -0
- package/dist/interpreter/filesystem/scope.d.ts +35 -0
- package/dist/interpreter/filesystem.d.ts +8 -0
- package/dist/interpreter/gate.d.ts +6 -0
- package/dist/interpreter/host-protocol.d.ts +100 -0
- package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
- package/dist/interpreter/http-ingress.d.ts +96 -0
- package/dist/interpreter/http-provider.d.ts +85 -0
- package/dist/interpreter/io.d.ts +20 -0
- package/dist/interpreter/mobile.d.ts +149 -0
- package/dist/interpreter/native-ingress.d.ts +95 -0
- package/dist/interpreter/node-port.d.ts +25 -0
- package/dist/interpreter/node.d.ts +36 -0
- package/dist/interpreter/revision.d.ts +64 -0
- package/dist/interpreter/scope.d.ts +89 -0
- package/dist/interpreter/socket-addresses.d.ts +50 -0
- package/dist/interpreter/socket-provider.d.ts +110 -0
- package/dist/interpreter/standard-cli.d.ts +34 -0
- package/dist/interpreter/standard-codec.d.ts +96 -0
- package/dist/interpreter/standard-filesystem.d.ts +47 -0
- package/dist/interpreter/standard-host.d.ts +71 -0
- package/dist/interpreter/standard-http-values.d.ts +159 -0
- package/dist/interpreter/standard-http.d.ts +9 -0
- package/dist/interpreter/standard-ingress.d.ts +63 -0
- package/dist/interpreter/standard-sockets.d.ts +177 -0
- package/dist/interpreter/standard-streams.d.ts +218 -0
- package/dist/interpreter/standard-system.d.ts +35 -0
- package/dist/interpreter/standard-utf8.d.ts +4 -0
- package/dist/interpreter/standard.d.ts +18 -0
- package/dist/interpreter/types.d.ts +152 -0
- package/dist/interpreter/wit-shape.d.ts +92 -0
- package/dist/manager.js +5 -332
- package/dist/msgpack.js +9 -615
- package/dist/node.d.ts +8 -1
- package/dist/node.js +248 -3287
- package/dist/rpc.js +196 -699
- package/dist/runtime/adapters.d.ts +120 -0
- package/dist/runtime/adapters.js +38 -0
- package/dist/runtime/calls.d.ts +9 -3
- package/dist/runtime/lifecycle.d.ts +3 -1
- package/dist/runtime/orbs.d.ts +5 -4
- package/dist/runtime/references.d.ts +27 -1
- package/dist/runtime/reload.d.ts +5 -3
- package/dist/runtime/scopes.d.ts +1 -1
- package/dist/runtime/signals.d.ts +4 -0
- package/dist/runtime/wit-client.d.ts +38 -0
- package/dist/telemetry.js +4 -25
- package/dist/tooling/build.d.ts +2 -2
- package/dist/tooling/client-resources.d.ts +23 -0
- package/dist/tooling/client.d.ts +10 -0
- package/dist/tooling/component-glue.d.ts +17 -0
- package/dist/tooling/component.d.ts +11 -0
- package/dist/tooling/index.d.ts +3 -1
- package/dist/tooling/index.js +1155 -102
- package/dist/tooling/resolver.d.ts +4 -4
- package/dist/tooling/typecheck.d.ts +2 -1
- package/dist/tooling/types.d.ts +27 -12
- package/dist/tooling/wit.d.ts +9 -0
- package/dist/wasi/wasi-clocks-types.d.ts +2 -0
- package/dist/wasi/wasi-http-client.d.ts +5 -0
- package/dist/wasi/wasi-http-types.d.ts +285 -0
- package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
- package/dist/wasi/wasi-sockets-types.d.ts +146 -0
- package/package.json +62 -35
- package/src/authoring/declaration.ts +1 -1
- package/src/authoring/types.ts +53 -3
- package/src/authoring/wit.ts +15 -0
- package/src/bridge/commands.ts +1105 -0
- package/src/bridge/identifiers.ts +2 -0
- package/src/bridge/kernel.ts +56 -98
- package/src/bridge/protocol.ts +3 -142
- package/src/browser.ts +90 -6
- package/src/context-key.ts +4 -7
- package/src/error.ts +1 -1
- package/src/errors.ts +7 -0
- package/src/guest.ts +327 -0
- package/src/host.ts +128 -23
- package/src/http/bytes.ts +87 -0
- package/src/http/events.ts +34 -0
- package/src/http.ts +272 -0
- package/src/index.ts +3 -0
- package/src/infrastructure/rpc/client.ts +136 -17
- package/src/infrastructure/rpc/resources.ts +123 -0
- package/src/interpreter/abi.ts +69 -0
- package/src/interpreter/acquire.ts +58 -0
- package/src/interpreter/browser-network.ts +170 -0
- package/src/interpreter/browser-port.ts +425 -0
- package/src/interpreter/browser.ts +340 -0
- package/src/interpreter/cli.ts +30 -0
- package/src/interpreter/codec.ts +298 -0
- package/src/interpreter/component/execution.ts +264 -0
- package/src/interpreter/component/host.ts +409 -0
- package/src/interpreter/component/instance.ts +138 -0
- package/src/interpreter/component/kernel.ts +611 -0
- package/src/interpreter/component/names.ts +13 -0
- package/src/interpreter/component/port.ts +598 -0
- package/src/interpreter/component/prepared.ts +194 -0
- package/src/interpreter/component/resources.ts +345 -0
- package/src/interpreter/component/revision.ts +702 -0
- package/src/interpreter/component/scope.ts +447 -0
- package/src/interpreter/component/streams.ts +180 -0
- package/src/interpreter/component/values.ts +254 -0
- package/src/interpreter/component/wasi-filesystem.ts +472 -0
- package/src/interpreter/component/wasi-host.ts +197 -0
- package/src/interpreter/component/wasi-http.ts +939 -0
- package/src/interpreter/component/wasi-sockets.ts +958 -0
- package/src/interpreter/component/wasi.ts +238 -0
- package/src/interpreter/core.ts +386 -0
- package/src/interpreter/fetch-http-provider.ts +98 -0
- package/src/interpreter/filesystem/contract.ts +138 -0
- package/src/interpreter/filesystem/memory.ts +180 -0
- package/src/interpreter/filesystem/opfs.ts +294 -0
- package/src/interpreter/filesystem/scope.ts +390 -0
- package/src/interpreter/filesystem.ts +20 -0
- package/src/interpreter/gate.ts +55 -0
- package/src/interpreter/host-protocol.ts +242 -0
- package/src/interpreter/http-ingress-fetch.ts +133 -0
- package/src/interpreter/http-ingress.ts +203 -0
- package/src/interpreter/http-provider.ts +105 -0
- package/src/interpreter/io.ts +66 -0
- package/src/interpreter/mobile.ts +385 -0
- package/src/interpreter/native-ingress.ts +550 -0
- package/src/interpreter/node-port.ts +218 -0
- package/src/interpreter/node.ts +114 -0
- package/src/interpreter/revision.ts +450 -0
- package/src/interpreter/scope.ts +453 -0
- package/src/interpreter/socket-addresses.ts +246 -0
- package/src/interpreter/socket-provider.ts +126 -0
- package/src/interpreter/standard-cli.ts +184 -0
- package/src/interpreter/standard-codec.ts +403 -0
- package/src/interpreter/standard-filesystem.ts +545 -0
- package/src/interpreter/standard-host.ts +840 -0
- package/src/interpreter/standard-http-values.ts +624 -0
- package/src/interpreter/standard-http.ts +622 -0
- package/src/interpreter/standard-ingress.ts +344 -0
- package/src/interpreter/standard-sockets.ts +847 -0
- package/src/interpreter/standard-streams.ts +710 -0
- package/src/interpreter/standard-system.ts +182 -0
- package/src/interpreter/standard-utf8.ts +72 -0
- package/src/interpreter/standard.ts +283 -0
- package/src/interpreter/types.ts +163 -0
- package/src/interpreter/wit-shape.ts +175 -0
- package/src/node.ts +43 -14
- package/src/runtime/activities.ts +6 -6
- package/src/runtime/adapters.ts +314 -0
- package/src/runtime/calls.ts +218 -56
- package/src/runtime/context.ts +7 -7
- package/src/runtime/lifecycle.ts +36 -17
- package/src/runtime/orbs.ts +81 -39
- package/src/runtime/programs.ts +16 -8
- package/src/runtime/references.ts +128 -11
- package/src/runtime/reload.ts +71 -30
- package/src/runtime/resources.ts +2 -2
- package/src/runtime/scopes.ts +17 -17
- package/src/runtime/session.ts +3 -1
- package/src/runtime/signals.ts +31 -0
- package/src/runtime/wit-client.ts +228 -0
- package/src/tooling/build.ts +152 -54
- package/src/tooling/client-resources.ts +74 -0
- package/src/tooling/client.ts +531 -0
- package/src/tooling/component-glue.ts +288 -0
- package/src/tooling/component.ts +225 -0
- package/src/tooling/index.ts +3 -7
- package/src/tooling/resolver.ts +42 -25
- package/src/tooling/typecheck.ts +59 -4
- package/src/tooling/types.ts +27 -12
- package/src/tooling/wit.ts +188 -0
- package/dist/embedded.d.ts +0 -1
- package/dist/embedded.js +0 -1
- package/src/embedded.ts +0 -293
|
@@ -0,0 +1,939 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outgoing `wasi:http@0.3.0` (`types` and `client`) for trusted JCO bindings.
|
|
3
|
+
*
|
|
4
|
+
* Value semantics (fields, options, request targets) come from `standard-http-values.ts`, which follows
|
|
5
|
+
* pinned upstream `wasmtime-wasi-http`. This module owns bodies and transport: the exact origin
|
|
6
|
+
* grant is checked before any provider call, uploads stream the guest body with backpressure and
|
|
7
|
+
* `Content-Length` enforcement, responses are published once their fields arrived, and body
|
|
8
|
+
* reads honor the between-bytes timeout and the framed length. Provider work is physically owned
|
|
9
|
+
* by the revision; guest-stream reads are bounded by its retirement. Incoming `wasi:http/handler`
|
|
10
|
+
* requests and responses use the same resources through the private `ingress` bridge.
|
|
11
|
+
*/
|
|
12
|
+
import type { ErrorCode } from "wasi:http/types@0.3.0";
|
|
13
|
+
import {
|
|
14
|
+
type HttpField,
|
|
15
|
+
type HttpProvider,
|
|
16
|
+
HttpProviderError,
|
|
17
|
+
type HttpProviderRequest,
|
|
18
|
+
type HttpProviderResponse,
|
|
19
|
+
} from "../http-provider.ts";
|
|
20
|
+
import {
|
|
21
|
+
CONNECTION_TERMINATED,
|
|
22
|
+
type HttpHandlerResponse,
|
|
23
|
+
HttpHandlerError,
|
|
24
|
+
type IncomingHttpRequest,
|
|
25
|
+
type IngressExchange,
|
|
26
|
+
} from "../http-ingress.ts";
|
|
27
|
+
import {
|
|
28
|
+
type HttpBody,
|
|
29
|
+
digits,
|
|
30
|
+
done,
|
|
31
|
+
err,
|
|
32
|
+
HttpFields,
|
|
33
|
+
HttpRequest,
|
|
34
|
+
HttpRequestOptions,
|
|
35
|
+
HttpResponse,
|
|
36
|
+
internal,
|
|
37
|
+
ok,
|
|
38
|
+
type Outcome,
|
|
39
|
+
type Trailers,
|
|
40
|
+
} from "../standard-http-values.ts";
|
|
41
|
+
import {
|
|
42
|
+
abortable,
|
|
43
|
+
cancelled,
|
|
44
|
+
closing,
|
|
45
|
+
guestBytes,
|
|
46
|
+
hostBytes,
|
|
47
|
+
type WasiHost,
|
|
48
|
+
type WasiInterfaces,
|
|
49
|
+
} from "./wasi-host.ts";
|
|
50
|
+
|
|
51
|
+
/** Compiled transport contents and trailers, consumed or dropped once. */
|
|
52
|
+
interface Body extends HttpBody {
|
|
53
|
+
consume(res: unknown): [AsyncIterable<Uint8Array> | object, Promise<Trailers>];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Grant-checked selection of the host transport. */
|
|
57
|
+
export interface HttpClient {
|
|
58
|
+
/** The provider granted for exactly this URL's origin, or `undefined` to deny. */
|
|
59
|
+
provider(url: URL): HttpProvider | undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The per-instance incoming bridge for `wasi:http/handler` (private; wired by the revision). It
|
|
64
|
+
* issues this instance's own `request` resource for an incoming request and delivers the
|
|
65
|
+
* `response` the handler returned. Everything stays within the standard resources, streams and
|
|
66
|
+
* futures; the application side is the existing `IngressExchange` carrier.
|
|
67
|
+
*/
|
|
68
|
+
export interface IngressBridge {
|
|
69
|
+
/**
|
|
70
|
+
* This instance's `request` for `incoming` (from `exchange.own()`); the guest owns it. Invalid
|
|
71
|
+
* input throws a `TypeError` after closing the request body it already owns.
|
|
72
|
+
*/
|
|
73
|
+
request(incoming: IncomingHttpRequest): unknown;
|
|
74
|
+
/**
|
|
75
|
+
* Publish the handler's `response` (this instance's class; anything else is refused) through
|
|
76
|
+
* `exchange.respond` and deliver its body and trailers as the application reads them. Settles
|
|
77
|
+
* when the delivery ended: resolves at the end of the body and trailers or when the application
|
|
78
|
+
* stopped reading (its client disconnected); rejects on a body or trailers failure and when the
|
|
79
|
+
* revision retired first.
|
|
80
|
+
*/
|
|
81
|
+
respond(response: unknown, exchange: IngressExchange): Promise<void>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Cases of `error-code`; a provider-supplied code outside them becomes `internal-error`. */
|
|
85
|
+
const ERROR_TAGS = new Set([
|
|
86
|
+
"DNS-timeout",
|
|
87
|
+
"DNS-error",
|
|
88
|
+
"destination-not-found",
|
|
89
|
+
"destination-unavailable",
|
|
90
|
+
"destination-IP-prohibited",
|
|
91
|
+
"destination-IP-unroutable",
|
|
92
|
+
"connection-refused",
|
|
93
|
+
"connection-terminated",
|
|
94
|
+
"connection-timeout",
|
|
95
|
+
"connection-read-timeout",
|
|
96
|
+
"connection-write-timeout",
|
|
97
|
+
"connection-limit-reached",
|
|
98
|
+
"TLS-protocol-error",
|
|
99
|
+
"TLS-certificate-error",
|
|
100
|
+
"TLS-alert-received",
|
|
101
|
+
"HTTP-request-denied",
|
|
102
|
+
"HTTP-request-length-required",
|
|
103
|
+
"HTTP-request-body-size",
|
|
104
|
+
"HTTP-request-method-invalid",
|
|
105
|
+
"HTTP-request-URI-invalid",
|
|
106
|
+
"HTTP-request-URI-too-long",
|
|
107
|
+
"HTTP-request-header-section-size",
|
|
108
|
+
"HTTP-request-header-size",
|
|
109
|
+
"HTTP-request-trailer-section-size",
|
|
110
|
+
"HTTP-request-trailer-size",
|
|
111
|
+
"HTTP-response-incomplete",
|
|
112
|
+
"HTTP-response-header-section-size",
|
|
113
|
+
"HTTP-response-header-size",
|
|
114
|
+
"HTTP-response-body-size",
|
|
115
|
+
"HTTP-response-trailer-section-size",
|
|
116
|
+
"HTTP-response-trailer-size",
|
|
117
|
+
"HTTP-response-transfer-coding",
|
|
118
|
+
"HTTP-response-content-coding",
|
|
119
|
+
"HTTP-response-timeout",
|
|
120
|
+
"HTTP-upgrade-failed",
|
|
121
|
+
"HTTP-protocol-error",
|
|
122
|
+
"loop-detected",
|
|
123
|
+
"configuration-error",
|
|
124
|
+
"internal-error",
|
|
125
|
+
]);
|
|
126
|
+
|
|
127
|
+
/** Map a failure to an `error-code`; `fallback` names the phase-specific generic code. */
|
|
128
|
+
function errorCode(error: unknown, fallback: (message: string) => ErrorCode = internal): ErrorCode {
|
|
129
|
+
if (error instanceof HttpProviderError || error instanceof HttpHandlerError) {
|
|
130
|
+
const code = error.code as { tag?: unknown } | undefined;
|
|
131
|
+
if (typeof code?.tag === "string" && ERROR_TAGS.has(code.tag)) return code as ErrorCode;
|
|
132
|
+
}
|
|
133
|
+
return fallback(error instanceof Error ? error.message : String(error));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Nanoseconds to timer milliseconds; a duration beyond the timer range means no timer. */
|
|
137
|
+
function millis(duration: bigint | undefined): number | undefined {
|
|
138
|
+
if (duration === undefined) return undefined;
|
|
139
|
+
const ms = (duration + 999_999n) / 1_000_000n;
|
|
140
|
+
return ms > 0x7fffffffn ? undefined : Number(ms);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Read a guest `future<T>` (a thenable or a JCO reader), bounded by `retired`. */
|
|
144
|
+
async function readFuture<T>(future: unknown, retired: AbortSignal): Promise<T> {
|
|
145
|
+
const value = future as { then?: unknown; read?: () => Promise<unknown> };
|
|
146
|
+
if (typeof value?.then === "function")
|
|
147
|
+
return (await abortable(value as Promise<T>, retired)) as T;
|
|
148
|
+
if (typeof value?.read === "function") {
|
|
149
|
+
const read = await abortable(value.read(), retired);
|
|
150
|
+
return (
|
|
151
|
+
read && typeof read === "object" && "done" in read && "value" in read
|
|
152
|
+
? (read as { value: unknown }).value
|
|
153
|
+
: read
|
|
154
|
+
) as T;
|
|
155
|
+
}
|
|
156
|
+
throw new TypeError("expected a guest future");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Wait for `pending` until `signal` aborts or `ms` passes. */
|
|
160
|
+
function deadline<T>(
|
|
161
|
+
pending: Promise<T>,
|
|
162
|
+
signal: AbortSignal | undefined,
|
|
163
|
+
ms: number | undefined,
|
|
164
|
+
): Promise<T> {
|
|
165
|
+
return new Promise<T>((resolve, reject) => {
|
|
166
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
167
|
+
const stop = () => {
|
|
168
|
+
clearTimeout(timer);
|
|
169
|
+
signal?.removeEventListener("abort", abort);
|
|
170
|
+
};
|
|
171
|
+
const abort = () => {
|
|
172
|
+
stop();
|
|
173
|
+
reject(cancelled());
|
|
174
|
+
};
|
|
175
|
+
// Observe the physical promise even if cancellation already happened before this wait.
|
|
176
|
+
pending.then(
|
|
177
|
+
(value) => (stop(), resolve(value)),
|
|
178
|
+
(error) => (stop(), reject(error)),
|
|
179
|
+
);
|
|
180
|
+
if (signal?.aborted) return abort();
|
|
181
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
182
|
+
if (ms !== undefined)
|
|
183
|
+
timer = setTimeout(() => {
|
|
184
|
+
stop();
|
|
185
|
+
reject(new HttpProviderError({ tag: "connection-read-timeout" } as never));
|
|
186
|
+
}, ms);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** A response's framed body length; `undefined` where HTTP defines no body or none was declared. */
|
|
191
|
+
function framedLength(method: string, status: number, fields: HttpFields): bigint | undefined {
|
|
192
|
+
if (method === "HEAD" || status < 200 || status === 204 || status === 304) return undefined;
|
|
193
|
+
const declared = new Set(fields.get("content-length").map(digits));
|
|
194
|
+
if (declared.size > 1)
|
|
195
|
+
throw new HttpProviderError(
|
|
196
|
+
internal("the HTTP provider returned conflicting lengths") as never,
|
|
197
|
+
);
|
|
198
|
+
const [length] = declared;
|
|
199
|
+
return length === undefined ? undefined : BigInt(length);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The `wasi:http/types` and `client` import objects of one instance. */
|
|
203
|
+
export function httpImports(
|
|
204
|
+
host: WasiHost,
|
|
205
|
+
client: HttpClient | undefined,
|
|
206
|
+
): WasiInterfaces<"types" | "client"> & { ingress: IngressBridge } {
|
|
207
|
+
/** A body the guest wrote: its contents stream, its trailers future and its transmission result. */
|
|
208
|
+
class GuestBody implements Body {
|
|
209
|
+
readonly result: Promise<Outcome>;
|
|
210
|
+
#settle!: (outcome: Outcome) => void;
|
|
211
|
+
#taken = false;
|
|
212
|
+
/** The trailers future reader was taken (read for a consumer, or released). */
|
|
213
|
+
#trailersTaken = false;
|
|
214
|
+
constructor(
|
|
215
|
+
readonly contents: unknown,
|
|
216
|
+
readonly trailers: unknown,
|
|
217
|
+
) {
|
|
218
|
+
this.result = new Promise((resolve) => (this.#settle = resolve));
|
|
219
|
+
}
|
|
220
|
+
settle(outcome: Outcome): void {
|
|
221
|
+
this.#settle(outcome);
|
|
222
|
+
}
|
|
223
|
+
/** Take the trailers future reader exactly once. */
|
|
224
|
+
#readTrailers(): Promise<Trailers> {
|
|
225
|
+
this.#trailersTaken = true;
|
|
226
|
+
return readFuture<Trailers>(this.trailers, host.retired);
|
|
227
|
+
}
|
|
228
|
+
/** Pass the guest's own stream and trailers through to the consumer. */
|
|
229
|
+
consume(res: unknown): [object, Promise<Trailers>] {
|
|
230
|
+
this.#taken = true;
|
|
231
|
+
readFuture<Outcome>(res, host.retired).then(
|
|
232
|
+
(outcome) => this.settle(outcome),
|
|
233
|
+
() => this.settle(done),
|
|
234
|
+
);
|
|
235
|
+
const contents =
|
|
236
|
+
this.contents ??
|
|
237
|
+
hostBytes(
|
|
238
|
+
async () => undefined,
|
|
239
|
+
() => {},
|
|
240
|
+
host.retired,
|
|
241
|
+
);
|
|
242
|
+
return [contents as object, this.#readTrailers()];
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Release a body nobody will read (a refused `send`, a message dropped unconsumed), once:
|
|
246
|
+
* the guest's contents stream is dropped, so its writer sees the reader gone, and the
|
|
247
|
+
* trailers future is read and its value released. JCO gives the host a guest future only as
|
|
248
|
+
* a lazy thenable without a drop, and the guest's future write completes only when its reader
|
|
249
|
+
* reads; left alone, that write keeps the guest's task suspended.
|
|
250
|
+
*/
|
|
251
|
+
discard(): void {
|
|
252
|
+
if (!this.#taken) {
|
|
253
|
+
this.#taken = true;
|
|
254
|
+
try {
|
|
255
|
+
(this.contents as { [Symbol.dispose]?: () => void } | undefined)?.[Symbol.dispose]?.();
|
|
256
|
+
} catch {
|
|
257
|
+
/* Already gone with its instance. */
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (this.#trailersTaken) return;
|
|
261
|
+
const trailers = this.trailers as { then?: unknown; read?: unknown } | null;
|
|
262
|
+
if (typeof trailers?.then !== "function" && typeof trailers?.read !== "function") {
|
|
263
|
+
this.#trailersTaken = true;
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
this.#readTrailers().then(
|
|
267
|
+
(value) => {
|
|
268
|
+
if (value?.tag === "ok") value.val?.release();
|
|
269
|
+
},
|
|
270
|
+
() => {},
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* The upload a provider reads, with `Content-Length` enforced. `completed` resolves `true` at
|
|
275
|
+
* the guest's end of body, `false` when the provider stopped reading early (as upstream, not a
|
|
276
|
+
* transmission failure by itself), and rejects only on a body failure: a length mismatch or a
|
|
277
|
+
* lost guest stream. The trailers' own error reaches the provider through `trailers`.
|
|
278
|
+
*/
|
|
279
|
+
upload(declared: bigint | undefined): {
|
|
280
|
+
body: ReadableStream<Uint8Array> | null;
|
|
281
|
+
trailers: Promise<readonly [string, Uint8Array][] | undefined>;
|
|
282
|
+
completed: Promise<boolean>;
|
|
283
|
+
/**
|
|
284
|
+
* The exchange failed: release the guest's body writer even when the provider never read
|
|
285
|
+
* or cancelled the upload, and fail the provider's pending or later reads.
|
|
286
|
+
*/
|
|
287
|
+
abort(reason: unknown): void;
|
|
288
|
+
} {
|
|
289
|
+
this.#taken = true;
|
|
290
|
+
let complete!: (finished: boolean) => void;
|
|
291
|
+
let fail!: (error: unknown) => void;
|
|
292
|
+
const completed = new Promise<boolean>(
|
|
293
|
+
(resolve, reject) => ((complete = resolve), (fail = reject)),
|
|
294
|
+
);
|
|
295
|
+
completed.catch(() => {});
|
|
296
|
+
const trailers = this.#readTrailers().then((value) => {
|
|
297
|
+
if (value.tag === "err") throw new HttpProviderError(value.val as never);
|
|
298
|
+
const pairs = value.val?.pairs();
|
|
299
|
+
value.val?.release();
|
|
300
|
+
return pairs;
|
|
301
|
+
});
|
|
302
|
+
trailers.catch(() => {});
|
|
303
|
+
if (this.contents === undefined) {
|
|
304
|
+
if (declared !== undefined && declared !== 0n) {
|
|
305
|
+
fail(
|
|
306
|
+
new HttpProviderError({
|
|
307
|
+
tag: "HTTP-request-body-size",
|
|
308
|
+
val: 0n,
|
|
309
|
+
} as never),
|
|
310
|
+
);
|
|
311
|
+
} else trailers.then(() => complete(true), fail);
|
|
312
|
+
return { body: null, trailers, completed, abort() {} };
|
|
313
|
+
}
|
|
314
|
+
const input = guestBytes(this.contents, host.retired);
|
|
315
|
+
let sent = 0n;
|
|
316
|
+
let stopped = false;
|
|
317
|
+
let source: ReadableStreamDefaultController<Uint8Array> | undefined;
|
|
318
|
+
const body = new ReadableStream<Uint8Array>(
|
|
319
|
+
{
|
|
320
|
+
start(controller) {
|
|
321
|
+
source = controller;
|
|
322
|
+
},
|
|
323
|
+
async pull(controller) {
|
|
324
|
+
try {
|
|
325
|
+
const next = await input.next();
|
|
326
|
+
if (stopped) return;
|
|
327
|
+
if (next.done) {
|
|
328
|
+
if (declared !== undefined && sent !== declared)
|
|
329
|
+
throw new HttpProviderError({
|
|
330
|
+
tag: "HTTP-request-body-size",
|
|
331
|
+
val: sent,
|
|
332
|
+
} as never);
|
|
333
|
+
// EOF is successful only after the guest's completion future succeeded.
|
|
334
|
+
// Never let a provider commit bytes whose trailers later report failure.
|
|
335
|
+
await trailers;
|
|
336
|
+
if (stopped) return;
|
|
337
|
+
stopped = true;
|
|
338
|
+
controller.close();
|
|
339
|
+
complete(true);
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
sent += BigInt(next.value.byteLength);
|
|
343
|
+
if (declared !== undefined && sent > declared)
|
|
344
|
+
throw new HttpProviderError({
|
|
345
|
+
tag: "HTTP-request-body-size",
|
|
346
|
+
val: sent,
|
|
347
|
+
} as never);
|
|
348
|
+
controller.enqueue(next.value);
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (stopped) return;
|
|
351
|
+
stopped = true;
|
|
352
|
+
void input.return!();
|
|
353
|
+
fail(error);
|
|
354
|
+
controller.error(error);
|
|
355
|
+
}
|
|
356
|
+
},
|
|
357
|
+
cancel() {
|
|
358
|
+
// The provider stopped reading: the guest's writer sees its reader dropped.
|
|
359
|
+
if (stopped) return;
|
|
360
|
+
stopped = true;
|
|
361
|
+
void input.return!();
|
|
362
|
+
complete(false);
|
|
363
|
+
},
|
|
364
|
+
},
|
|
365
|
+
// Strict backpressure: nothing is read from the guest before the provider asks for it.
|
|
366
|
+
{ highWaterMark: 0 },
|
|
367
|
+
);
|
|
368
|
+
const abort = (reason: unknown) => {
|
|
369
|
+
if (stopped) return;
|
|
370
|
+
stopped = true;
|
|
371
|
+
void input.return!();
|
|
372
|
+
try {
|
|
373
|
+
source?.error(reason);
|
|
374
|
+
} catch {
|
|
375
|
+
/* Already closed or errored. */
|
|
376
|
+
}
|
|
377
|
+
fail(reason);
|
|
378
|
+
};
|
|
379
|
+
return { body, trailers, completed, abort };
|
|
380
|
+
}
|
|
381
|
+
/** Dropped unconsumed: released, and its transmission result settles. */
|
|
382
|
+
close(): void {
|
|
383
|
+
if (this.#taken) return;
|
|
384
|
+
this.discard();
|
|
385
|
+
this.settle(done);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** A body received from a provider. */
|
|
390
|
+
class ReceivedBody implements Body {
|
|
391
|
+
#consumed = false;
|
|
392
|
+
#released = false;
|
|
393
|
+
readonly #retire = () => this.#release();
|
|
394
|
+
constructor(
|
|
395
|
+
readonly reader: ReadableStreamDefaultReader<Uint8Array> | undefined,
|
|
396
|
+
readonly trailers: Promise<readonly HttpField[] | undefined> | undefined,
|
|
397
|
+
readonly length: bigint | undefined,
|
|
398
|
+
readonly between: number | undefined,
|
|
399
|
+
readonly exchange: AbortController,
|
|
400
|
+
readonly abortUpload: (reason: unknown) => void,
|
|
401
|
+
) {
|
|
402
|
+
trailers?.catch(() => {});
|
|
403
|
+
host.retired.addEventListener("abort", this.#retire, { once: true });
|
|
404
|
+
}
|
|
405
|
+
consume(res: unknown): [object, Promise<Trailers>] {
|
|
406
|
+
this.#consumed = true;
|
|
407
|
+
readFuture<Outcome>(res, host.retired).then(
|
|
408
|
+
(outcome) => outcome.tag === "err" && this.#release(),
|
|
409
|
+
() => this.#release(),
|
|
410
|
+
);
|
|
411
|
+
let received = 0n;
|
|
412
|
+
let settle!: (value: Trailers) => void;
|
|
413
|
+
const trailers = new Promise<Trailers>((resolve) => (settle = resolve));
|
|
414
|
+
const reader = this.reader;
|
|
415
|
+
const stream = hostBytes(
|
|
416
|
+
async () => {
|
|
417
|
+
for (;;) {
|
|
418
|
+
const next = reader
|
|
419
|
+
? await host.physical(() =>
|
|
420
|
+
deadline(reader.read(), this.exchange.signal, this.between),
|
|
421
|
+
)
|
|
422
|
+
: { done: true as const, value: undefined };
|
|
423
|
+
if (next.done) {
|
|
424
|
+
if (this.length !== undefined && received !== this.length)
|
|
425
|
+
throw new HttpProviderError({ tag: "HTTP-response-incomplete" } as never);
|
|
426
|
+
return undefined;
|
|
427
|
+
}
|
|
428
|
+
if (!(next.value instanceof Uint8Array))
|
|
429
|
+
throw new HttpProviderError(
|
|
430
|
+
internal("the HTTP provider produced a non-byte chunk") as never,
|
|
431
|
+
);
|
|
432
|
+
if (!next.value.byteLength) continue;
|
|
433
|
+
received += BigInt(next.value.byteLength);
|
|
434
|
+
if (this.length !== undefined && received > this.length)
|
|
435
|
+
throw new HttpProviderError({
|
|
436
|
+
tag: "HTTP-response-body-size",
|
|
437
|
+
val: received,
|
|
438
|
+
} as never);
|
|
439
|
+
return next.value;
|
|
440
|
+
}
|
|
441
|
+
},
|
|
442
|
+
(end, failure) => {
|
|
443
|
+
if (end !== "eof") {
|
|
444
|
+
this.#release();
|
|
445
|
+
settle(
|
|
446
|
+
err(
|
|
447
|
+
end === "failed"
|
|
448
|
+
? errorCode(
|
|
449
|
+
failure,
|
|
450
|
+
(message) => ({ tag: "HTTP-protocol-error", val: message }) as never,
|
|
451
|
+
)
|
|
452
|
+
: internal("response body was dropped"),
|
|
453
|
+
),
|
|
454
|
+
);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
abortable(Promise.resolve(this.trailers), host.retired)
|
|
458
|
+
.then((pairs) => settle(ok(pairs ? HttpFields.received(pairs) : undefined)))
|
|
459
|
+
.catch((error) => {
|
|
460
|
+
this.#release();
|
|
461
|
+
settle(err(errorCode(error)));
|
|
462
|
+
})
|
|
463
|
+
.finally(() => host.retired.removeEventListener("abort", this.#retire));
|
|
464
|
+
},
|
|
465
|
+
host.retired,
|
|
466
|
+
);
|
|
467
|
+
return [stream, trailers];
|
|
468
|
+
}
|
|
469
|
+
close(): void {
|
|
470
|
+
if (this.#consumed) return;
|
|
471
|
+
this.#consumed = true;
|
|
472
|
+
this.#release();
|
|
473
|
+
}
|
|
474
|
+
/** One physical exchange close, including a retained response or moved body at retirement. */
|
|
475
|
+
#release(): void {
|
|
476
|
+
if (this.#released) return;
|
|
477
|
+
this.#released = true;
|
|
478
|
+
host.retired.removeEventListener("abort", this.#retire);
|
|
479
|
+
this.exchange.abort();
|
|
480
|
+
this.abortUpload(
|
|
481
|
+
new HttpProviderError(
|
|
482
|
+
internal("response was released before its request body completed") as never,
|
|
483
|
+
),
|
|
484
|
+
);
|
|
485
|
+
const reader = this.reader;
|
|
486
|
+
if (reader) closing(host, () => reader.cancel().catch(() => {}));
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
class Request extends HttpRequest<Body> {
|
|
491
|
+
static new(
|
|
492
|
+
headers: HttpFields,
|
|
493
|
+
contents: unknown,
|
|
494
|
+
trailers: unknown,
|
|
495
|
+
options: HttpRequestOptions | undefined,
|
|
496
|
+
) {
|
|
497
|
+
const body = new GuestBody(contents, trailers);
|
|
498
|
+
return [new Request(headers.frozen(), options?.timeouts, body), body.result];
|
|
499
|
+
}
|
|
500
|
+
static consumeBody(self: Request, res: unknown) {
|
|
501
|
+
if (!(self instanceof Request)) throw new TypeError("Foreign HTTP request");
|
|
502
|
+
return self.take().consume(res);
|
|
503
|
+
}
|
|
504
|
+
[Symbol.dispose](): void {
|
|
505
|
+
this.release();
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
class Response extends HttpResponse<Body> {
|
|
509
|
+
static new(headers: HttpFields, contents: unknown, trailers: unknown) {
|
|
510
|
+
const body = new GuestBody(contents, trailers);
|
|
511
|
+
return [new Response(headers.frozen(), body), body.result];
|
|
512
|
+
}
|
|
513
|
+
static consumeBody(self: Response, res: unknown) {
|
|
514
|
+
if (!(self instanceof Response)) throw new TypeError("Foreign HTTP response");
|
|
515
|
+
return self.take().consume(res);
|
|
516
|
+
}
|
|
517
|
+
[Symbol.dispose](): void {
|
|
518
|
+
this.release();
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** A late or refused provider response has no guest owner for either body or trailers. */
|
|
523
|
+
function discard(response: HttpProviderResponse | undefined): void {
|
|
524
|
+
response?.trailers?.catch(() => {});
|
|
525
|
+
const body = response?.body;
|
|
526
|
+
if (body instanceof ReadableStream) closing(host, () => body.cancel().catch(() => {}));
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* `client.send`. Ownership of the request moves at this first turn, so everything the exchange
|
|
531
|
+
* needs is captured before the first `await`; the exact origin grant is checked before any
|
|
532
|
+
* provider call.
|
|
533
|
+
*/
|
|
534
|
+
async function send(request: Request) {
|
|
535
|
+
if (!(request instanceof Request)) throw new TypeError("Foreign HTTP request");
|
|
536
|
+
const body = request.take() as GuestBody;
|
|
537
|
+
const method = request.methodName;
|
|
538
|
+
const timeouts = Object.freeze({ ...request.options });
|
|
539
|
+
const target = request.target();
|
|
540
|
+
// A refusal before any provider call releases the unread body, so the guest's writers finish
|
|
541
|
+
// and the refusal stays a recoverable `err`.
|
|
542
|
+
if (target.tag === "err") {
|
|
543
|
+
body.settle(err(target.val));
|
|
544
|
+
body.discard();
|
|
545
|
+
return target;
|
|
546
|
+
}
|
|
547
|
+
const provider = client?.provider(target.val.url);
|
|
548
|
+
if (!provider) {
|
|
549
|
+
body.settle(err({ tag: "HTTP-request-denied" } as ErrorCode));
|
|
550
|
+
body.discard();
|
|
551
|
+
return err({ tag: "HTTP-request-denied" } as ErrorCode);
|
|
552
|
+
}
|
|
553
|
+
const declared = request.headers.get("content-length")[0];
|
|
554
|
+
const upload = body.upload(declared && BigInt(digits(declared)));
|
|
555
|
+
const exchange = new AbortController();
|
|
556
|
+
const outgoing: HttpProviderRequest = Object.freeze({
|
|
557
|
+
url: target.val.url,
|
|
558
|
+
pathWithQuery: target.val.pathWithQuery,
|
|
559
|
+
method,
|
|
560
|
+
fields: request.headers.pairs(),
|
|
561
|
+
body: upload.body,
|
|
562
|
+
trailers: upload.trailers,
|
|
563
|
+
timeouts,
|
|
564
|
+
signal: exchange.signal,
|
|
565
|
+
});
|
|
566
|
+
const fail = (code: ErrorCode) => {
|
|
567
|
+
exchange.abort();
|
|
568
|
+
body.settle(err(code));
|
|
569
|
+
upload.abort(new HttpProviderError(code as never));
|
|
570
|
+
return err(code);
|
|
571
|
+
};
|
|
572
|
+
// A body failure ends the exchange; an early stop by the provider leaves it to the provider.
|
|
573
|
+
upload.completed.catch((error) => fail(errorCode(error)));
|
|
574
|
+
const signal = host.signal();
|
|
575
|
+
if (signal.aborted) return fail(internal("request was cancelled"));
|
|
576
|
+
let pending!: Promise<HttpProviderResponse>;
|
|
577
|
+
let response: HttpProviderResponse;
|
|
578
|
+
try {
|
|
579
|
+
response = await deadline(
|
|
580
|
+
host.physical(() => {
|
|
581
|
+
if (signal.aborted) return Promise.reject(cancelled());
|
|
582
|
+
return (pending = provider.send(outgoing));
|
|
583
|
+
}),
|
|
584
|
+
signal,
|
|
585
|
+
millis(timeouts.firstByte),
|
|
586
|
+
);
|
|
587
|
+
} catch (error) {
|
|
588
|
+
// The provider's late result still belongs to the revision, although the caller stopped
|
|
589
|
+
// waiting. Release its body when it arrives instead of leaking the unread connection.
|
|
590
|
+
pending?.then(discard, () => {});
|
|
591
|
+
if (signal.aborted) {
|
|
592
|
+
// The caller observes cancellation separately. Let the guest finish this standard
|
|
593
|
+
// result import cooperatively; throwing here would turn cancellation into a trap.
|
|
594
|
+
return fail(internal("request was cancelled"));
|
|
595
|
+
}
|
|
596
|
+
return fail(errorCode(error));
|
|
597
|
+
}
|
|
598
|
+
let fields: HttpFields;
|
|
599
|
+
let length: bigint | undefined;
|
|
600
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
601
|
+
try {
|
|
602
|
+
const status = response?.status;
|
|
603
|
+
if (!Number.isInteger(status) || status < 100 || status > 999)
|
|
604
|
+
throw new HttpProviderError(
|
|
605
|
+
internal("the HTTP provider returned an invalid status") as never,
|
|
606
|
+
);
|
|
607
|
+
fields = HttpFields.received(response.fields);
|
|
608
|
+
length = framedLength(method, status, fields);
|
|
609
|
+
if (response.body !== null && !(response.body instanceof ReadableStream))
|
|
610
|
+
throw new HttpProviderError(
|
|
611
|
+
internal("the HTTP provider returned an invalid body") as never,
|
|
612
|
+
);
|
|
613
|
+
reader = response.body?.getReader();
|
|
614
|
+
} catch (error) {
|
|
615
|
+
discard(response);
|
|
616
|
+
return fail(errorCode(error));
|
|
617
|
+
}
|
|
618
|
+
// After a response, the transmission succeeded once the body ended or the provider stopped
|
|
619
|
+
// reading it (upstream: a dropped body sender is success).
|
|
620
|
+
upload.completed.then(
|
|
621
|
+
() => body.settle(done),
|
|
622
|
+
() => {},
|
|
623
|
+
);
|
|
624
|
+
const received = new ReceivedBody(
|
|
625
|
+
reader,
|
|
626
|
+
response.trailers,
|
|
627
|
+
length,
|
|
628
|
+
millis(timeouts.betweenBytes),
|
|
629
|
+
exchange,
|
|
630
|
+
upload.abort,
|
|
631
|
+
);
|
|
632
|
+
return ok(new Response(fields, received, response.status));
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* An incoming request's contents, pulled from the application's iterable only as the handler
|
|
637
|
+
* reads. The iterator's `return()` runs once, as tracked cleanup, when the handler drops the
|
|
638
|
+
* body early, when the exchange ends early, or when the call ends with the body unfinished.
|
|
639
|
+
*/
|
|
640
|
+
class IncomingBody implements Body {
|
|
641
|
+
#iterator: AsyncIterator<Uint8Array> | undefined;
|
|
642
|
+
#stopped = false;
|
|
643
|
+
#finished = false;
|
|
644
|
+
#terminated: ErrorCode | undefined;
|
|
645
|
+
readonly #stop = new AbortController();
|
|
646
|
+
/** A response delivery is reading; the call's end then waits for that delivery. */
|
|
647
|
+
delivering = false;
|
|
648
|
+
/** The handler call ended. */
|
|
649
|
+
callEnded = false;
|
|
650
|
+
|
|
651
|
+
constructor(
|
|
652
|
+
readonly source: AsyncIterable<Uint8Array> | null,
|
|
653
|
+
readonly trailers: PromiseLike<readonly HttpField[] | undefined> | undefined,
|
|
654
|
+
) {
|
|
655
|
+
if (typeof trailers?.then === "function") Promise.resolve(trailers).catch(() => {});
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
consume(res: unknown): [object, Promise<Trailers>] {
|
|
659
|
+
// The application has no use for the handler's processing result.
|
|
660
|
+
readFuture<unknown>(res, host.retired).catch(() => {});
|
|
661
|
+
let settle!: (value: Trailers) => void;
|
|
662
|
+
const trailers = new Promise<Trailers>((resolve) => (settle = resolve));
|
|
663
|
+
const stream = hostBytes(
|
|
664
|
+
() => this.#read(),
|
|
665
|
+
(end, failure) => {
|
|
666
|
+
if (end !== "eof") {
|
|
667
|
+
this.#release();
|
|
668
|
+
settle(end === "failed" ? err(errorCode(failure)) : ok(undefined));
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
this.#finished = true;
|
|
672
|
+
if (!this.trailers) return settle(ok(undefined));
|
|
673
|
+
Promise.resolve(this.trailers).then(
|
|
674
|
+
(pairs) => {
|
|
675
|
+
try {
|
|
676
|
+
settle(ok(pairs?.length ? HttpFields.received(pairs) : undefined));
|
|
677
|
+
} catch (error) {
|
|
678
|
+
settle(err(errorCode(error)));
|
|
679
|
+
}
|
|
680
|
+
},
|
|
681
|
+
(error) => settle(err(errorCode(error))),
|
|
682
|
+
);
|
|
683
|
+
},
|
|
684
|
+
host.retired,
|
|
685
|
+
);
|
|
686
|
+
return [stream, trailers];
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** The next non-empty chunk, or `undefined` at the end; a terminated body fails the read. */
|
|
690
|
+
async #read(): Promise<Uint8Array | undefined> {
|
|
691
|
+
if (this.#terminated) throw new HttpProviderError(this.#terminated as never);
|
|
692
|
+
if (!this.source || this.#stopped) return undefined;
|
|
693
|
+
this.#iterator ??= this.source[Symbol.asyncIterator]();
|
|
694
|
+
for (;;) {
|
|
695
|
+
let next: IteratorResult<Uint8Array>;
|
|
696
|
+
try {
|
|
697
|
+
next = await abortable(this.#iterator.next(), this.#stop.signal);
|
|
698
|
+
} catch (error) {
|
|
699
|
+
if (this.#terminated) throw new HttpProviderError(this.#terminated as never);
|
|
700
|
+
throw error;
|
|
701
|
+
}
|
|
702
|
+
if (next.done) {
|
|
703
|
+
this.#iterator = undefined;
|
|
704
|
+
return undefined;
|
|
705
|
+
}
|
|
706
|
+
if (!(next.value instanceof Uint8Array))
|
|
707
|
+
throw new HttpProviderError(
|
|
708
|
+
internal("incoming request chunks must be Uint8Array") as never,
|
|
709
|
+
);
|
|
710
|
+
if (next.value.byteLength) return next.value;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Stop the application's iterable once. Its factory, `return` lookup and call are guarded,
|
|
716
|
+
* but its completion belongs to the application: neither the call nor retirement waits on
|
|
717
|
+
* an application iterator whose `return` promise never settles.
|
|
718
|
+
*/
|
|
719
|
+
#release(): void {
|
|
720
|
+
if (this.#stopped) return;
|
|
721
|
+
this.#stopped = true;
|
|
722
|
+
const iterator = this.#iterator;
|
|
723
|
+
const source = this.source;
|
|
724
|
+
this.#iterator = undefined;
|
|
725
|
+
if (iterator || source)
|
|
726
|
+
// The contract calls the application's `return()` without awaiting it in the call.
|
|
727
|
+
void Promise.resolve()
|
|
728
|
+
.then(() => (iterator ?? source![Symbol.asyncIterator]()).return?.())
|
|
729
|
+
.catch(() => {});
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** The exchange ended: a pending or later read fails with `code`. */
|
|
733
|
+
terminate(code: ErrorCode): void {
|
|
734
|
+
if (this.#terminated || this.#finished) return this.#release();
|
|
735
|
+
this.#terminated = code;
|
|
736
|
+
this.#stop.abort();
|
|
737
|
+
this.#release();
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** Dropped unconsumed. */
|
|
741
|
+
close(): void {
|
|
742
|
+
this.#release();
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** Received fields of the application; an invalid name or value is its error. */
|
|
747
|
+
const incomingFields = (pairs: readonly HttpField[], what: string) => {
|
|
748
|
+
try {
|
|
749
|
+
return HttpFields.received(pairs);
|
|
750
|
+
} catch {
|
|
751
|
+
throw new TypeError(`invalid incoming ${what} field`);
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
/** Request bodies issued by this instance, by the exchange's request. */
|
|
756
|
+
const incoming = new WeakMap<IncomingHttpRequest, IncomingBody>();
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* The response the handler published, read by the application. The delivery ends once:
|
|
760
|
+
* - end of body and trailers: the transmission result is `ok`, or the trailers' own error;
|
|
761
|
+
* - the application stopped reading (`return()`): its client disconnected; the handler sees
|
|
762
|
+
* `connection-terminated`, its request body is closed and its next write fails;
|
|
763
|
+
* - the revision retired: same signals, and a pending or later read rejects with the reason.
|
|
764
|
+
*/
|
|
765
|
+
function deliver(published: Response, exchange: IngressExchange): Promise<void> {
|
|
766
|
+
const status = published.getStatusCode();
|
|
767
|
+
const pairs = published.headers.pairs();
|
|
768
|
+
const body = published.take();
|
|
769
|
+
// The response's own reference moved here; its body lives on alone.
|
|
770
|
+
published.release();
|
|
771
|
+
const request = incoming.get(exchange.request);
|
|
772
|
+
if (request) request.delivering = true;
|
|
773
|
+
let transmitted!: (outcome: Outcome) => void;
|
|
774
|
+
const transmission = new Promise<Outcome>((resolve) => (transmitted = resolve));
|
|
775
|
+
const [contents, future] = body.consume(transmission);
|
|
776
|
+
const chunks: AsyncIterator<Uint8Array> =
|
|
777
|
+
typeof (contents as { read?: unknown }).read === "function"
|
|
778
|
+
? guestBytes(contents, host.retired)
|
|
779
|
+
: (contents as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]();
|
|
780
|
+
const written = future.then((result) => {
|
|
781
|
+
if (result.tag === "err") throw new HttpHandlerError(result.val);
|
|
782
|
+
const fields = result.val?.pairs();
|
|
783
|
+
result.val?.release();
|
|
784
|
+
return fields?.length ? fields : undefined;
|
|
785
|
+
});
|
|
786
|
+
let stopTrailers!: (reason: unknown) => void;
|
|
787
|
+
const stopped = new Promise<never>((_, reject) => (stopTrailers = reject));
|
|
788
|
+
const trailers = Promise.race([written, stopped]);
|
|
789
|
+
for (const promise of [written, stopped, trailers]) promise.catch(() => {});
|
|
790
|
+
let resolveEnd!: () => void;
|
|
791
|
+
let rejectEnd!: (error: unknown) => void;
|
|
792
|
+
const ended = new Promise<void>((resolve, reject) => {
|
|
793
|
+
resolveEnd = resolve;
|
|
794
|
+
rejectEnd = reject;
|
|
795
|
+
});
|
|
796
|
+
ended.catch(() => {});
|
|
797
|
+
let finished = false;
|
|
798
|
+
let started = false;
|
|
799
|
+
let failure: unknown;
|
|
800
|
+
const finish = (outcome: Outcome, error?: unknown) => {
|
|
801
|
+
if (finished) return;
|
|
802
|
+
finished = true;
|
|
803
|
+
signal.removeEventListener("abort", retire);
|
|
804
|
+
transmitted(outcome);
|
|
805
|
+
if (request) {
|
|
806
|
+
request.delivering = false;
|
|
807
|
+
if (outcome.tag === "err" || request.callEnded) request.terminate(CONNECTION_TERMINATED);
|
|
808
|
+
}
|
|
809
|
+
if (error === undefined) resolveEnd();
|
|
810
|
+
else rejectEnd(error);
|
|
811
|
+
};
|
|
812
|
+
/** The application stopped reading, or the revision retired with `reason`. */
|
|
813
|
+
const disconnect = (reason?: unknown) => {
|
|
814
|
+
if (finished) return;
|
|
815
|
+
failure = reason;
|
|
816
|
+
void chunks.return?.();
|
|
817
|
+
stopTrailers(reason ?? new HttpHandlerError(CONNECTION_TERMINATED));
|
|
818
|
+
finish(err(CONNECTION_TERMINATED), reason);
|
|
819
|
+
};
|
|
820
|
+
// The delivery is physical work of the handler's callback: the callback (its admission, its
|
|
821
|
+
// scope and its deadline) lasts until the delivery ended, since the guest may still produce
|
|
822
|
+
// the body after its export task returned. Cancellation, the deadline and retirement abort it.
|
|
823
|
+
const signal = host.signal();
|
|
824
|
+
const retire = () => disconnect(cancelled());
|
|
825
|
+
if (signal.aborted) queueMicrotask(retire);
|
|
826
|
+
else signal.addEventListener("abort", retire, { once: true });
|
|
827
|
+
host.physical(() => ended).catch(() => {});
|
|
828
|
+
const next = async (): Promise<IteratorResult<Uint8Array>> => {
|
|
829
|
+
if (finished) {
|
|
830
|
+
if (failure !== undefined) throw failure;
|
|
831
|
+
return { done: true, value: undefined };
|
|
832
|
+
}
|
|
833
|
+
let chunk: IteratorResult<Uint8Array>;
|
|
834
|
+
try {
|
|
835
|
+
chunk = await chunks.next();
|
|
836
|
+
} catch (error) {
|
|
837
|
+
if (finished) throw failure ?? error;
|
|
838
|
+
finish(err(errorCode(error)), error);
|
|
839
|
+
throw error;
|
|
840
|
+
}
|
|
841
|
+
// A delivery that ended meanwhile never reports a clean end of body for it.
|
|
842
|
+
if (finished) {
|
|
843
|
+
if (failure !== undefined) throw failure;
|
|
844
|
+
return { done: true, value: undefined };
|
|
845
|
+
}
|
|
846
|
+
if (!chunk.done) return { done: false, value: chunk.value };
|
|
847
|
+
// The body ended; the transmission completes with the trailers.
|
|
848
|
+
try {
|
|
849
|
+
await trailers;
|
|
850
|
+
} catch (error) {
|
|
851
|
+
if (finished) throw failure ?? error;
|
|
852
|
+
finish(err(errorCode(error)), error);
|
|
853
|
+
throw error;
|
|
854
|
+
}
|
|
855
|
+
if (finished) {
|
|
856
|
+
if (failure !== undefined) throw failure;
|
|
857
|
+
return { done: true, value: undefined };
|
|
858
|
+
}
|
|
859
|
+
finish(done);
|
|
860
|
+
return { done: true, value: undefined };
|
|
861
|
+
};
|
|
862
|
+
exchange.respond(
|
|
863
|
+
Object.freeze({
|
|
864
|
+
status,
|
|
865
|
+
fields: Object.freeze(pairs.map((pair) => Object.freeze(pair) as HttpField)),
|
|
866
|
+
body: Object.freeze({
|
|
867
|
+
[Symbol.asyncIterator]: (): AsyncIterator<Uint8Array> => {
|
|
868
|
+
if (started) throw new TypeError("the response body is read once");
|
|
869
|
+
started = true;
|
|
870
|
+
return {
|
|
871
|
+
next,
|
|
872
|
+
return: async () => {
|
|
873
|
+
disconnect();
|
|
874
|
+
return { done: true, value: undefined };
|
|
875
|
+
},
|
|
876
|
+
};
|
|
877
|
+
},
|
|
878
|
+
}),
|
|
879
|
+
trailers,
|
|
880
|
+
}) satisfies HttpHandlerResponse,
|
|
881
|
+
);
|
|
882
|
+
return ended;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
const ingress: IngressBridge = {
|
|
886
|
+
request(parts: IncomingHttpRequest) {
|
|
887
|
+
const body = new IncomingBody(parts.body, parts.trailers);
|
|
888
|
+
let headers: HttpFields;
|
|
889
|
+
try {
|
|
890
|
+
headers = incomingFields(parts.fields, "request");
|
|
891
|
+
} catch (error) {
|
|
892
|
+
body.close();
|
|
893
|
+
throw error;
|
|
894
|
+
}
|
|
895
|
+
const request = new Request(headers, undefined, body);
|
|
896
|
+
const refuse = (what: string) => {
|
|
897
|
+
request.release();
|
|
898
|
+
return new TypeError(`invalid incoming request ${what}`);
|
|
899
|
+
};
|
|
900
|
+
if (request.setMethod({ tag: "other", val: parts.method }).tag === "err")
|
|
901
|
+
throw refuse("method");
|
|
902
|
+
if (
|
|
903
|
+
parts.scheme !== undefined &&
|
|
904
|
+
request.setScheme({ tag: "other", val: parts.scheme }).tag === "err"
|
|
905
|
+
)
|
|
906
|
+
throw refuse("scheme");
|
|
907
|
+
if (request.setAuthority(parts.authority).tag === "err") throw refuse("authority");
|
|
908
|
+
if (request.setPathWithQuery(parts.pathWithQuery).tag === "err")
|
|
909
|
+
throw refuse("path with query");
|
|
910
|
+
incoming.set(parts, body);
|
|
911
|
+
// The call's end closes an unfinished request body, unless a delivery still streams
|
|
912
|
+
// (it may be passing that body through); the delivery's own end closes it then.
|
|
913
|
+
const ended = host.signal();
|
|
914
|
+
const end = () => {
|
|
915
|
+
body.callEnded = true;
|
|
916
|
+
if (!body.delivering) body.terminate(CONNECTION_TERMINATED);
|
|
917
|
+
};
|
|
918
|
+
if (ended.aborted) end();
|
|
919
|
+
else ended.addEventListener("abort", end, { once: true });
|
|
920
|
+
return request;
|
|
921
|
+
},
|
|
922
|
+
respond(response: unknown, exchange: IngressExchange) {
|
|
923
|
+
if (!(response instanceof Response))
|
|
924
|
+
return Promise.reject(new TypeError("Foreign HTTP response"));
|
|
925
|
+
return deliver(response, exchange);
|
|
926
|
+
},
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
return {
|
|
930
|
+
types: {
|
|
931
|
+
Fields: HttpFields,
|
|
932
|
+
RequestOptions: HttpRequestOptions,
|
|
933
|
+
Request,
|
|
934
|
+
Response,
|
|
935
|
+
},
|
|
936
|
+
client: { send },
|
|
937
|
+
ingress,
|
|
938
|
+
};
|
|
939
|
+
}
|