@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,958 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard `wasi:sockets` (TCP, UDP) and `wasi:sockets/ip-name-lookup` for the browser
|
|
3
|
+
* standard host, over an injected `SocketProvider` (`socket-provider.ts`). Browsers have no
|
|
4
|
+
* ambient sockets.
|
|
5
|
+
*
|
|
6
|
+
* Every call follows one order, so a refusal never reaches the provider:
|
|
7
|
+
* 1. argument and state checks, as pinned upstream `wasmtime-wasi` 51.0.0-rc.1;
|
|
8
|
+
* 2. the exact grant of the provider bound to that WIT import (`access-denied`);
|
|
9
|
+
* 3. provider capability (`not-supported`; name lookup `permanent-resolver-failure`);
|
|
10
|
+
* 4. the provider call.
|
|
11
|
+
*
|
|
12
|
+
* Ownership follows WASI's shared model: a socket handle and each stream derived from it hold
|
|
13
|
+
* one reference to the provider backend. Dropping the handle leaves its streams working; a
|
|
14
|
+
* dropped receive stream shuts down reads; the last reference closes the backend. Accepted
|
|
15
|
+
* sockets are independent. Every closing promise is physical work tracked by the host.
|
|
16
|
+
*/
|
|
17
|
+
import type {
|
|
18
|
+
ErrorCode,
|
|
19
|
+
IpAddress,
|
|
20
|
+
IpAddressFamily,
|
|
21
|
+
IpSocketAddress,
|
|
22
|
+
} from "wasi:sockets/types@0.3.0";
|
|
23
|
+
import type { ErrorCode as LookupErrorCode } from "wasi:sockets/ip-name-lookup@0.3.0";
|
|
24
|
+
import type { SocketAccess } from "../browser-network.ts";
|
|
25
|
+
import {
|
|
26
|
+
type Address,
|
|
27
|
+
checkedIpAddress,
|
|
28
|
+
fromWit,
|
|
29
|
+
hasFamily,
|
|
30
|
+
isRemote,
|
|
31
|
+
isUnicast,
|
|
32
|
+
key,
|
|
33
|
+
parseHostName,
|
|
34
|
+
toWit,
|
|
35
|
+
unspecified,
|
|
36
|
+
} from "../socket-addresses.ts";
|
|
37
|
+
import {
|
|
38
|
+
NameLookupError,
|
|
39
|
+
type SocketOptions,
|
|
40
|
+
SocketProviderError,
|
|
41
|
+
type TcpBackend,
|
|
42
|
+
type TcpConnection,
|
|
43
|
+
type TcpListener,
|
|
44
|
+
type TcpOptions,
|
|
45
|
+
type UdpBackend,
|
|
46
|
+
type UdpOptions,
|
|
47
|
+
} from "../socket-provider.ts";
|
|
48
|
+
import {
|
|
49
|
+
abortable,
|
|
50
|
+
closing,
|
|
51
|
+
guestBytes,
|
|
52
|
+
hostBytes,
|
|
53
|
+
hostItems,
|
|
54
|
+
type WasiHost,
|
|
55
|
+
type WasiInterfaces,
|
|
56
|
+
} from "./wasi-host.ts";
|
|
57
|
+
|
|
58
|
+
/** The host and cancellation of the callback serving one socket operation. */
|
|
59
|
+
interface StandardCall {
|
|
60
|
+
readonly host: WasiHost;
|
|
61
|
+
readonly signal: AbortSignal | undefined;
|
|
62
|
+
}
|
|
63
|
+
const callOf = (host: WasiHost): StandardCall => ({
|
|
64
|
+
host,
|
|
65
|
+
signal: host.signal(),
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/** Upstream `MAX_DATAGRAM_SIZE`. */
|
|
69
|
+
const MAX_DATAGRAM = 0xffff;
|
|
70
|
+
/** Upstream listen backlog default and clamp. */
|
|
71
|
+
const DEFAULT_BACKLOG = 128;
|
|
72
|
+
const MAX_BACKLOG = 0x7fffffff;
|
|
73
|
+
|
|
74
|
+
type Result<T, E> = { tag: "ok"; val: T } | { tag: "err"; val: E };
|
|
75
|
+
const ok = <T>(val: T): { tag: "ok"; val: T } => ({ tag: "ok", val });
|
|
76
|
+
const fail = (tag: ErrorCode["tag"]): { tag: "err"; val: ErrorCode } => ({
|
|
77
|
+
tag: "err",
|
|
78
|
+
val: { tag } as ErrorCode,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
/** The providers bound to this revision's socket and lookup imports. */
|
|
82
|
+
export interface SocketBindings {
|
|
83
|
+
readonly types?: SocketAccess | undefined;
|
|
84
|
+
readonly lookup?: SocketAccess | undefined;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---------------------------------------------------------------------------------------------
|
|
88
|
+
// errors
|
|
89
|
+
|
|
90
|
+
/** `wasi:sockets/types#error-code` and `ip-name-lookup#error-code` cases. */
|
|
91
|
+
const SOCKET_CODES = new Set([
|
|
92
|
+
"access-denied",
|
|
93
|
+
"not-supported",
|
|
94
|
+
"invalid-argument",
|
|
95
|
+
"out-of-memory",
|
|
96
|
+
"timeout",
|
|
97
|
+
"invalid-state",
|
|
98
|
+
"address-not-bindable",
|
|
99
|
+
"address-in-use",
|
|
100
|
+
"remote-unreachable",
|
|
101
|
+
"connection-refused",
|
|
102
|
+
"connection-broken",
|
|
103
|
+
"connection-reset",
|
|
104
|
+
"connection-aborted",
|
|
105
|
+
"datagram-too-large",
|
|
106
|
+
"other",
|
|
107
|
+
]);
|
|
108
|
+
const LOOKUP_CODES = new Set([
|
|
109
|
+
"access-denied",
|
|
110
|
+
"invalid-argument",
|
|
111
|
+
"name-unresolvable",
|
|
112
|
+
"temporary-resolver-failure",
|
|
113
|
+
"permanent-resolver-failure",
|
|
114
|
+
"other",
|
|
115
|
+
]);
|
|
116
|
+
|
|
117
|
+
/** A provider code only when it is a standard case; otherwise `other(message)`. */
|
|
118
|
+
function code<C extends { tag: string }>(error: unknown, cases: Set<string>, typed: unknown): C {
|
|
119
|
+
const tag = (typed as { tag?: unknown } | undefined)?.tag;
|
|
120
|
+
if (
|
|
121
|
+
typeof tag === "string" &&
|
|
122
|
+
cases.has(tag) &&
|
|
123
|
+
(tag !== "other" ||
|
|
124
|
+
typeof (typed as { val?: unknown }).val === "string" ||
|
|
125
|
+
(typed as { val?: unknown }).val === undefined)
|
|
126
|
+
)
|
|
127
|
+
return typed as C;
|
|
128
|
+
return {
|
|
129
|
+
tag: "other",
|
|
130
|
+
val: error instanceof Error ? error.message : String(error),
|
|
131
|
+
} as unknown as C;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const socketCode = (error: unknown): ErrorCode =>
|
|
135
|
+
code(error, SOCKET_CODES, error instanceof SocketProviderError ? error.code : undefined);
|
|
136
|
+
const lookupCode = (error: unknown): LookupErrorCode =>
|
|
137
|
+
code(error, LOOKUP_CODES, error instanceof NameLookupError ? error.code : undefined);
|
|
138
|
+
|
|
139
|
+
/** Cancellation is an ordinary WASI error, never a rejection that traps generated bindings. */
|
|
140
|
+
const callCancelled = (): { tag: "err"; val: { tag: "other"; val: string } } => ({
|
|
141
|
+
tag: "err",
|
|
142
|
+
val: { tag: "other", val: "call cancelled" },
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
/** Run a synchronous provider call, reporting its failure as a standard result. */
|
|
146
|
+
function attempt<T>(operation: () => T): Result<T, ErrorCode> {
|
|
147
|
+
try {
|
|
148
|
+
return ok(operation());
|
|
149
|
+
} catch (error) {
|
|
150
|
+
return { tag: "err", val: socketCode(error) };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A provider-returned address as a standard result; malformed is the provider's failure. */
|
|
155
|
+
function localAddress(value: IpSocketAddress | undefined): Result<IpSocketAddress, ErrorCode> {
|
|
156
|
+
if (value === undefined) return fail("invalid-state");
|
|
157
|
+
const address = fromWit(value);
|
|
158
|
+
return address
|
|
159
|
+
? ok(toWit(address))
|
|
160
|
+
: { tag: "err", val: { tag: "other", val: "invalid provider address" } };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** A provider-returned address, validated; a malformed one is the provider's failure. */
|
|
164
|
+
function provided(value: unknown): Address {
|
|
165
|
+
const address = fromWit(value);
|
|
166
|
+
if (!address) throw new Error("invalid provider address");
|
|
167
|
+
return address;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---------------------------------------------------------------------------------------------
|
|
171
|
+
// shared physical ownership
|
|
172
|
+
|
|
173
|
+
/** Backends of each revision not yet closed, closed at its retirement. */
|
|
174
|
+
const LIVE = new WeakMap<AbortSignal, Set<Shared<{ close(): Promise<void> }>>>();
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* One provider backend shared by a socket handle and its streams; the last user closes it. A
|
|
178
|
+
* backend the guest still holds when the revision retires (quarantine or disposal) is closed
|
|
179
|
+
* then. Closing always waits for the backend's pending operations (a connect) to settle first,
|
|
180
|
+
* so a late result is handled before the backend goes away.
|
|
181
|
+
*/
|
|
182
|
+
class Shared<B extends { close(): Promise<void> }> {
|
|
183
|
+
#users = 1;
|
|
184
|
+
#closed = false;
|
|
185
|
+
readonly #busy = new Set<Promise<unknown>>();
|
|
186
|
+
|
|
187
|
+
constructor(
|
|
188
|
+
readonly host: WasiHost,
|
|
189
|
+
readonly backend: B,
|
|
190
|
+
) {
|
|
191
|
+
let live = LIVE.get(host.retired);
|
|
192
|
+
if (!live) {
|
|
193
|
+
const revision = new Set<Shared<{ close(): Promise<void> }>>();
|
|
194
|
+
live = revision;
|
|
195
|
+
LIVE.set(host.retired, live);
|
|
196
|
+
host.retired.addEventListener(
|
|
197
|
+
"abort",
|
|
198
|
+
() => {
|
|
199
|
+
for (const shared of [...revision]) shared.#close();
|
|
200
|
+
},
|
|
201
|
+
{ once: true },
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
if (host.retired.aborted) this.#close();
|
|
205
|
+
else live.add(this);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Keep the backend open until `operation` settled. */
|
|
209
|
+
busy(operation: Promise<unknown>): void {
|
|
210
|
+
this.#busy.add(operation);
|
|
211
|
+
const forget = () => this.#busy.delete(operation);
|
|
212
|
+
operation.then(forget, forget);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
retain(): void {
|
|
216
|
+
this.#users++;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
release(): void {
|
|
220
|
+
if (--this.#users === 0) this.#close();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
#close(): void {
|
|
224
|
+
if (this.#closed) return;
|
|
225
|
+
this.#closed = true;
|
|
226
|
+
LIVE.get(this.host.retired)?.delete(this);
|
|
227
|
+
closing(this.host, async () => {
|
|
228
|
+
while (this.#busy.size) await Promise.allSettled([...this.#busy]);
|
|
229
|
+
await this.backend.close();
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Handle-table reference counting, as for every standard resource. */
|
|
235
|
+
abstract class SocketResource {
|
|
236
|
+
#users = 1;
|
|
237
|
+
|
|
238
|
+
retain(): void {
|
|
239
|
+
this.#users++;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
release(): void {
|
|
243
|
+
if (--this.#users === 0) this.close();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
protected abstract close(): void;
|
|
247
|
+
|
|
248
|
+
/** The guest dropped its handle. */
|
|
249
|
+
[Symbol.dispose](): void {
|
|
250
|
+
this.release();
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Independent option access: an absent getter or setter is `not-supported`, not invented. */
|
|
255
|
+
function getOption<O, K extends keyof O>(
|
|
256
|
+
backend: SocketOptions<O>,
|
|
257
|
+
name: K,
|
|
258
|
+
valid: (value: unknown) => boolean,
|
|
259
|
+
): Result<O[K], ErrorCode> {
|
|
260
|
+
if (!backend.getOption) return fail("not-supported");
|
|
261
|
+
const value = attempt(() => backend.getOption!(name));
|
|
262
|
+
if (value.tag === "ok" && !valid(value.val))
|
|
263
|
+
return {
|
|
264
|
+
tag: "err",
|
|
265
|
+
val: { tag: "other", val: `invalid provider ${String(name)}` },
|
|
266
|
+
};
|
|
267
|
+
return value;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function setOption<O, K extends keyof O>(
|
|
271
|
+
backend: SocketOptions<O>,
|
|
272
|
+
name: K,
|
|
273
|
+
value: O[K],
|
|
274
|
+
): Result<void, ErrorCode> {
|
|
275
|
+
if (!backend.setOption) return fail("not-supported");
|
|
276
|
+
return attempt(() => backend.setOption!(name, value));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const isU8 = (v: unknown) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 0xff;
|
|
280
|
+
const isU32 = (v: unknown) =>
|
|
281
|
+
typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 0xffffffff;
|
|
282
|
+
const isU64 = (v: unknown) => typeof v === "bigint" && v > 0n && v < 1n << 64n;
|
|
283
|
+
const isBool = (v: unknown) => typeof v === "boolean";
|
|
284
|
+
|
|
285
|
+
// ---------------------------------------------------------------------------------------------
|
|
286
|
+
// TCP
|
|
287
|
+
|
|
288
|
+
type TcpState =
|
|
289
|
+
| { kind: "default" }
|
|
290
|
+
| { kind: "connecting" }
|
|
291
|
+
| { kind: "connected"; connection: TcpConnection }
|
|
292
|
+
| { kind: "listening"; listener: TcpListener }
|
|
293
|
+
| { kind: "closed"; code: ErrorCode };
|
|
294
|
+
|
|
295
|
+
/** Close a connection nobody will receive; each promise is its physical acknowledgement. */
|
|
296
|
+
function discardConnection(host: WasiHost, connection: TcpConnection): Promise<unknown> {
|
|
297
|
+
const discarded = Promise.allSettled([
|
|
298
|
+
Promise.resolve().then(() => connection.readable.cancel()),
|
|
299
|
+
Promise.resolve().then(() => connection.writable.abort()),
|
|
300
|
+
]);
|
|
301
|
+
closing(host, () => discarded);
|
|
302
|
+
return discarded;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Validate a provider connection; the host never trusts its shape. */
|
|
306
|
+
function checkedConnection(value: unknown): TcpConnection {
|
|
307
|
+
const connection = value as TcpConnection;
|
|
308
|
+
if (
|
|
309
|
+
!(connection?.readable instanceof ReadableStream) ||
|
|
310
|
+
!(connection.writable instanceof WritableStream)
|
|
311
|
+
)
|
|
312
|
+
throw new Error("invalid provider connection");
|
|
313
|
+
provided(connection.remote);
|
|
314
|
+
return connection;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** `wasi:sockets/types#tcp-socket`. */
|
|
318
|
+
export class TcpSocket extends SocketResource {
|
|
319
|
+
#state: TcpState;
|
|
320
|
+
#bound: boolean;
|
|
321
|
+
#backlog = DEFAULT_BACKLOG;
|
|
322
|
+
#sent = false;
|
|
323
|
+
#received = false;
|
|
324
|
+
|
|
325
|
+
constructor(
|
|
326
|
+
readonly access: SocketAccess,
|
|
327
|
+
readonly family: IpAddressFamily,
|
|
328
|
+
readonly shared: Shared<TcpBackend>,
|
|
329
|
+
connection?: TcpConnection,
|
|
330
|
+
) {
|
|
331
|
+
super();
|
|
332
|
+
this.#state = connection ? { kind: "connected", connection } : { kind: "default" };
|
|
333
|
+
this.#bound = connection !== undefined;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
protected close(): void {
|
|
337
|
+
this.shared.release();
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
get #backend(): TcpBackend {
|
|
341
|
+
return this.shared.backend;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
get #grants() {
|
|
345
|
+
return this.access.grants;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
bind(local: IpSocketAddress): Result<void, ErrorCode> {
|
|
349
|
+
if (this.#bound || this.#state.kind !== "default") return fail("invalid-state");
|
|
350
|
+
const address = fromWit(local)!;
|
|
351
|
+
if (!isUnicast(address) || !hasFamily(address, this.family)) return fail("invalid-argument");
|
|
352
|
+
if (!this.#grants.allows(address, "tcp-bind")) return fail("access-denied");
|
|
353
|
+
const backend = this.#backend;
|
|
354
|
+
if (!backend.bind) return fail("not-supported");
|
|
355
|
+
const bound = attempt(() => backend.bind!(toWit(address)));
|
|
356
|
+
if (bound.tag === "ok") this.#bound = true;
|
|
357
|
+
return bound;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async connect(
|
|
361
|
+
remote: IpSocketAddress,
|
|
362
|
+
call: StandardCall = callOf(this.shared.host),
|
|
363
|
+
): Promise<Result<void, ErrorCode>> {
|
|
364
|
+
if (this.#state.kind !== "default") return fail("invalid-state");
|
|
365
|
+
const address = fromWit(remote)!;
|
|
366
|
+
if (!isUnicast(address) || !isRemote(address) || !hasFamily(address, this.family))
|
|
367
|
+
return fail("invalid-argument");
|
|
368
|
+
if (!this.#bound && !this.#grants.allows(unspecified(this.family), "tcp-bind"))
|
|
369
|
+
return fail("access-denied");
|
|
370
|
+
if (!this.#grants.allows(address, "tcp-connect")) return fail("access-denied");
|
|
371
|
+
this.#state = { kind: "connecting" };
|
|
372
|
+
const abort = new AbortController();
|
|
373
|
+
const stop = () => abort.abort();
|
|
374
|
+
call.signal?.addEventListener("abort", stop, { once: true });
|
|
375
|
+
// The provider's own promise: a connection it delivers after cancellation is discarded.
|
|
376
|
+
const raw = Promise.resolve().then(() => this.#backend.connect(toWit(address), abort.signal));
|
|
377
|
+
this.shared.busy(raw);
|
|
378
|
+
const pending = call.host.physical(() => raw);
|
|
379
|
+
try {
|
|
380
|
+
const connection = checkedConnection(await abortable(pending, call.signal));
|
|
381
|
+
this.#state = { kind: "connected", connection };
|
|
382
|
+
this.#bound = true;
|
|
383
|
+
return ok(undefined);
|
|
384
|
+
} catch (error) {
|
|
385
|
+
this.#state = { kind: "closed", code: { tag: "invalid-state" } };
|
|
386
|
+
if (!call.signal?.aborted) {
|
|
387
|
+
const failure = socketCode(error);
|
|
388
|
+
this.#state = { kind: "closed", code: failure };
|
|
389
|
+
return { tag: "err", val: failure };
|
|
390
|
+
}
|
|
391
|
+
// A connection that arrives after cancellation is closed and never published.
|
|
392
|
+
// The backend closes only after this discard (its pending work).
|
|
393
|
+
this.shared.busy(
|
|
394
|
+
raw.then(
|
|
395
|
+
(late) => discardConnection(call.host, late),
|
|
396
|
+
() => {},
|
|
397
|
+
),
|
|
398
|
+
);
|
|
399
|
+
return callCancelled();
|
|
400
|
+
} finally {
|
|
401
|
+
call.signal?.removeEventListener("abort", stop);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
listen(
|
|
406
|
+
call: StandardCall = callOf(this.shared.host),
|
|
407
|
+
): Result<AsyncIterableIterator<unknown>, ErrorCode> {
|
|
408
|
+
if (this.#state.kind !== "default") return fail("invalid-state");
|
|
409
|
+
const implicit = unspecified(this.family);
|
|
410
|
+
if (this.#bound) {
|
|
411
|
+
const local = localAddress(this.#backend.local);
|
|
412
|
+
if (local.tag === "err") return local;
|
|
413
|
+
if (!this.#grants.allows(fromWit(local.val)!, "tcp-listen")) return fail("access-denied");
|
|
414
|
+
} else if (
|
|
415
|
+
!this.#grants.allows(implicit, "tcp-bind") ||
|
|
416
|
+
!this.#grants.allows(implicit, "tcp-listen")
|
|
417
|
+
)
|
|
418
|
+
return fail("access-denied");
|
|
419
|
+
const backend = this.#backend;
|
|
420
|
+
if (!backend.listen) return fail("not-supported");
|
|
421
|
+
const listened = attempt(() => backend.listen!(this.#backlog));
|
|
422
|
+
if (listened.tag === "err") return listened;
|
|
423
|
+
const listener = listened.val;
|
|
424
|
+
if (typeof listener?.accept !== "function")
|
|
425
|
+
return {
|
|
426
|
+
tag: "err",
|
|
427
|
+
val: { tag: "other", val: "invalid provider listener" },
|
|
428
|
+
};
|
|
429
|
+
this.#state = { kind: "listening", listener };
|
|
430
|
+
this.#bound = true;
|
|
431
|
+
return ok(this.#acceptStream(call.host, listener));
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* The listen stream holds its own backend reference and one revision-owned accept pull at a
|
|
436
|
+
* time. Dropping it aborts that pull, waits for its settlement (the physical acknowledgement),
|
|
437
|
+
* then releases the reference; the socket handle's reference is independent.
|
|
438
|
+
*/
|
|
439
|
+
#acceptStream(host: WasiHost, listener: TcpListener): AsyncIterableIterator<unknown> {
|
|
440
|
+
this.shared.retain();
|
|
441
|
+
const stop = new AbortController();
|
|
442
|
+
let accepting: Promise<unknown> | undefined;
|
|
443
|
+
const next = async (): Promise<TcpSocket> => {
|
|
444
|
+
for (;;) {
|
|
445
|
+
// A retained accept stream belongs to the revision; each pull belongs to the callback
|
|
446
|
+
// reading it now. Do not capture the callback that originally called `listen`.
|
|
447
|
+
const call = callOf(host);
|
|
448
|
+
const signal = call.signal ? AbortSignal.any([stop.signal, call.signal]) : stop.signal;
|
|
449
|
+
const pull = Promise.resolve().then(() => listener.accept(signal));
|
|
450
|
+
accepting = pull;
|
|
451
|
+
this.shared.busy(pull);
|
|
452
|
+
let accepted: Awaited<typeof pull>;
|
|
453
|
+
try {
|
|
454
|
+
accepted = await abortable(
|
|
455
|
+
host.physical(() => pull),
|
|
456
|
+
signal,
|
|
457
|
+
);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
if (signal.aborted) {
|
|
460
|
+
// A provider may acknowledge cancellation with a late accepted connection. Nobody
|
|
461
|
+
// can receive it, but the listener owns its physical disposal until it settles.
|
|
462
|
+
const discarded = pull.then(
|
|
463
|
+
async ({ socket, connection }) => {
|
|
464
|
+
await discardConnection(host, connection);
|
|
465
|
+
await socket.close();
|
|
466
|
+
},
|
|
467
|
+
() => {},
|
|
468
|
+
);
|
|
469
|
+
this.shared.busy(discarded);
|
|
470
|
+
closing(host, () => discarded);
|
|
471
|
+
}
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
const { socket, connection } = accepted;
|
|
475
|
+
let checked: TcpConnection;
|
|
476
|
+
try {
|
|
477
|
+
checked = checkedConnection(connection);
|
|
478
|
+
if (typeof socket?.close !== "function") throw new Error("invalid provider socket");
|
|
479
|
+
} catch (error) {
|
|
480
|
+
closing(host, () => socket?.close?.());
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
const Socket = this.constructor as new (
|
|
484
|
+
...args: ConstructorParameters<typeof TcpSocket>
|
|
485
|
+
) => TcpSocket;
|
|
486
|
+
const child = new Socket(this.access, this.family, new Shared(host, socket), checked);
|
|
487
|
+
// Native accepts any peer once listening on a granted address (`tcp-accept`).
|
|
488
|
+
if (this.#grants.allows(provided(checked.remote), "tcp-accept")) return child;
|
|
489
|
+
child.release();
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
return hostItems(
|
|
493
|
+
next,
|
|
494
|
+
() => {
|
|
495
|
+
stop.abort();
|
|
496
|
+
const pending = accepting;
|
|
497
|
+
closing(host, async () => {
|
|
498
|
+
await pending?.then(
|
|
499
|
+
() => {},
|
|
500
|
+
() => {},
|
|
501
|
+
);
|
|
502
|
+
this.shared.release();
|
|
503
|
+
});
|
|
504
|
+
},
|
|
505
|
+
host.retired,
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
send(
|
|
510
|
+
stream: unknown,
|
|
511
|
+
call: StandardCall = callOf(this.shared.host),
|
|
512
|
+
): Promise<Result<void, ErrorCode>> {
|
|
513
|
+
const data = guestBytes(stream, call.host.retired);
|
|
514
|
+
if (this.#state.kind !== "connected" || this.#sent) {
|
|
515
|
+
void data.return!();
|
|
516
|
+
return Promise.resolve(fail("invalid-state"));
|
|
517
|
+
}
|
|
518
|
+
const connection = this.#state.connection;
|
|
519
|
+
const locked = attempt(() => connection.writable.getWriter());
|
|
520
|
+
if (locked.tag === "err") {
|
|
521
|
+
void data.return!();
|
|
522
|
+
return Promise.resolve(locked);
|
|
523
|
+
}
|
|
524
|
+
this.#sent = true;
|
|
525
|
+
const host = call.host;
|
|
526
|
+
const writer = locked.val;
|
|
527
|
+
this.shared.retain();
|
|
528
|
+
const value = (async (): Promise<Result<void, ErrorCode>> => {
|
|
529
|
+
try {
|
|
530
|
+
for await (const chunk of data) await host.physical(() => writer.write(chunk));
|
|
531
|
+
// A clean end of the guest stream is a write shutdown, acknowledged by its promise.
|
|
532
|
+
const shutdown = writer.close();
|
|
533
|
+
closing(host, () => shutdown);
|
|
534
|
+
await shutdown;
|
|
535
|
+
return ok(undefined);
|
|
536
|
+
} catch (error) {
|
|
537
|
+
void data.return!();
|
|
538
|
+
const aborting = writer.abort(error);
|
|
539
|
+
closing(host, () => aborting);
|
|
540
|
+
return { tag: "err", val: socketCode(error) };
|
|
541
|
+
} finally {
|
|
542
|
+
this.shared.release();
|
|
543
|
+
}
|
|
544
|
+
})();
|
|
545
|
+
host.cleanup(() => value);
|
|
546
|
+
return value;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
receive(
|
|
550
|
+
call: StandardCall = callOf(this.shared.host),
|
|
551
|
+
): [AsyncIterableIterator<Uint8Array>, Promise<Result<void, ErrorCode>>] {
|
|
552
|
+
const empty = () =>
|
|
553
|
+
hostBytes(
|
|
554
|
+
async () => undefined,
|
|
555
|
+
() => {},
|
|
556
|
+
call.host.retired,
|
|
557
|
+
);
|
|
558
|
+
if (this.#state.kind !== "connected" || this.#received)
|
|
559
|
+
return [empty(), Promise.resolve(fail("invalid-state"))];
|
|
560
|
+
const connection = this.#state.connection;
|
|
561
|
+
const locked = attempt(() => connection.readable.getReader());
|
|
562
|
+
if (locked.tag === "err") return [empty(), Promise.resolve(locked)];
|
|
563
|
+
this.#received = true;
|
|
564
|
+
const host = call.host;
|
|
565
|
+
const reader = locked.val;
|
|
566
|
+
this.shared.retain();
|
|
567
|
+
let settle!: (result: Result<void, ErrorCode>) => void;
|
|
568
|
+
const done = new Promise<Result<void, ErrorCode>>((resolve) => {
|
|
569
|
+
settle = resolve;
|
|
570
|
+
});
|
|
571
|
+
const close = (end: "eof" | "dropped" | "failed") => {
|
|
572
|
+
closing(host, async () => {
|
|
573
|
+
// A drop or failure shuts down reads; its promise is the acknowledgement.
|
|
574
|
+
if (end !== "eof") await reader.cancel().catch(() => {});
|
|
575
|
+
this.shared.release();
|
|
576
|
+
});
|
|
577
|
+
};
|
|
578
|
+
const stream = hostBytes(
|
|
579
|
+
async () => {
|
|
580
|
+
for (;;) {
|
|
581
|
+
const { done: end, value } = await host.physical(() => reader.read());
|
|
582
|
+
if (end) return undefined;
|
|
583
|
+
if (!(value instanceof Uint8Array)) throw new Error("invalid provider chunk");
|
|
584
|
+
// Empty chunks are legal and are not the end of the stream.
|
|
585
|
+
if (value.byteLength) return value.slice();
|
|
586
|
+
}
|
|
587
|
+
},
|
|
588
|
+
// Upstream: end of stream and an early drop are both `ok`; a failure is its code.
|
|
589
|
+
(end, failure) => {
|
|
590
|
+
close(end);
|
|
591
|
+
settle(end === "failed" ? { tag: "err", val: socketCode(failure) } : ok(undefined));
|
|
592
|
+
},
|
|
593
|
+
host.retired,
|
|
594
|
+
);
|
|
595
|
+
return [stream, done];
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
getLocalAddress(): Result<IpSocketAddress, ErrorCode> {
|
|
599
|
+
if (this.#state.kind === "closed") return { tag: "err", val: this.#state.code };
|
|
600
|
+
if (!this.#bound || this.#state.kind === "connecting") return fail("invalid-state");
|
|
601
|
+
return localAddress(this.#backend.local);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
getRemoteAddress(): Result<IpSocketAddress, ErrorCode> {
|
|
605
|
+
if (this.#state.kind === "closed") return { tag: "err", val: this.#state.code };
|
|
606
|
+
if (this.#state.kind !== "connected") return fail("invalid-state");
|
|
607
|
+
return ok(toWit(provided(this.#state.connection.remote)));
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
getIsListening(): boolean {
|
|
611
|
+
return this.#state.kind === "listening";
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
getAddressFamily(): IpAddressFamily {
|
|
615
|
+
return this.family;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
setListenBacklogSize(value: bigint): Result<void, ErrorCode> {
|
|
619
|
+
if (value === 0n) return fail("invalid-argument");
|
|
620
|
+
const backlog = value > BigInt(MAX_BACKLOG) ? MAX_BACKLOG : Number(value);
|
|
621
|
+
switch (this.#state.kind) {
|
|
622
|
+
case "default":
|
|
623
|
+
this.#backlog = backlog;
|
|
624
|
+
return ok(undefined);
|
|
625
|
+
case "listening":
|
|
626
|
+
return setOption<TcpOptions, "listenBacklogSize">(
|
|
627
|
+
this.#backend,
|
|
628
|
+
"listenBacklogSize",
|
|
629
|
+
BigInt(backlog),
|
|
630
|
+
);
|
|
631
|
+
case "closed":
|
|
632
|
+
return { tag: "err", val: this.#state.code };
|
|
633
|
+
default:
|
|
634
|
+
return fail("invalid-state");
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
#get<K extends keyof TcpOptions>(name: K, valid: (v: unknown) => boolean) {
|
|
639
|
+
if (this.#state.kind === "closed") return { tag: "err" as const, val: this.#state.code };
|
|
640
|
+
return getOption<TcpOptions, K>(this.#backend, name, valid);
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
#set<K extends keyof TcpOptions>(name: K, value: TcpOptions[K], positive: boolean) {
|
|
644
|
+
if (positive && (value === 0 || value === 0n)) return fail("invalid-argument");
|
|
645
|
+
if (this.#state.kind === "closed") return { tag: "err" as const, val: this.#state.code };
|
|
646
|
+
return setOption<TcpOptions, K>(this.#backend, name, value);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
getKeepAliveEnabled() {
|
|
650
|
+
return this.#get("keepAliveEnabled", isBool);
|
|
651
|
+
}
|
|
652
|
+
setKeepAliveEnabled(value: boolean) {
|
|
653
|
+
return this.#set("keepAliveEnabled", value, false);
|
|
654
|
+
}
|
|
655
|
+
getKeepAliveIdleTime() {
|
|
656
|
+
return this.#get("keepAliveIdleTime", isU64);
|
|
657
|
+
}
|
|
658
|
+
setKeepAliveIdleTime(value: bigint) {
|
|
659
|
+
return this.#set("keepAliveIdleTime", value, true);
|
|
660
|
+
}
|
|
661
|
+
getKeepAliveInterval() {
|
|
662
|
+
return this.#get("keepAliveInterval", isU64);
|
|
663
|
+
}
|
|
664
|
+
setKeepAliveInterval(value: bigint) {
|
|
665
|
+
return this.#set("keepAliveInterval", value, true);
|
|
666
|
+
}
|
|
667
|
+
getKeepAliveCount() {
|
|
668
|
+
return this.#get("keepAliveCount", isU32);
|
|
669
|
+
}
|
|
670
|
+
setKeepAliveCount(value: number) {
|
|
671
|
+
return this.#set("keepAliveCount", value, true);
|
|
672
|
+
}
|
|
673
|
+
getHopLimit() {
|
|
674
|
+
return this.#get("hopLimit", isU8);
|
|
675
|
+
}
|
|
676
|
+
setHopLimit(value: number) {
|
|
677
|
+
return this.#set("hopLimit", value, true);
|
|
678
|
+
}
|
|
679
|
+
getReceiveBufferSize() {
|
|
680
|
+
return this.#get("receiveBufferSize", isU64);
|
|
681
|
+
}
|
|
682
|
+
setReceiveBufferSize(value: bigint) {
|
|
683
|
+
return this.#set("receiveBufferSize", value, true);
|
|
684
|
+
}
|
|
685
|
+
getSendBufferSize() {
|
|
686
|
+
return this.#get("sendBufferSize", isU64);
|
|
687
|
+
}
|
|
688
|
+
setSendBufferSize(value: bigint) {
|
|
689
|
+
return this.#set("sendBufferSize", value, true);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// ---------------------------------------------------------------------------------------------
|
|
694
|
+
// UDP
|
|
695
|
+
|
|
696
|
+
/** `wasi:sockets/types#udp-socket`. Peer association and receive filtering are host state. */
|
|
697
|
+
export class UdpSocket extends SocketResource {
|
|
698
|
+
#bound = false;
|
|
699
|
+
#remote: Address | undefined;
|
|
700
|
+
|
|
701
|
+
constructor(
|
|
702
|
+
readonly access: SocketAccess,
|
|
703
|
+
readonly family: IpAddressFamily,
|
|
704
|
+
readonly shared: Shared<UdpBackend>,
|
|
705
|
+
) {
|
|
706
|
+
super();
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
protected close(): void {
|
|
710
|
+
this.shared.release();
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
get #backend(): UdpBackend {
|
|
714
|
+
return this.shared.backend;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
get #grants() {
|
|
718
|
+
return this.access.grants;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
bind(local: IpSocketAddress): Result<void, ErrorCode> {
|
|
722
|
+
if (this.#bound) return fail("invalid-state");
|
|
723
|
+
const address = fromWit(local)!;
|
|
724
|
+
if (!hasFamily(address, this.family)) return fail("invalid-argument");
|
|
725
|
+
if (!this.#grants.allows(address, "udp-bind")) return fail("access-denied");
|
|
726
|
+
return this.#bind(address);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
#bind(address: Address): Result<void, ErrorCode> {
|
|
730
|
+
const backend = this.#backend;
|
|
731
|
+
if (!backend.bind) return fail("not-supported");
|
|
732
|
+
const bound = attempt(() => backend.bind!(toWit(address)));
|
|
733
|
+
if (bound.tag === "ok") this.#bound = true;
|
|
734
|
+
return bound;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
connect(remote: IpSocketAddress): Result<void, ErrorCode> {
|
|
738
|
+
const address = fromWit(remote)!;
|
|
739
|
+
if (!hasFamily(address, this.family) || !isRemote(address)) return fail("invalid-argument");
|
|
740
|
+
const implicit = unspecified(this.family);
|
|
741
|
+
if (!this.#bound && !this.#grants.allows(implicit, "udp-bind")) return fail("access-denied");
|
|
742
|
+
if (!this.#grants.allows(address, "udp-send") || !this.#grants.allows(address, "udp-receive"))
|
|
743
|
+
return fail("access-denied");
|
|
744
|
+
if (!this.#bound) {
|
|
745
|
+
const bound = this.#bind(implicit);
|
|
746
|
+
if (bound.tag === "err") return bound;
|
|
747
|
+
}
|
|
748
|
+
this.#remote = address;
|
|
749
|
+
return ok(undefined);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
disconnect(): Result<void, ErrorCode> {
|
|
753
|
+
if (!this.#remote) return fail("invalid-state");
|
|
754
|
+
this.#remote = undefined;
|
|
755
|
+
return ok(undefined);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
async send(
|
|
759
|
+
data: Uint8Array,
|
|
760
|
+
remote: IpSocketAddress | undefined,
|
|
761
|
+
call: StandardCall = callOf(this.shared.host),
|
|
762
|
+
): Promise<Result<void, ErrorCode>> {
|
|
763
|
+
if (data.byteLength > MAX_DATAGRAM) return fail("datagram-too-large");
|
|
764
|
+
let target: Address;
|
|
765
|
+
if (remote !== undefined) {
|
|
766
|
+
target = fromWit(remote)!;
|
|
767
|
+
if (!isRemote(target) || !hasFamily(target, this.family)) return fail("invalid-argument");
|
|
768
|
+
if (this.#remote && key(this.#remote) !== key(target)) return fail("invalid-argument");
|
|
769
|
+
} else if (this.#remote) target = this.#remote;
|
|
770
|
+
else return fail("invalid-argument");
|
|
771
|
+
if (!this.#bound && !this.#grants.allows(unspecified(this.family), "udp-bind"))
|
|
772
|
+
return fail("access-denied");
|
|
773
|
+
if (!this.#grants.allows(target, "udp-send")) return fail("access-denied");
|
|
774
|
+
const abort = new AbortController();
|
|
775
|
+
const stop = () => abort.abort();
|
|
776
|
+
call.signal?.addEventListener("abort", stop, { once: true });
|
|
777
|
+
try {
|
|
778
|
+
await abortable(
|
|
779
|
+
call.host.physical(() => this.#backend.send(data.slice(), toWit(target), abort.signal)),
|
|
780
|
+
call.signal,
|
|
781
|
+
);
|
|
782
|
+
this.#bound = true;
|
|
783
|
+
return ok(undefined);
|
|
784
|
+
} catch (error) {
|
|
785
|
+
if (call.signal?.aborted) return callCancelled();
|
|
786
|
+
return { tag: "err", val: socketCode(error) };
|
|
787
|
+
} finally {
|
|
788
|
+
call.signal?.removeEventListener("abort", stop);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
async receive(
|
|
793
|
+
call: StandardCall = callOf(this.shared.host),
|
|
794
|
+
): Promise<Result<[Uint8Array, IpSocketAddress], ErrorCode>> {
|
|
795
|
+
if (!this.#bound) return fail("invalid-state");
|
|
796
|
+
const abort = new AbortController();
|
|
797
|
+
const stop = () => abort.abort();
|
|
798
|
+
call.signal?.addEventListener("abort", stop, { once: true });
|
|
799
|
+
try {
|
|
800
|
+
for (;;) {
|
|
801
|
+
// A datagram arriving after cancellation is dropped, like network loss.
|
|
802
|
+
const datagram = await abortable(
|
|
803
|
+
call.host.physical(() => this.#backend.receive(abort.signal)),
|
|
804
|
+
call.signal,
|
|
805
|
+
);
|
|
806
|
+
const sender = provided(datagram?.remote);
|
|
807
|
+
if (!(datagram.data instanceof Uint8Array) || datagram.data.byteLength > MAX_DATAGRAM)
|
|
808
|
+
throw new Error("invalid provider datagram");
|
|
809
|
+
// Datagrams from ungranted or unconnected peers are dropped, never delivered.
|
|
810
|
+
if (this.#remote && key(this.#remote) !== key(sender)) continue;
|
|
811
|
+
if (!this.#grants.allows(sender, "udp-receive")) continue;
|
|
812
|
+
return ok([datagram.data.slice(), toWit(sender)] as [Uint8Array, IpSocketAddress]);
|
|
813
|
+
}
|
|
814
|
+
} catch (error) {
|
|
815
|
+
if (call.signal?.aborted) return callCancelled();
|
|
816
|
+
return { tag: "err", val: socketCode(error) };
|
|
817
|
+
} finally {
|
|
818
|
+
call.signal?.removeEventListener("abort", stop);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
getLocalAddress(): Result<IpSocketAddress, ErrorCode> {
|
|
823
|
+
return this.#bound ? localAddress(this.#backend.local) : fail("invalid-state");
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
getRemoteAddress(): Result<IpSocketAddress, ErrorCode> {
|
|
827
|
+
return this.#remote ? ok(toWit(this.#remote)) : fail("invalid-state");
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
getAddressFamily(): IpAddressFamily {
|
|
831
|
+
return this.family;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
#set<K extends keyof UdpOptions>(name: K, value: UdpOptions[K]) {
|
|
835
|
+
if (value === 0 || value === 0n) return fail("invalid-argument");
|
|
836
|
+
return setOption<UdpOptions, K>(this.#backend, name, value);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
getUnicastHopLimit() {
|
|
840
|
+
return getOption<UdpOptions, "unicastHopLimit">(this.#backend, "unicastHopLimit", isU8);
|
|
841
|
+
}
|
|
842
|
+
setUnicastHopLimit(value: number) {
|
|
843
|
+
return this.#set("unicastHopLimit", value);
|
|
844
|
+
}
|
|
845
|
+
getReceiveBufferSize() {
|
|
846
|
+
return getOption<UdpOptions, "receiveBufferSize">(this.#backend, "receiveBufferSize", isU64);
|
|
847
|
+
}
|
|
848
|
+
setReceiveBufferSize(value: bigint) {
|
|
849
|
+
return this.#set("receiveBufferSize", value);
|
|
850
|
+
}
|
|
851
|
+
getSendBufferSize() {
|
|
852
|
+
return getOption<UdpOptions, "sendBufferSize">(this.#backend, "sendBufferSize", isU64);
|
|
853
|
+
}
|
|
854
|
+
setSendBufferSize(value: bigint) {
|
|
855
|
+
return this.#set("sendBufferSize", value);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// ---------------------------------------------------------------------------------------------
|
|
860
|
+
// name lookup and binding
|
|
861
|
+
|
|
862
|
+
/** `resolve-addresses`: grant first (upstream order), then `url::Host::parse`, then provider. */
|
|
863
|
+
async function resolveAddresses(
|
|
864
|
+
access: SocketAccess | undefined,
|
|
865
|
+
name: string,
|
|
866
|
+
call: StandardCall,
|
|
867
|
+
): Promise<Result<IpAddress[], LookupErrorCode>> {
|
|
868
|
+
const failure = (tag: LookupErrorCode["tag"]) => ({
|
|
869
|
+
tag: "err" as const,
|
|
870
|
+
val: { tag } as LookupErrorCode,
|
|
871
|
+
});
|
|
872
|
+
if (!access?.grants.resolve) return failure("access-denied");
|
|
873
|
+
const parsed = parseHostName(name);
|
|
874
|
+
if (!parsed) return failure("invalid-argument");
|
|
875
|
+
if ("ip" in parsed) return ok([parsed.ip]);
|
|
876
|
+
const resolve = access.provider?.resolve;
|
|
877
|
+
if (!resolve) return failure("permanent-resolver-failure");
|
|
878
|
+
const abort = new AbortController();
|
|
879
|
+
const stop = () => abort.abort();
|
|
880
|
+
call.signal?.addEventListener("abort", stop, { once: true });
|
|
881
|
+
try {
|
|
882
|
+
const found = await abortable(
|
|
883
|
+
call.host.physical(() => resolve.call(access.provider, parsed.domain, abort.signal)),
|
|
884
|
+
call.signal,
|
|
885
|
+
);
|
|
886
|
+
if (!Array.isArray(found)) throw new Error("invalid provider result");
|
|
887
|
+
const addresses = found.map(checkedIpAddress);
|
|
888
|
+
if (addresses.some((address) => address === undefined))
|
|
889
|
+
throw new Error("invalid provider address");
|
|
890
|
+
// The standard never succeeds with no addresses.
|
|
891
|
+
if (!addresses.length) return failure("name-unresolvable");
|
|
892
|
+
return ok(addresses as IpAddress[]);
|
|
893
|
+
} catch (error) {
|
|
894
|
+
if (call.signal?.aborted) return callCancelled();
|
|
895
|
+
return { tag: "err", val: lookupCode(error) };
|
|
896
|
+
} finally {
|
|
897
|
+
call.signal?.removeEventListener("abort", stop);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/** `create` for one protocol: grant, then capability, then the provider's synchronous create. */
|
|
902
|
+
function create<B extends { close(): Promise<void> }, S>(
|
|
903
|
+
access: SocketAccess | undefined,
|
|
904
|
+
allowed: boolean,
|
|
905
|
+
factory: { create(family: IpAddressFamily): B } | undefined,
|
|
906
|
+
family: IpAddressFamily,
|
|
907
|
+
host: WasiHost,
|
|
908
|
+
make: (access: SocketAccess, shared: Shared<B>) => S,
|
|
909
|
+
): Result<S, ErrorCode> {
|
|
910
|
+
if (!access || !allowed) return fail("access-denied");
|
|
911
|
+
if (!factory) return fail("not-supported");
|
|
912
|
+
const created = attempt(() => factory.create(family));
|
|
913
|
+
if (created.tag === "err") return created;
|
|
914
|
+
if (typeof created.val?.close !== "function")
|
|
915
|
+
return {
|
|
916
|
+
tag: "err",
|
|
917
|
+
val: { tag: "other", val: "invalid provider socket" },
|
|
918
|
+
};
|
|
919
|
+
return ok(make(access, new Shared(host, created.val)));
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/** The `wasi:sockets` import objects of one instance; resource classes are per instance. */
|
|
923
|
+
export function socketImports(
|
|
924
|
+
host: WasiHost,
|
|
925
|
+
bindings: SocketBindings,
|
|
926
|
+
): WasiInterfaces<"types" | "ip-name-lookup"> {
|
|
927
|
+
const types = bindings.types;
|
|
928
|
+
class Tcp extends TcpSocket {
|
|
929
|
+
static create(family: IpAddressFamily) {
|
|
930
|
+
return create(
|
|
931
|
+
types,
|
|
932
|
+
types?.grants.tcp ?? false,
|
|
933
|
+
types?.provider?.tcp,
|
|
934
|
+
family,
|
|
935
|
+
host,
|
|
936
|
+
(access, shared) => new Tcp(access, family, shared),
|
|
937
|
+
);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
class Udp extends UdpSocket {
|
|
941
|
+
static create(family: IpAddressFamily) {
|
|
942
|
+
return create(
|
|
943
|
+
types,
|
|
944
|
+
types?.grants.udp ?? false,
|
|
945
|
+
types?.provider?.udp,
|
|
946
|
+
family,
|
|
947
|
+
host,
|
|
948
|
+
(access, shared) => new Udp(access, family, shared),
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return {
|
|
953
|
+
types: { TcpSocket: Tcp, UdpSocket: Udp },
|
|
954
|
+
"ip-name-lookup": {
|
|
955
|
+
resolveAddresses: (name: string) => resolveAddresses(bindings.lookup, name, callOf(host)),
|
|
956
|
+
},
|
|
957
|
+
};
|
|
958
|
+
}
|