@syntropika/tembra-sdk 0.2.2 → 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 -3332
- 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 -3310
- 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 -3321
- 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 +7 -6
- 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 +213 -90
- 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 -301
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One incoming HTTP exchange over a native typed carrier (Node NAPI, mobile UniFFI): the
|
|
3
|
+
* protocol of `PHASE5_NATIVE_CARRIER_CONTRACT.md`, shared by `NodePort` and `MobileDriver`.
|
|
4
|
+
* Platform adapters only translate their binding's names and byte types into `CarrierEvent`s
|
|
5
|
+
* and `CarrierTransport` calls; JSON appears only in host requests and the completion envelope.
|
|
6
|
+
*
|
|
7
|
+
* Lifetime:
|
|
8
|
+
* - The response head is published as soon as its `head` event arrives.
|
|
9
|
+
* - The call (and so the caller's root and revision gate) ends only after `complete`, after
|
|
10
|
+
* every admitted host operation settled, and after `finish()`.
|
|
11
|
+
* - Once `complete` was seen, or the exchange was abandoned, no pull, supply, disconnect or
|
|
12
|
+
* cancel is sent again: the same native port serves the revision's next exchange, so these
|
|
13
|
+
* would reach the wrong request. Only replies to host operations admitted before `complete`
|
|
14
|
+
* (drained before `finish`) and `finish` itself follow; both bindings cleared their reply
|
|
15
|
+
* maps at `complete` and never reuse ids, so such a late reply is refused and owns nothing.
|
|
16
|
+
*
|
|
17
|
+
* Request body: each `request-pull` awaits the application iterator's `next()` and answers
|
|
18
|
+
* once. Its `return()` is called once, without being awaited, when the exchange ends (complete,
|
|
19
|
+
* disconnect, cancellation, abandonment) before the body was read to its end. A `next()` still
|
|
20
|
+
* pending at that point is abandoned, never awaited, so an application iterator that never
|
|
21
|
+
* settles cannot hold the call.
|
|
22
|
+
*
|
|
23
|
+
* Refusal: a handler `error-code` arrives as `refused`, one WIT value in the standard binary
|
|
24
|
+
* codec, before `complete`; the exchange reports it as `HttpHandlerError` after settlement. The
|
|
25
|
+
* call itself still settles with its own completion (the untyped repeat, or a later trap,
|
|
26
|
+
* deadline or cancellation). Malformed bytes fail the call; completion text is never parsed.
|
|
27
|
+
*
|
|
28
|
+
* Response body: each `next()` sends exactly one pull and awaits its frame. The body ends at
|
|
29
|
+
* `end` (trailers resolve), at `error`, at the consumer's `return()` (a disconnect) or when the
|
|
30
|
+
* call completes without a terminal frame (cancellation, trap, timeout): the latter is a failure,
|
|
31
|
+
* never a truncated end.
|
|
32
|
+
*/
|
|
33
|
+
import { refusal, reply } from "./codec.ts";
|
|
34
|
+
import { failure as fault } from "../error.ts";
|
|
35
|
+
import { decodeAsyncHostRequest, decodeHostRequest } from "./host-protocol.ts";
|
|
36
|
+
import { decode, type HandleCodec, Reader } from "./standard-codec.ts";
|
|
37
|
+
import { METHODS, TYPES } from "./standard.ts";
|
|
38
|
+
import type { ErrorCode } from "wasi:http/types@0.3.0";
|
|
39
|
+
import {
|
|
40
|
+
CONNECTION_TERMINATED,
|
|
41
|
+
HttpHandlerError,
|
|
42
|
+
type HttpHandlerResponse,
|
|
43
|
+
type IncomingHttpRequest,
|
|
44
|
+
type IngressExchange,
|
|
45
|
+
} from "./http-ingress.ts";
|
|
46
|
+
import type { HttpField } from "./http-provider.ts";
|
|
47
|
+
import type { ExecutionScope, IngressDispatch } from "./types.ts";
|
|
48
|
+
|
|
49
|
+
/** Carrier events in the SDK's byte form. */
|
|
50
|
+
export type CarrierEvent =
|
|
51
|
+
| { kind: "host"; id: number; asynchronous: boolean; packet: string }
|
|
52
|
+
/** The completion envelope JSON: `{"ok":…}` or `{"error":{code,reason,message}}`. */
|
|
53
|
+
| { kind: "complete"; result: string }
|
|
54
|
+
| { kind: "head"; status: number; fields: readonly HttpField[] }
|
|
55
|
+
| { kind: "request-pull" }
|
|
56
|
+
| { kind: "data"; data: Uint8Array }
|
|
57
|
+
| { kind: "trailers"; fields: readonly HttpField[] }
|
|
58
|
+
| { kind: "end" }
|
|
59
|
+
| { kind: "error"; message: string }
|
|
60
|
+
/** The handler returned its `error-code` (standard binary codec bytes); never with a head. */
|
|
61
|
+
| { kind: "refused"; code: Uint8Array };
|
|
62
|
+
|
|
63
|
+
/** The answer to one `request-pull`: a chunk, the end with its trailers, or an error. */
|
|
64
|
+
export type RequestAnswer =
|
|
65
|
+
| { kind: "data"; data: Uint8Array }
|
|
66
|
+
| { kind: "end"; trailers: readonly HttpField[] }
|
|
67
|
+
| { kind: "error"; message: string };
|
|
68
|
+
|
|
69
|
+
/** The native exchange's control calls; each may throw, none is called after `complete`. */
|
|
70
|
+
export interface CarrierTransport {
|
|
71
|
+
/** Answer the pending request pull; `false` when the answer is no longer wanted. */
|
|
72
|
+
supply(answer: RequestAnswer): boolean;
|
|
73
|
+
/** Ask for one response frame. */
|
|
74
|
+
pull(): void;
|
|
75
|
+
/** The client went away. */
|
|
76
|
+
disconnect(): void;
|
|
77
|
+
/** The caller cancelled the call. */
|
|
78
|
+
cancel(): void;
|
|
79
|
+
reply(id: number, packet: string): boolean;
|
|
80
|
+
/** Release the native ticket after `complete`. */
|
|
81
|
+
finish(): void;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The control packet that starts the handler callback; the request travels typed. */
|
|
85
|
+
export function ingressPacket(dispatch: IngressDispatch): string {
|
|
86
|
+
return JSON.stringify({
|
|
87
|
+
kind: "ingress",
|
|
88
|
+
environment: dispatch.environment,
|
|
89
|
+
service: dispatch.service,
|
|
90
|
+
method: dispatch.method,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Encode one host reply without throwing through a native callback frame. */
|
|
95
|
+
export function respond(operation: () => unknown): string {
|
|
96
|
+
try {
|
|
97
|
+
return `{"ok":${reply(operation())}}`;
|
|
98
|
+
} catch (error) {
|
|
99
|
+
return refusal(error);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The `error-code` type: `wasi:http/client#send`'s error branch, which `handle` shares. */
|
|
104
|
+
const ERROR_CODE = (() => {
|
|
105
|
+
const send = METHODS.find(
|
|
106
|
+
(method) => method.interface === "wasi:http/client@0.3.0" && method.name === "send",
|
|
107
|
+
);
|
|
108
|
+
const result = send?.result === undefined ? undefined : TYPES[send.result];
|
|
109
|
+
if (result?.[0] !== "result") throw new Error("generated tables lack wasi:http/client#send");
|
|
110
|
+
return result[2] as number;
|
|
111
|
+
})();
|
|
112
|
+
const NO_HANDLES: HandleCodec = {
|
|
113
|
+
handle() {
|
|
114
|
+
throw new RangeError("an error code carries no handles");
|
|
115
|
+
},
|
|
116
|
+
value() {
|
|
117
|
+
throw new RangeError("an error code carries no handles");
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/** Decode a native `refused` event: exactly one WIT `error-code` in the standard binary codec. */
|
|
122
|
+
export function refusedCode(bytes: Uint8Array): ErrorCode {
|
|
123
|
+
if (!(bytes instanceof Uint8Array)) throw new TypeError("a refused code must be bytes");
|
|
124
|
+
const reader = new Reader(bytes);
|
|
125
|
+
const code = decode(reader, ERROR_CODE, NO_HANDLES) as ErrorCode;
|
|
126
|
+
reader.end();
|
|
127
|
+
return code;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A settable promise whose rejection is never reported as unhandled. */
|
|
131
|
+
function deferred<T>() {
|
|
132
|
+
let resolve!: (value: T) => void;
|
|
133
|
+
let reject!: (reason: unknown) => void;
|
|
134
|
+
const promise = new Promise<T>((done, fail) => {
|
|
135
|
+
resolve = done;
|
|
136
|
+
reject = fail;
|
|
137
|
+
});
|
|
138
|
+
promise.catch(() => {});
|
|
139
|
+
return { promise, resolve, reject };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Observe a value the application handed back, so a late rejection is never unhandled. */
|
|
143
|
+
function quiet(value: unknown): void {
|
|
144
|
+
if (typeof (value as PromiseLike<unknown> | undefined)?.then === "function")
|
|
145
|
+
Promise.resolve(value).catch(() => {});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Checked field pairs from the application; anything else is refused. */
|
|
149
|
+
function checkedFields(value: unknown): readonly HttpField[] {
|
|
150
|
+
if (value === undefined || value === null) return [];
|
|
151
|
+
if (!Array.isArray(value)) throw new TypeError("request trailers must be an array");
|
|
152
|
+
return value.map((field) => {
|
|
153
|
+
const [name, bytes] = Array.isArray(field) ? field : [];
|
|
154
|
+
if (typeof name !== "string" || !(bytes instanceof Uint8Array))
|
|
155
|
+
throw new TypeError("request trailers are [name, Uint8Array] pairs");
|
|
156
|
+
return [name, bytes] as const;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const ABANDONED = Symbol("abandoned");
|
|
161
|
+
type Frame = { kind: "data"; data: Uint8Array } | { kind: "trailers" } | { kind: "end" };
|
|
162
|
+
|
|
163
|
+
/** One exchange's protocol state; created per request, never reused. */
|
|
164
|
+
export class NativeIngress {
|
|
165
|
+
/** Settles after `complete`, the drain of admitted host work and `finish()`. */
|
|
166
|
+
readonly settled: Promise<void>;
|
|
167
|
+
#settle!: { resolve: () => void; reject: (error: unknown) => void };
|
|
168
|
+
/** `complete` was seen or the exchange was abandoned: the transport belongs to nobody. */
|
|
169
|
+
#done = false;
|
|
170
|
+
#failure: unknown;
|
|
171
|
+
readonly #pending = new Set<Promise<void>>();
|
|
172
|
+
#detach = () => {};
|
|
173
|
+
|
|
174
|
+
// Request side.
|
|
175
|
+
#iterator: AsyncIterator<Uint8Array> | undefined;
|
|
176
|
+
#requestEnded = false;
|
|
177
|
+
#requestClosed = false;
|
|
178
|
+
readonly #requestStop = deferred<typeof ABANDONED>();
|
|
179
|
+
#pulls = 0;
|
|
180
|
+
#pulling = false;
|
|
181
|
+
|
|
182
|
+
// Response side.
|
|
183
|
+
#headed = false;
|
|
184
|
+
#started = false;
|
|
185
|
+
#ended = false;
|
|
186
|
+
#bodyFailure: unknown;
|
|
187
|
+
#trailerFields: readonly HttpField[] | undefined;
|
|
188
|
+
readonly #trailers = deferred<readonly HttpField[] | undefined>();
|
|
189
|
+
#frame: ReturnType<typeof deferred<Frame>> | undefined;
|
|
190
|
+
#reading: Promise<unknown> = Promise.resolve();
|
|
191
|
+
|
|
192
|
+
constructor(
|
|
193
|
+
readonly transport: CarrierTransport,
|
|
194
|
+
readonly exchange: IngressExchange,
|
|
195
|
+
readonly scope: ExecutionScope,
|
|
196
|
+
) {
|
|
197
|
+
this.settled = new Promise((resolve, reject) => {
|
|
198
|
+
this.#settle = { resolve, reject };
|
|
199
|
+
});
|
|
200
|
+
// A rejected call is also reported through the exchange; the caller awaits `settled`.
|
|
201
|
+
this.settled.catch(() => {});
|
|
202
|
+
// This exchange owns the request from now on, body and trailers: every end below closes
|
|
203
|
+
// the body, and a trailers rejection is answered to the guest when its body reaches the
|
|
204
|
+
// end, never reported as unhandled meanwhile.
|
|
205
|
+
quiet(exchange.own().trailers);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The request as the application supplied it. */
|
|
209
|
+
get request(): IncomingHttpRequest {
|
|
210
|
+
return this.exchange.request;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The native exchange has begun: connect the caller's cancellation to it. */
|
|
214
|
+
begun(): void {
|
|
215
|
+
const signal = this.scope.signal;
|
|
216
|
+
if (!signal) return;
|
|
217
|
+
const cancel = () => this.#cancel();
|
|
218
|
+
this.#detach = () => signal.removeEventListener("abort", cancel);
|
|
219
|
+
if (signal.aborted) cancel();
|
|
220
|
+
else signal.addEventListener("abort", cancel, { once: true });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Handle one carrier event; never throws, so a native callback frame is never unwound. */
|
|
224
|
+
event(event: CarrierEvent): void {
|
|
225
|
+
if (this.#done) return;
|
|
226
|
+
try {
|
|
227
|
+
switch (event.kind) {
|
|
228
|
+
case "host":
|
|
229
|
+
return this.#host(event);
|
|
230
|
+
case "request-pull":
|
|
231
|
+
this.#pulls++;
|
|
232
|
+
return void this.#serveRequest();
|
|
233
|
+
case "head":
|
|
234
|
+
return this.#head(event.status, event.fields);
|
|
235
|
+
case "data":
|
|
236
|
+
return this.#deliver({ kind: "data", data: event.data });
|
|
237
|
+
case "trailers":
|
|
238
|
+
this.#trailerFields = event.fields;
|
|
239
|
+
return this.#deliver({ kind: "trailers" });
|
|
240
|
+
case "end":
|
|
241
|
+
this.#ended = true;
|
|
242
|
+
this.#trailers.resolve(this.#trailerFields?.length ? this.#trailerFields : undefined);
|
|
243
|
+
return this.#deliver({ kind: "end" });
|
|
244
|
+
case "error": {
|
|
245
|
+
const failure = new HttpHandlerError(
|
|
246
|
+
{ tag: "internal-error", val: event.message },
|
|
247
|
+
event.message,
|
|
248
|
+
);
|
|
249
|
+
this.#endDelivery(failure);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
case "refused":
|
|
253
|
+
// Recorded now, reported by the exchange only after the call settled. Malformed
|
|
254
|
+
// bytes are a transport failure; nothing is guessed from completion text.
|
|
255
|
+
if (this.#headed) throw new Error("a refused exchange cannot have a head");
|
|
256
|
+
return this.exchange.refuse(refusedCode(event.code));
|
|
257
|
+
case "complete":
|
|
258
|
+
// Backstop: an unexpected failure fails this call instead of escaping unobserved.
|
|
259
|
+
return void this.#complete(event.result).catch((error) => this.#settle.reject(error));
|
|
260
|
+
default:
|
|
261
|
+
throw new Error("Unknown incoming HTTP carrier event");
|
|
262
|
+
}
|
|
263
|
+
} catch (error) {
|
|
264
|
+
this.#broken(error);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The transport failed (its event stream broke): end both bodies, revoke and drain host work,
|
|
270
|
+
* and reject. The platform adapter then quarantines its native exchange; `finish` is not called.
|
|
271
|
+
*/
|
|
272
|
+
async abandon(error: unknown): Promise<void> {
|
|
273
|
+
if (this.#done) return;
|
|
274
|
+
this.#done = true;
|
|
275
|
+
this.#detach();
|
|
276
|
+
this.#endDelivery(error);
|
|
277
|
+
this.#closeRequest();
|
|
278
|
+
this.scope.cancel();
|
|
279
|
+
await Promise.allSettled([...this.#pending]);
|
|
280
|
+
this.#settle.reject(error);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* A failure inside this adapter or its platform mapping: keep it for the completion, and free
|
|
285
|
+
* the guest from anything it waits on (disconnect, then cancel). The exchange still finishes.
|
|
286
|
+
*/
|
|
287
|
+
fail(error: unknown): void {
|
|
288
|
+
this.#broken(error);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
#broken(error: unknown): void {
|
|
292
|
+
this.#failure ??= error;
|
|
293
|
+
// A frame may have been lost: the body can only fail now, never end as if complete.
|
|
294
|
+
this.#endDelivery(error);
|
|
295
|
+
this.#closeRequest();
|
|
296
|
+
if (this.#done) return;
|
|
297
|
+
for (const operation of [() => this.transport.disconnect(), () => this.transport.cancel()])
|
|
298
|
+
try {
|
|
299
|
+
operation();
|
|
300
|
+
} catch {
|
|
301
|
+
// The completion still arrives; the recorded failure is reported then.
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
#cancel(): void {
|
|
306
|
+
if (this.#done) return;
|
|
307
|
+
try {
|
|
308
|
+
this.transport.cancel();
|
|
309
|
+
} catch (error) {
|
|
310
|
+
this.#failure ??= error;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
#host(event: Extract<CarrierEvent, { kind: "host" }>): void {
|
|
315
|
+
const { id, packet } = event;
|
|
316
|
+
if (!event.asynchronous) {
|
|
317
|
+
this.transport.reply(
|
|
318
|
+
id,
|
|
319
|
+
respond(() => this.scope.sync(decodeHostRequest(packet))),
|
|
320
|
+
);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
let request!: ReturnType<typeof decodeAsyncHostRequest>;
|
|
324
|
+
const operation = Promise.resolve()
|
|
325
|
+
.then(() => {
|
|
326
|
+
request = decodeAsyncHostRequest(packet);
|
|
327
|
+
return this.scope.async(request);
|
|
328
|
+
})
|
|
329
|
+
.then(
|
|
330
|
+
(value) =>
|
|
331
|
+
this.scope.deliver(request, value, (value) =>
|
|
332
|
+
this.transport.reply(
|
|
333
|
+
id,
|
|
334
|
+
respond(() => value),
|
|
335
|
+
),
|
|
336
|
+
),
|
|
337
|
+
(error) =>
|
|
338
|
+
void this.transport.reply(
|
|
339
|
+
id,
|
|
340
|
+
respond(() => {
|
|
341
|
+
throw error;
|
|
342
|
+
}),
|
|
343
|
+
),
|
|
344
|
+
)
|
|
345
|
+
.catch((error) => {
|
|
346
|
+
this.#failure ??= error;
|
|
347
|
+
});
|
|
348
|
+
this.#pending.add(operation);
|
|
349
|
+
void operation.finally(() => this.#pending.delete(operation));
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Answer request pulls one at a time, in order. */
|
|
353
|
+
async #serveRequest(): Promise<void> {
|
|
354
|
+
if (this.#pulling) return;
|
|
355
|
+
this.#pulling = true;
|
|
356
|
+
try {
|
|
357
|
+
while (this.#pulls > 0 && !this.#done) {
|
|
358
|
+
this.#pulls--;
|
|
359
|
+
const answer = await this.#nextRequest();
|
|
360
|
+
if (answer === ABANDONED || this.#done) return;
|
|
361
|
+
try {
|
|
362
|
+
this.transport.supply(answer);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
this.#broken(error);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
} finally {
|
|
369
|
+
this.#pulling = false;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** The next answer from the application's body, or `ABANDONED` once the exchange ended. */
|
|
374
|
+
async #nextRequest(): Promise<RequestAnswer | typeof ABANDONED> {
|
|
375
|
+
const stop = this.#requestStop.promise;
|
|
376
|
+
try {
|
|
377
|
+
if (this.#requestClosed) return ABANDONED;
|
|
378
|
+
const { body, trailers } = this.request;
|
|
379
|
+
if (body && !this.#requestEnded) {
|
|
380
|
+
this.#iterator ??= body[Symbol.asyncIterator]();
|
|
381
|
+
for (;;) {
|
|
382
|
+
const pending = this.#iterator.next();
|
|
383
|
+
quiet(pending);
|
|
384
|
+
const next = await Promise.race([pending, stop]);
|
|
385
|
+
if (next === ABANDONED) return ABANDONED;
|
|
386
|
+
if (next.done) break;
|
|
387
|
+
if (!(next.value instanceof Uint8Array))
|
|
388
|
+
throw new TypeError("incoming request chunks must be Uint8Array");
|
|
389
|
+
if (next.value.byteLength) return { kind: "data", data: next.value };
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
this.#requestEnded = true;
|
|
393
|
+
this.#iterator = undefined;
|
|
394
|
+
if (!trailers) return { kind: "end", trailers: [] };
|
|
395
|
+
const pairs = await Promise.race([Promise.resolve(trailers), stop]);
|
|
396
|
+
if (pairs === ABANDONED) return ABANDONED;
|
|
397
|
+
return { kind: "end", trailers: checkedFields(pairs) };
|
|
398
|
+
} catch (error) {
|
|
399
|
+
// A failed read ends the guest's body with `internal-error`; the iterator is done.
|
|
400
|
+
this.#requestEnded = true;
|
|
401
|
+
this.#iterator = undefined;
|
|
402
|
+
return { kind: "error", message: error instanceof Error ? error.message : String(error) };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Stop the application's body once; its `return()` is never awaited. Every application call
|
|
408
|
+
* here (the iterator factory of a never-read body, the `return` lookup and call) is guarded:
|
|
409
|
+
* this runs on the completion, disconnect and abandonment paths, which must always finish.
|
|
410
|
+
*/
|
|
411
|
+
#closeRequest(): void {
|
|
412
|
+
if (this.#requestClosed) return;
|
|
413
|
+
this.#requestClosed = true;
|
|
414
|
+
this.#requestStop.resolve(ABANDONED);
|
|
415
|
+
if (this.#requestEnded) return;
|
|
416
|
+
const iterator = this.#iterator;
|
|
417
|
+
this.#iterator = undefined;
|
|
418
|
+
try {
|
|
419
|
+
quiet((iterator ?? this.request.body?.[Symbol.asyncIterator]())?.return?.());
|
|
420
|
+
} catch {
|
|
421
|
+
// A body that cannot be opened or closed (a locked stream) cannot affect the exchange.
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Publish the response head; its body is pulled only as the consumer reads. */
|
|
426
|
+
#head(status: number, fields: readonly HttpField[]): void {
|
|
427
|
+
if (this.#headed) throw new Error("the response head was already published");
|
|
428
|
+
this.#headed = true;
|
|
429
|
+
const body = Object.freeze({
|
|
430
|
+
[Symbol.asyncIterator]: () => this.#responseIterator(),
|
|
431
|
+
});
|
|
432
|
+
const response: HttpHandlerResponse = Object.freeze({
|
|
433
|
+
status,
|
|
434
|
+
fields: Object.freeze(fields.map((field) => Object.freeze(field) as HttpField)),
|
|
435
|
+
body,
|
|
436
|
+
trailers: this.#trailers.promise,
|
|
437
|
+
});
|
|
438
|
+
this.exchange.respond(response);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
#responseIterator(): AsyncIterator<Uint8Array> {
|
|
442
|
+
if (this.#started) throw new TypeError("the response body is read once");
|
|
443
|
+
this.#started = true;
|
|
444
|
+
return {
|
|
445
|
+
next: () => {
|
|
446
|
+
// Reads are sequential: one pull, one frame.
|
|
447
|
+
const read = this.#reading.then(() => this.#next());
|
|
448
|
+
this.#reading = read.catch(() => {});
|
|
449
|
+
return read;
|
|
450
|
+
},
|
|
451
|
+
return: async () => {
|
|
452
|
+
this.#disconnect();
|
|
453
|
+
return { done: true, value: undefined };
|
|
454
|
+
},
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async #next(): Promise<IteratorResult<Uint8Array>> {
|
|
459
|
+
for (;;) {
|
|
460
|
+
if (this.#ended) {
|
|
461
|
+
if (this.#bodyFailure !== undefined) throw this.#bodyFailure;
|
|
462
|
+
return { done: true, value: undefined };
|
|
463
|
+
}
|
|
464
|
+
const frame = deferred<Frame>();
|
|
465
|
+
this.#frame = frame;
|
|
466
|
+
try {
|
|
467
|
+
this.transport.pull();
|
|
468
|
+
} catch (error) {
|
|
469
|
+
// The carrier already ended (a host-driven end whose completion is on its way): the
|
|
470
|
+
// body fails; the call reports its own completion.
|
|
471
|
+
this.#frame = undefined;
|
|
472
|
+
this.#endDelivery(error);
|
|
473
|
+
try {
|
|
474
|
+
this.transport.disconnect();
|
|
475
|
+
} catch {
|
|
476
|
+
// Nothing is left to disconnect.
|
|
477
|
+
}
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
const next = await frame.promise;
|
|
481
|
+
if (next.kind === "data") return { done: false, value: next.data };
|
|
482
|
+
if (next.kind === "end") return { done: true, value: undefined };
|
|
483
|
+
// Trailers: the end follows on the next pull.
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Hand a frame to the read waiting for it; a frame nobody waits for is late and ignored. */
|
|
488
|
+
#deliver(frame: Frame): void {
|
|
489
|
+
const waiting = this.#frame;
|
|
490
|
+
this.#frame = undefined;
|
|
491
|
+
waiting?.resolve(frame);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** End the delivery early: pending and later reads and the trailers fail with `failure`. */
|
|
495
|
+
#endDelivery(failure: unknown): void {
|
|
496
|
+
if (this.#ended) return;
|
|
497
|
+
this.#ended = true;
|
|
498
|
+
this.#bodyFailure = failure;
|
|
499
|
+
this.#trailers.reject(failure);
|
|
500
|
+
const waiting = this.#frame;
|
|
501
|
+
this.#frame = undefined;
|
|
502
|
+
waiting?.reject(failure);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** The consumer stopped reading: the client disconnected. */
|
|
506
|
+
#disconnect(): void {
|
|
507
|
+
if (this.#ended) return;
|
|
508
|
+
this.#endDelivery(new HttpHandlerError(CONNECTION_TERMINATED));
|
|
509
|
+
this.#closeRequest();
|
|
510
|
+
if (this.#done) return;
|
|
511
|
+
try {
|
|
512
|
+
this.transport.disconnect();
|
|
513
|
+
} catch (error) {
|
|
514
|
+
this.#broken(error);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** Physical completion: end what is still open, revoke and drain host work, then finish. */
|
|
519
|
+
async #complete(result: string): Promise<void> {
|
|
520
|
+
this.#done = true;
|
|
521
|
+
this.#detach();
|
|
522
|
+
let envelope: { ok?: unknown; error?: unknown };
|
|
523
|
+
let error: unknown;
|
|
524
|
+
try {
|
|
525
|
+
envelope = JSON.parse(result);
|
|
526
|
+
if (Object.hasOwn(envelope, "ok")) {
|
|
527
|
+
if (typeof envelope.ok !== "string") throw new Error("Invalid guest result packet");
|
|
528
|
+
} else error = envelope.error ?? "Interpreter operation failed";
|
|
529
|
+
} catch (invalid) {
|
|
530
|
+
error = invalid;
|
|
531
|
+
}
|
|
532
|
+
// A refusal's completion repeats it untyped; the typed `refused` event already reached the
|
|
533
|
+
// exchange, whose head reports it. The call itself reports its own completion, so a trap,
|
|
534
|
+
// deadline or cancellation stays the call's failure.
|
|
535
|
+
const outcome = error !== undefined ? fault(error) : undefined;
|
|
536
|
+
// A host-driven end (cancellation, trap, timeout) completes without a terminal frame.
|
|
537
|
+
this.#endDelivery(outcome ?? new Error("the HTTP handler callback ended"));
|
|
538
|
+
this.#closeRequest();
|
|
539
|
+
this.scope.cancel();
|
|
540
|
+
await Promise.allSettled([...this.#pending]);
|
|
541
|
+
try {
|
|
542
|
+
this.transport.finish();
|
|
543
|
+
} catch (finishing) {
|
|
544
|
+
this.#failure ??= finishing;
|
|
545
|
+
}
|
|
546
|
+
if (this.#failure !== undefined) return this.#settle.reject(this.#failure);
|
|
547
|
+
if (outcome !== undefined) return this.#settle.reject(outcome);
|
|
548
|
+
this.#settle.resolve();
|
|
549
|
+
}
|
|
550
|
+
}
|