@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.
Files changed (241) hide show
  1. package/README.md +43 -17
  2. package/dist/authoring/types.d.ts +64 -3
  3. package/dist/authoring/wit.d.ts +6 -0
  4. package/dist/bridge/commands.d.ts +1190 -0
  5. package/dist/bridge/identifiers.d.ts +2 -0
  6. package/dist/bridge/kernel.d.ts +18 -107
  7. package/dist/bridge/protocol.d.ts +3 -138
  8. package/dist/browser.d.ts +14 -1
  9. package/dist/browser.js +141 -3298
  10. package/dist/chunks/browser-b8jamxw2.js +3399 -0
  11. package/dist/chunks/execution-nsqc6nrt.js +1419 -0
  12. package/dist/chunks/index-01zk0xqx.js +160 -0
  13. package/dist/chunks/index-3fjdfdfd.js +152 -0
  14. package/dist/chunks/index-aaymjn7v.js +787 -0
  15. package/dist/chunks/index-c1w7z9hx.js +356 -0
  16. package/dist/chunks/index-h8t0n42q.js +738 -0
  17. package/dist/chunks/index-hfds9mzp.js +308 -0
  18. package/dist/chunks/index-kr4x67wt.js +177 -0
  19. package/dist/chunks/index-kr6bnh34.js +117 -0
  20. package/dist/chunks/index-kyt9dj0a.js +1421 -0
  21. package/dist/chunks/index-n1wxzc9w.js +830 -0
  22. package/dist/chunks/index-pvac426d.js +74 -0
  23. package/dist/chunks/index-smyds5ce.js +3234 -0
  24. package/dist/chunks/index-sse8aapb.js +121 -0
  25. package/dist/chunks/index-v6heph77.js +643 -0
  26. package/dist/chunks/index-xrdvnv37.js +3448 -0
  27. package/dist/chunks/index-za4mg94e.js +26 -0
  28. package/dist/chunks/index-zkqmnjj8.js +167 -0
  29. package/dist/coordinator.js +9 -500
  30. package/dist/error.d.ts +2 -0
  31. package/dist/errors.d.ts +3 -0
  32. package/dist/guest.d.ts +173 -0
  33. package/dist/guest.js +26 -0
  34. package/dist/host.d.ts +36 -30
  35. package/dist/host.js +37 -3276
  36. package/dist/http/bytes.d.ts +8 -0
  37. package/dist/http/events.d.ts +7 -0
  38. package/dist/http.d.ts +45 -0
  39. package/dist/http.js +291 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +49 -862
  42. package/dist/infrastructure/rpc/client.d.ts +2 -1
  43. package/dist/infrastructure/rpc/resources.d.ts +28 -0
  44. package/dist/interpreter/abi.d.ts +54 -0
  45. package/dist/interpreter/acquire.d.ts +18 -0
  46. package/dist/interpreter/browser-network.d.ts +52 -0
  47. package/dist/interpreter/browser-port.d.ts +55 -0
  48. package/dist/interpreter/browser.d.ts +79 -0
  49. package/dist/interpreter/cli.d.ts +5 -0
  50. package/dist/interpreter/codec.d.ts +42 -0
  51. package/dist/interpreter/component/execution.d.ts +42 -0
  52. package/dist/interpreter/component/host.d.ts +69 -0
  53. package/dist/interpreter/component/instance.d.ts +40 -0
  54. package/dist/interpreter/component/kernel.d.ts +120 -0
  55. package/dist/interpreter/component/names.d.ts +5 -0
  56. package/dist/interpreter/component/port.d.ts +85 -0
  57. package/dist/interpreter/component/prepared.d.ts +97 -0
  58. package/dist/interpreter/component/resources.d.ts +45 -0
  59. package/dist/interpreter/component/revision.d.ts +87 -0
  60. package/dist/interpreter/component/scope.d.ts +116 -0
  61. package/dist/interpreter/component/streams.d.ts +28 -0
  62. package/dist/interpreter/component/values.d.ts +79 -0
  63. package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
  64. package/dist/interpreter/component/wasi-host.d.ts +64 -0
  65. package/dist/interpreter/component/wasi-http.d.ts +33 -0
  66. package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
  67. package/dist/interpreter/component/wasi.d.ts +41 -0
  68. package/dist/interpreter/core.d.ts +64 -0
  69. package/dist/interpreter/fetch-http-provider.d.ts +17 -0
  70. package/dist/interpreter/filesystem/contract.d.ts +85 -0
  71. package/dist/interpreter/filesystem/memory.d.ts +3 -0
  72. package/dist/interpreter/filesystem/opfs.d.ts +3 -0
  73. package/dist/interpreter/filesystem/scope.d.ts +35 -0
  74. package/dist/interpreter/filesystem.d.ts +8 -0
  75. package/dist/interpreter/gate.d.ts +6 -0
  76. package/dist/interpreter/host-protocol.d.ts +100 -0
  77. package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
  78. package/dist/interpreter/http-ingress.d.ts +96 -0
  79. package/dist/interpreter/http-provider.d.ts +85 -0
  80. package/dist/interpreter/io.d.ts +20 -0
  81. package/dist/interpreter/mobile.d.ts +149 -0
  82. package/dist/interpreter/native-ingress.d.ts +95 -0
  83. package/dist/interpreter/node-port.d.ts +25 -0
  84. package/dist/interpreter/node.d.ts +36 -0
  85. package/dist/interpreter/revision.d.ts +64 -0
  86. package/dist/interpreter/scope.d.ts +89 -0
  87. package/dist/interpreter/socket-addresses.d.ts +50 -0
  88. package/dist/interpreter/socket-provider.d.ts +110 -0
  89. package/dist/interpreter/standard-cli.d.ts +34 -0
  90. package/dist/interpreter/standard-codec.d.ts +96 -0
  91. package/dist/interpreter/standard-filesystem.d.ts +47 -0
  92. package/dist/interpreter/standard-host.d.ts +71 -0
  93. package/dist/interpreter/standard-http-values.d.ts +159 -0
  94. package/dist/interpreter/standard-http.d.ts +9 -0
  95. package/dist/interpreter/standard-ingress.d.ts +63 -0
  96. package/dist/interpreter/standard-sockets.d.ts +177 -0
  97. package/dist/interpreter/standard-streams.d.ts +218 -0
  98. package/dist/interpreter/standard-system.d.ts +35 -0
  99. package/dist/interpreter/standard-utf8.d.ts +4 -0
  100. package/dist/interpreter/standard.d.ts +18 -0
  101. package/dist/interpreter/types.d.ts +152 -0
  102. package/dist/interpreter/wit-shape.d.ts +92 -0
  103. package/dist/manager.js +5 -332
  104. package/dist/msgpack.js +9 -615
  105. package/dist/node.d.ts +8 -1
  106. package/dist/node.js +248 -3287
  107. package/dist/rpc.js +196 -699
  108. package/dist/runtime/adapters.d.ts +120 -0
  109. package/dist/runtime/adapters.js +38 -0
  110. package/dist/runtime/calls.d.ts +9 -3
  111. package/dist/runtime/lifecycle.d.ts +3 -1
  112. package/dist/runtime/orbs.d.ts +5 -4
  113. package/dist/runtime/references.d.ts +27 -1
  114. package/dist/runtime/reload.d.ts +5 -3
  115. package/dist/runtime/scopes.d.ts +1 -1
  116. package/dist/runtime/signals.d.ts +4 -0
  117. package/dist/runtime/wit-client.d.ts +38 -0
  118. package/dist/telemetry.js +4 -25
  119. package/dist/tooling/build.d.ts +2 -2
  120. package/dist/tooling/client-resources.d.ts +23 -0
  121. package/dist/tooling/client.d.ts +10 -0
  122. package/dist/tooling/component-glue.d.ts +17 -0
  123. package/dist/tooling/component.d.ts +11 -0
  124. package/dist/tooling/index.d.ts +3 -1
  125. package/dist/tooling/index.js +1155 -102
  126. package/dist/tooling/resolver.d.ts +4 -4
  127. package/dist/tooling/typecheck.d.ts +2 -1
  128. package/dist/tooling/types.d.ts +27 -12
  129. package/dist/tooling/wit.d.ts +9 -0
  130. package/dist/wasi/wasi-clocks-types.d.ts +2 -0
  131. package/dist/wasi/wasi-http-client.d.ts +5 -0
  132. package/dist/wasi/wasi-http-types.d.ts +285 -0
  133. package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
  134. package/dist/wasi/wasi-sockets-types.d.ts +146 -0
  135. package/package.json +62 -35
  136. package/src/authoring/declaration.ts +1 -1
  137. package/src/authoring/types.ts +53 -3
  138. package/src/authoring/wit.ts +15 -0
  139. package/src/bridge/commands.ts +1105 -0
  140. package/src/bridge/identifiers.ts +2 -0
  141. package/src/bridge/kernel.ts +56 -98
  142. package/src/bridge/protocol.ts +3 -142
  143. package/src/browser.ts +90 -6
  144. package/src/context-key.ts +4 -7
  145. package/src/error.ts +1 -1
  146. package/src/errors.ts +7 -0
  147. package/src/guest.ts +327 -0
  148. package/src/host.ts +128 -23
  149. package/src/http/bytes.ts +87 -0
  150. package/src/http/events.ts +34 -0
  151. package/src/http.ts +272 -0
  152. package/src/index.ts +3 -0
  153. package/src/infrastructure/rpc/client.ts +136 -17
  154. package/src/infrastructure/rpc/resources.ts +123 -0
  155. package/src/interpreter/abi.ts +69 -0
  156. package/src/interpreter/acquire.ts +58 -0
  157. package/src/interpreter/browser-network.ts +170 -0
  158. package/src/interpreter/browser-port.ts +425 -0
  159. package/src/interpreter/browser.ts +340 -0
  160. package/src/interpreter/cli.ts +30 -0
  161. package/src/interpreter/codec.ts +298 -0
  162. package/src/interpreter/component/execution.ts +264 -0
  163. package/src/interpreter/component/host.ts +409 -0
  164. package/src/interpreter/component/instance.ts +138 -0
  165. package/src/interpreter/component/kernel.ts +611 -0
  166. package/src/interpreter/component/names.ts +13 -0
  167. package/src/interpreter/component/port.ts +598 -0
  168. package/src/interpreter/component/prepared.ts +194 -0
  169. package/src/interpreter/component/resources.ts +345 -0
  170. package/src/interpreter/component/revision.ts +702 -0
  171. package/src/interpreter/component/scope.ts +447 -0
  172. package/src/interpreter/component/streams.ts +180 -0
  173. package/src/interpreter/component/values.ts +254 -0
  174. package/src/interpreter/component/wasi-filesystem.ts +472 -0
  175. package/src/interpreter/component/wasi-host.ts +197 -0
  176. package/src/interpreter/component/wasi-http.ts +939 -0
  177. package/src/interpreter/component/wasi-sockets.ts +958 -0
  178. package/src/interpreter/component/wasi.ts +238 -0
  179. package/src/interpreter/core.ts +386 -0
  180. package/src/interpreter/fetch-http-provider.ts +98 -0
  181. package/src/interpreter/filesystem/contract.ts +138 -0
  182. package/src/interpreter/filesystem/memory.ts +180 -0
  183. package/src/interpreter/filesystem/opfs.ts +294 -0
  184. package/src/interpreter/filesystem/scope.ts +390 -0
  185. package/src/interpreter/filesystem.ts +20 -0
  186. package/src/interpreter/gate.ts +55 -0
  187. package/src/interpreter/host-protocol.ts +242 -0
  188. package/src/interpreter/http-ingress-fetch.ts +133 -0
  189. package/src/interpreter/http-ingress.ts +203 -0
  190. package/src/interpreter/http-provider.ts +105 -0
  191. package/src/interpreter/io.ts +66 -0
  192. package/src/interpreter/mobile.ts +385 -0
  193. package/src/interpreter/native-ingress.ts +550 -0
  194. package/src/interpreter/node-port.ts +218 -0
  195. package/src/interpreter/node.ts +114 -0
  196. package/src/interpreter/revision.ts +450 -0
  197. package/src/interpreter/scope.ts +453 -0
  198. package/src/interpreter/socket-addresses.ts +246 -0
  199. package/src/interpreter/socket-provider.ts +126 -0
  200. package/src/interpreter/standard-cli.ts +184 -0
  201. package/src/interpreter/standard-codec.ts +403 -0
  202. package/src/interpreter/standard-filesystem.ts +545 -0
  203. package/src/interpreter/standard-host.ts +840 -0
  204. package/src/interpreter/standard-http-values.ts +624 -0
  205. package/src/interpreter/standard-http.ts +622 -0
  206. package/src/interpreter/standard-ingress.ts +344 -0
  207. package/src/interpreter/standard-sockets.ts +847 -0
  208. package/src/interpreter/standard-streams.ts +710 -0
  209. package/src/interpreter/standard-system.ts +182 -0
  210. package/src/interpreter/standard-utf8.ts +72 -0
  211. package/src/interpreter/standard.ts +283 -0
  212. package/src/interpreter/types.ts +163 -0
  213. package/src/interpreter/wit-shape.ts +175 -0
  214. package/src/node.ts +43 -14
  215. package/src/runtime/activities.ts +6 -6
  216. package/src/runtime/adapters.ts +314 -0
  217. package/src/runtime/calls.ts +218 -56
  218. package/src/runtime/context.ts +7 -7
  219. package/src/runtime/lifecycle.ts +36 -17
  220. package/src/runtime/orbs.ts +81 -39
  221. package/src/runtime/programs.ts +16 -8
  222. package/src/runtime/references.ts +128 -11
  223. package/src/runtime/reload.ts +71 -30
  224. package/src/runtime/resources.ts +2 -2
  225. package/src/runtime/scopes.ts +17 -17
  226. package/src/runtime/session.ts +3 -1
  227. package/src/runtime/signals.ts +31 -0
  228. package/src/runtime/wit-client.ts +228 -0
  229. package/src/tooling/build.ts +152 -54
  230. package/src/tooling/client-resources.ts +74 -0
  231. package/src/tooling/client.ts +531 -0
  232. package/src/tooling/component-glue.ts +288 -0
  233. package/src/tooling/component.ts +225 -0
  234. package/src/tooling/index.ts +3 -7
  235. package/src/tooling/resolver.ts +42 -25
  236. package/src/tooling/typecheck.ts +59 -4
  237. package/src/tooling/types.ts +27 -12
  238. package/src/tooling/wit.ts +188 -0
  239. package/dist/embedded.d.ts +0 -1
  240. package/dist/embedded.js +0 -1
  241. package/src/embedded.ts +0 -293
@@ -0,0 +1,598 @@
1
+ /**
2
+ * One isolated component instance and the callback it currently serves.
3
+ *
4
+ * Every guest entry (a service method, a contribution, an incoming HTTP request) is one admitted
5
+ * callback: the revision's gate serializes entry. A published byte-stream head can park its
6
+ * callback so another entry can proceed while its producer remains physically owned. Host
7
+ * imports resolve their authority from the callback active when they are called;
8
+ * an asynchronous import keeps the callback it captured, never a later one. A callback ends only
9
+ * after every host operation it started has physically settled. A timeout, an uncaught guest
10
+ * exception or a trap poisons the instance, which is never entered again.
11
+ *
12
+ * Physical completion is the generated export task's real exit, observed through the trusted
13
+ * glue's exact build-time instrumentation (`tooling/component-glue.ts`): a callback keeps its admission and its
14
+ * import attribution from entry until that exit, even after its result was returned at
15
+ * `task.return`. A trap, or a task that exits rejected, quarantines the instance and rejects
16
+ * every waiter racing the trap signal. No event-loop timing is used as a completion signal.
17
+ *
18
+ * A callback answers its faults as the native worker's do. A trap, an uncaught guest exception or
19
+ * a timeout answers `unavailable/wasm_executor` with a `component trap: ` message. A busy or closed
20
+ * instance answers `unavailable/wasm_executor`. Every entry of a quarantined instance answers
21
+ * `unavailable/wasm_executor_quarantined` with the trap's message. A structured error that traps
22
+ * the guest, such as a dependency's refusal, is a trap too.
23
+ */
24
+ import { isDescriptor, TembraError } from "../../error.ts";
25
+ import { Errors, type ErrorDescriptor } from "../../errors.ts";
26
+ import type { CoreLimits, TaskObserver } from "./instance.ts";
27
+ import type { CallbackScope } from "./scope.ts";
28
+ import { abortable, type WasiHost } from "./wasi-host.ts";
29
+
30
+ /** The callback a host import acts for. */
31
+ export interface Callback {
32
+ readonly scope: CallbackScope;
33
+ /** The host-issued environment of this callback. */
34
+ readonly environment: bigint;
35
+ /** Physical host operations started by this callback. */
36
+ readonly pending: Set<Promise<unknown>>;
37
+ /** Aborts when the callback ends; its waiters stop while physical work stays tracked. */
38
+ readonly ended: AbortController;
39
+ /** The generated export task this callback entered, bound synchronously at entry. */
40
+ task: number | undefined;
41
+ /** Resolves at that task's real exit. */
42
+ readonly exit: Promise<void>;
43
+ readonly exited: () => void;
44
+ }
45
+
46
+ /**
47
+ * Whether `error` is the executor's own answer to a fault, which is answered unchanged. Structured
48
+ * errors are recognized by their fields, as `failure` does, so one from another SDK copy counts.
49
+ */
50
+ function executorFault(error: unknown): error is ErrorDescriptor {
51
+ return isDescriptor(error) && error.reason === Errors.Unavailable.WasmExecutor.reason;
52
+ }
53
+
54
+ /** The text of a failure, a structured one as the native worker writes it: `code/reason: message`. */
55
+ export function failureText(error: unknown): string {
56
+ try {
57
+ if (isDescriptor(error)) return `${error.code}/${error.reason}: ${error.message}`;
58
+ return error instanceof Error ? error.message : String(error);
59
+ } catch {
60
+ // An arbitrary thrown value must not hide the fault it stands for.
61
+ return "the component trapped";
62
+ }
63
+ }
64
+
65
+ /** The message of a component fault, as the native worker words a trap. */
66
+ function trapMessage(cause: unknown): string {
67
+ if (executorFault(cause)) return cause.message;
68
+ return `component trap: ${cause === undefined ? "the component trapped" : failureText(cause)}`;
69
+ }
70
+
71
+ /** The answer of each fault already answered: every wait the fault ends sees one error. */
72
+ const faults = new WeakMap<object, TembraError>();
73
+
74
+ /**
75
+ * The error a callback answers for a fault of the component: `unavailable/wasm_executor`, whatever
76
+ * caused it, a structured error included, since anything the guest throws traps it. A guest's own
77
+ * refusal is its WIT `err`, a value that never reaches here.
78
+ */
79
+ function fault(error: unknown): TembraError {
80
+ if (error instanceof TembraError && executorFault(error)) return error;
81
+ const object = typeof error === "object" && error !== null ? error : undefined;
82
+ const known = object && faults.get(object);
83
+ if (known) return known;
84
+ const answer = executorFault(error)
85
+ ? new TembraError(error, error.message, { cause: error })
86
+ : new TembraError(Errors.Unavailable.WasmExecutor, trapMessage(error), { cause: error });
87
+ if (object) faults.set(object, answer);
88
+ return answer;
89
+ }
90
+
91
+ export class ComponentPort {
92
+ exports: Record<string, Record<string, (...args: unknown[]) => unknown>> | undefined;
93
+ #active: Callback | undefined;
94
+ /** All physically live callbacks, including parked stream producers. */
95
+ readonly #callbacks = new Set<Callback>();
96
+ readonly #completions = new Set<Promise<void>>();
97
+ #destroying = false;
98
+ readonly #destructorTasks = new Set<number>();
99
+ readonly #nestedDestructors = new Map<number, { callback: Callback; exited(): void }>();
100
+ readonly #destructorPending = new Set<Promise<unknown>>();
101
+ #destructorExited: (() => void) | undefined;
102
+ /** The callback being entered right now; its export task starts synchronously. */
103
+ #admitting: Callback | undefined;
104
+ /** Whether any callback was admitted; earlier tasks are the instance's own initialization. */
105
+ #admitted = false;
106
+ /** Export tasks of admitted callbacks until their exit. */
107
+ readonly #tasks = new Map<number, Callback>();
108
+ #access: { currentRootTask(): number | null } | undefined;
109
+ /** Rejects once the instance is quarantined; waiters race it. */
110
+ readonly #trap: Promise<never>;
111
+ #rejectTrap!: (error: unknown) => void;
112
+
113
+ /** Lifecycle notifications from the instrumented glue of this instance. */
114
+ readonly observer: TaskObserver = {
115
+ attach: (access) => {
116
+ this.#access = access;
117
+ },
118
+ taskStarted: ({ id, entry }) => {
119
+ if (this.#destroying) {
120
+ if (entry !== "<resource-drop>") {
121
+ this.poison(new Error("A destructor entered a non-destructor export task"));
122
+ return;
123
+ }
124
+ this.#destructorTasks.add(id);
125
+ return;
126
+ }
127
+ // A guest can drop an owner returned through an own argument. JCO gives its canonical
128
+ // destructor a separate task; only the exact executing parent proves its admission.
129
+ if (entry === "<resource-drop>") {
130
+ const parent = this.#access?.currentRootTask();
131
+ const callback =
132
+ parent === null || parent === undefined
133
+ ? undefined
134
+ : (this.#tasks.get(parent) ?? this.#nestedDestructors.get(parent)?.callback);
135
+ if (callback) {
136
+ const exit = Promise.withResolvers<void>();
137
+ this.#nestedDestructors.set(id, { callback, exited: exit.resolve });
138
+ this.physical(callback, exit.promise);
139
+ return;
140
+ }
141
+ if (this.#admitted)
142
+ this.poison(new Error("A resource destructor started outside an admitted parent task"));
143
+ return;
144
+ }
145
+ const callback = this.#admitting;
146
+ if (!callback) {
147
+ // Instantiation runs the component's own initialization before any admission.
148
+ if (this.#admitted)
149
+ this.poison(new Error("An export task started outside an admitted callback"));
150
+ return;
151
+ }
152
+ if (callback.task !== undefined) {
153
+ this.poison(new Error("One callback entered more than one export task"));
154
+ return;
155
+ }
156
+ callback.task = id;
157
+ this.#tasks.set(id, callback);
158
+ },
159
+ taskExited: ({ id, rejected, error }) => {
160
+ const nested = this.#nestedDestructors.get(id);
161
+ if (nested) {
162
+ this.#nestedDestructors.delete(id);
163
+ if (rejected || error !== undefined)
164
+ this.poison(error ?? new Error("A component resource destructor ended rejected"));
165
+ nested.exited();
166
+ return;
167
+ }
168
+ if (this.#destructorTasks.delete(id)) {
169
+ if (rejected || error !== undefined)
170
+ this.poison(error ?? new Error("A component resource destructor ended rejected"));
171
+ if (!this.#destructorTasks.size) this.#destructorExited?.();
172
+ return;
173
+ }
174
+ const callback = this.#tasks.get(id);
175
+ if (!callback) return;
176
+ // A rejected task left guest state the guest never observed: the instance cannot be reused.
177
+ if (rejected || error !== undefined)
178
+ this.poison(error ?? new Error("A component callback task ended rejected"));
179
+ callback.exited();
180
+ },
181
+ trapped: (error) => this.poison(error),
182
+ };
183
+ #closed = false;
184
+ #poisoned = false;
185
+ readonly #retired = new AbortController();
186
+ /** Why the instance was quarantined, kept for the refusal of later entries. */
187
+ #cause: unknown;
188
+ /** Whether the instrumented glue attached its task accessor during instantiation. */
189
+ get attached(): boolean {
190
+ return this.#access !== undefined;
191
+ }
192
+ /** Every provider operation of this revision, settled before providers are disposed. */
193
+ readonly #physical = new Set<Promise<unknown>>();
194
+
195
+ /** Services of the WASI adapters bound to this instance. */
196
+ readonly wasi: WasiHost = {
197
+ physical: <T>(operation: () => Promise<T>): Promise<T> => {
198
+ if (this.#retired.signal.aborted)
199
+ return Promise.reject(new Error("The revision has retired"));
200
+ const work = Promise.resolve().then(operation);
201
+ this.#track(work);
202
+ const callback = this.#attributed();
203
+ if (!callback) {
204
+ this.#destructorPhysical(work);
205
+ return abortable(work, this.#retired.signal);
206
+ }
207
+ this.physical(callback, work);
208
+ return abortable(abortable(work, callback.ended.signal), callback.scope.signal);
209
+ },
210
+ cleanup: (operation: () => unknown): void => {
211
+ const callback = this.#attributed();
212
+ const work = Promise.resolve().then(operation);
213
+ this.#track(work);
214
+ if (callback) this.physical(callback, work);
215
+ else this.#destructorPhysical(work);
216
+ // A destructor has no result lane. Its failure must not disappear after a successful
217
+ // export result, or let the next callback reuse an incompletely closed resource.
218
+ work.catch((error: unknown) => this.poison(error));
219
+ },
220
+ retired: this.#retired.signal,
221
+ signal: (): AbortSignal => {
222
+ const callback = this.#attributed();
223
+ const signals = [this.#retired.signal];
224
+ if (callback) {
225
+ signals.push(callback.ended.signal);
226
+ if (callback.scope.signal) signals.push(callback.scope.signal);
227
+ }
228
+ return AbortSignal.any(signals);
229
+ },
230
+ };
231
+
232
+ #track(work: Promise<unknown>): void {
233
+ this.#physical.add(work);
234
+ const forget = () => this.#physical.delete(work);
235
+ work.then(forget, forget);
236
+ }
237
+
238
+ #destructorPhysical(work: Promise<unknown>): void {
239
+ const id = this.#access?.currentRootTask();
240
+ if (id === null || id === undefined) return;
241
+ const nested = this.#nestedDestructors.get(id);
242
+ if (nested) {
243
+ this.physical(nested.callback, work);
244
+ return;
245
+ }
246
+ if (!this.#destructorTasks.has(id)) return;
247
+ this.#destructorPending.add(work);
248
+ const forget = () => this.#destructorPending.delete(work);
249
+ work.then(forget, forget);
250
+ }
251
+
252
+ /** Shared fuel and page budget of the instance, set at instantiation. */
253
+ limits: CoreLimits | undefined;
254
+
255
+ constructor(
256
+ readonly timeout: number,
257
+ readonly dispose: () => Promise<void>,
258
+ /** Fuel shared by a physically overlapping callback group; continuations never refill it. */
259
+ readonly callFuel: bigint = 100_000_000n,
260
+ ) {
261
+ this.#trap = new Promise<never>((_, reject) => (this.#rejectTrap = reject));
262
+ this.#trap.catch(() => {});
263
+ }
264
+
265
+ /**
266
+ * The callback a host import serves: the admitted callback owning the guest's current root
267
+ * export task (read synchronously at import entry), or the active callback for host-side work
268
+ * outside guest code. There is none between callbacks.
269
+ */
270
+ current(): Callback {
271
+ const id = this.#access?.currentRootTask();
272
+ if (id !== null && id !== undefined) {
273
+ if (this.#destructorTasks.has(id) || this.#nestedDestructors.has(id))
274
+ throw new Error("A resource destructor holds no call authority");
275
+ const owner = this.#tasks.get(id);
276
+ if (!owner) throw new Error("Host import from a task outside any admitted callback");
277
+ return owner;
278
+ }
279
+ if (this.#destroying) throw new Error("A resource destructor holds no call authority");
280
+ const active = this.#active;
281
+ if (!active) throw new Error("No active host scope");
282
+ return active;
283
+ }
284
+
285
+ #attributed(): Callback | undefined {
286
+ try {
287
+ return this.current();
288
+ } catch {
289
+ return undefined;
290
+ }
291
+ }
292
+
293
+ /** Queue revision-owned destruction; it must never wait on the callback holding its gate. */
294
+ cleanup(operation: () => Promise<void>): Promise<void> {
295
+ const work = Promise.resolve().then(operation);
296
+ this.#track(work);
297
+ work.catch((error: unknown) => this.poison(error));
298
+ return work;
299
+ }
300
+
301
+ /** Run a guest destructor without borrowing the active callback's authority. */
302
+ async destroy(call: () => void): Promise<void> {
303
+ if (!this.usable) return;
304
+ if (this.#destroying) throw new Error("A resource destructor is already active");
305
+ this.#destroying = true;
306
+ const exited = Promise.withResolvers<void>();
307
+ this.#destructorExited = exited.resolve;
308
+ const expired = () => new Error("Resource destructor exceeded its wall time limit");
309
+ const started = performance.now();
310
+ let timer: ReturnType<typeof setTimeout> | undefined;
311
+ const deadline = new Promise<never>((_, reject) => {
312
+ timer = setTimeout(() => reject(expired()), this.timeout);
313
+ });
314
+ const physical = (async () => {
315
+ await exited.promise;
316
+ while (this.#destructorPending.size) await Promise.allSettled([...this.#destructorPending]);
317
+ })();
318
+ let failure: { error: unknown } | undefined;
319
+ try {
320
+ if (this.limits && !this.#callbacks.size) this.limits.fuel.value = this.callFuel;
321
+ call();
322
+ if (!this.#destructorTasks.size) exited.resolve();
323
+ // Instrumentation reports the exact task exit through its exit promise. Even a
324
+ // synchronous canonical destructor delivers that notification asynchronously.
325
+ await Promise.race([physical, deadline, this.#trap]);
326
+ // An end after the deadline is a timeout too: a thread held past it runs the timer late.
327
+ if (performance.now() - started > this.timeout) throw expired();
328
+ if (this.#poisoned) throw this.#cause ?? new Error("A resource destructor trapped");
329
+ } catch (error) {
330
+ this.poison(error);
331
+ failure = { error };
332
+ } finally {
333
+ clearTimeout(timer);
334
+ if (!this.#destructorTasks.size) exited.resolve();
335
+ // A timeout poisons immediately, but a resource's cleanup and anchor remain retained
336
+ // until its actual destructor task and the provider work it started have ended.
337
+ await physical;
338
+ this.#destructorTasks.clear();
339
+ this.#destructorExited = undefined;
340
+ this.#destroying = false;
341
+ }
342
+ if (failure) throw failure.error;
343
+ }
344
+
345
+ /** Race a waiter against the quarantine signal. */
346
+ guard<T>(operation: Promise<T>): Promise<T> {
347
+ return Promise.race([operation, this.#trap]);
348
+ }
349
+
350
+ /** Account one physical host operation to its callback until it settles. */
351
+ physical<T>(callback: Callback, operation: Promise<T>): Promise<T> {
352
+ callback.pending.add(operation);
353
+ const forget = () => callback.pending.delete(operation);
354
+ operation.then(forget, forget);
355
+ return operation;
356
+ }
357
+
358
+ /** Whether the instance can still be entered. */
359
+ get usable(): boolean {
360
+ return !this.#closed && !this.#poisoned;
361
+ }
362
+
363
+ /** The refusal of an entry into this quarantined instance, naming its trap. */
364
+ #quarantined(): TembraError {
365
+ return new TembraError(Errors.Unavailable.WasmExecutorQuarantined, trapMessage(this.#cause), {
366
+ cause: this.#cause,
367
+ });
368
+ }
369
+
370
+ /** Mark the instance unusable after a trap observed outside `run`. */
371
+ poison(cause?: unknown): void {
372
+ if (!this.#poisoned) {
373
+ // Waiters see the actual trap; later entries are refused as quarantined, naming the same
374
+ // trap, which a trap without a cause names alike for both.
375
+ const trap = cause ?? new Error("the component trapped");
376
+ this.#rejectTrap(trap);
377
+ this.#cause = trap;
378
+ }
379
+ this.#poisoned = true;
380
+ this.#retired.abort();
381
+ }
382
+
383
+ /**
384
+ * Serve one callback through its bounded outcome, joining actual completion on success.
385
+ * Register physical retention before waiting: a failure can answer promptly while its task
386
+ * and providers are still physically owned by the invocation.
387
+ */
388
+ async run<T>(
389
+ environment: bigint,
390
+ scope: CallbackScope,
391
+ call: () => T | Promise<T>,
392
+ retain?: (physical: Promise<void>) => void,
393
+ ): Promise<T> {
394
+ const { result, finished, physical } = this.start(environment, scope, call);
395
+ retain?.(physical);
396
+ const value = await result;
397
+ await finished;
398
+ await physical;
399
+ return value;
400
+ }
401
+
402
+ /**
403
+ * Enter one admitted callback. `result` settles with the export's value (an incoming HTTP
404
+ * response head can be used while its body still streams). `finished` is the bounded callback
405
+ * outcome; `physical` proves actual task exit and settlement of its host work, even if a
406
+ * timeout or trap already rejected `finished`. Retention uses `physical`, never the deadline.
407
+ * One deadline governs the whole lifetime: on expiry the instance is quarantined, the callback's
408
+ * authority and waits are revoked, and provider work still running stays owned by the revision
409
+ * until its disposal. `call` must turn recoverable WIT `result` errors into values; anything it
410
+ * throws is a trap. After a successful checked stream head, `park()` releases the exclusive
411
+ * entry slot while preserving this callback's physical lifetime and deadline. Overlapping
412
+ * callbacks and destructors share the group's original fuel until every callback has ended.
413
+ */
414
+ start<T>(
415
+ environment: bigint,
416
+ scope: CallbackScope,
417
+ call: () => T | Promise<T>,
418
+ ): { result: Promise<T>; finished: Promise<void>; physical: Promise<void>; park(): void } {
419
+ if (this.#poisoned) throw this.#quarantined();
420
+ if (this.#closed || this.#active || this.#destroying)
421
+ throw new TembraError(Errors.Unavailable.WasmExecutor, "Component is closed or busy");
422
+ if (!this.exports)
423
+ throw new TembraError(Errors.Unavailable.WasmExecutor, "Component is not instantiated");
424
+ const newGroup = this.#callbacks.size === 0;
425
+ let exited!: () => void;
426
+ const exit = new Promise<void>((resolve) => (exited = resolve));
427
+ const callback: Callback = {
428
+ scope,
429
+ environment,
430
+ pending: new Set(),
431
+ ended: new AbortController(),
432
+ task: undefined,
433
+ exit,
434
+ exited,
435
+ };
436
+ this.#callbacks.add(callback);
437
+ this.#active = callback;
438
+ // The one timeout of this callback, which poisons the port when it first happens.
439
+ let timeout: Error | undefined;
440
+ const expired = () => {
441
+ if (!timeout) {
442
+ timeout = fault(new Error("Component callback exceeded its wall time limit"));
443
+ this.poison(timeout);
444
+ }
445
+ return timeout;
446
+ };
447
+ const started = performance.now();
448
+ let timer: ReturnType<typeof setTimeout> | undefined;
449
+ const deadline = new Promise<never>((_, reject) => {
450
+ timer = setTimeout(() => reject(expired()), this.timeout);
451
+ });
452
+ deadline.catch(() => {});
453
+ // An outcome after the deadline, a result or a rejection, is a timeout too: a thread held
454
+ // past it runs the timer late, and the race still takes an outcome that is ready by then.
455
+ const bounded = async <V>(operation: Promise<V>) => {
456
+ let outcome: { value: V } | { error: unknown };
457
+ try {
458
+ outcome = { value: await Promise.race([operation, deadline, this.#trap]) };
459
+ } catch (error) {
460
+ outcome = { error };
461
+ }
462
+ if (performance.now() - started > this.timeout) throw expired();
463
+ if ("error" in outcome) throw outcome.error;
464
+ return outcome.value;
465
+ };
466
+ let ended = false;
467
+ const revoke = () => {
468
+ if (ended) return;
469
+ ended = true;
470
+ clearTimeout(timer);
471
+ // Revoke the callback's authority: its waits and later host requests are refused.
472
+ scope.cancel();
473
+ callback.ended.abort();
474
+ if (this.#active === callback) this.#active = undefined;
475
+ };
476
+ const release = () => {
477
+ if (callback.task !== undefined) this.#tasks.delete(callback.task);
478
+ this.#callbacks.delete(callback);
479
+ };
480
+ let pending: Promise<T>;
481
+ try {
482
+ scope.check();
483
+ if (this.limits && newGroup) this.limits.fuel.value = this.callFuel;
484
+ // The export task starts synchronously inside the generated wrapper and binds here.
485
+ this.#admitting = callback;
486
+ this.#admitted = true;
487
+ try {
488
+ pending = Promise.resolve(call());
489
+ } finally {
490
+ this.#admitting = undefined;
491
+ }
492
+ } catch (error) {
493
+ pending = Promise.reject(error);
494
+ }
495
+ if (callback.task === undefined) {
496
+ // The guest was never entered (a host-side refusal): nothing to quarantine.
497
+ const result = (async () => {
498
+ try {
499
+ await pending;
500
+ } finally {
501
+ revoke();
502
+ release();
503
+ }
504
+ const error = new TembraError(
505
+ Errors.Unavailable.WasmExecutor,
506
+ "No generated export task was observed for this callback",
507
+ );
508
+ this.poison(error);
509
+ throw error;
510
+ })();
511
+ const finished = result.then(() => undefined);
512
+ this.#completion(finished);
513
+ return {
514
+ result,
515
+ finished,
516
+ physical: finished,
517
+ park() {
518
+ throw new Error("No successful component result to park");
519
+ },
520
+ };
521
+ }
522
+ let published = false;
523
+ const result = bounded(pending).then(
524
+ (value) => {
525
+ published = true;
526
+ return value;
527
+ },
528
+ (error: unknown) => {
529
+ this.poison(error);
530
+ throw fault(error);
531
+ },
532
+ );
533
+ const finished = (async () => {
534
+ try {
535
+ await result.catch(() => undefined);
536
+ // A result is not physical completion: admission and attribution stay with this
537
+ // callback until its task really exits and its host operations settled.
538
+ await bounded(callback.exit);
539
+ while (callback.pending.size) await bounded(Promise.allSettled([...callback.pending]));
540
+ } catch (error) {
541
+ this.poison(error);
542
+ throw fault(error);
543
+ } finally {
544
+ revoke();
545
+ }
546
+ if (this.#poisoned) throw this.#quarantined();
547
+ })();
548
+ result.catch(() => undefined);
549
+ finished.catch(() => undefined);
550
+ const physical = (async () => {
551
+ try {
552
+ // Quarantine revokes waiters promptly; it is not evidence that a suspended stack or
553
+ // its providers exited. Retain task identity and its kernel owner until both did.
554
+ await pending.catch(() => undefined);
555
+ await callback.exit;
556
+ while (callback.pending.size) await Promise.allSettled([...callback.pending]);
557
+ await finished;
558
+ } finally {
559
+ release();
560
+ }
561
+ })();
562
+ physical.catch(() => undefined);
563
+ this.#completion(physical);
564
+ return {
565
+ result,
566
+ finished,
567
+ physical,
568
+ park: () => {
569
+ if (!published) throw new Error("No successful component result to park");
570
+ if (this.#active === callback) this.#active = undefined;
571
+ },
572
+ };
573
+ }
574
+
575
+ #completion(work: Promise<void>): void {
576
+ this.#completions.add(work);
577
+ const forget = () => this.#completions.delete(work);
578
+ work.then(forget, forget);
579
+ }
580
+
581
+ /** Join physical provider work and resource destruction without retiring the instance. */
582
+ async settled(): Promise<void> {
583
+ while (this.#completions.size || this.#physical.size)
584
+ await Promise.allSettled([...this.#completions, ...this.#physical]);
585
+ }
586
+
587
+ /** Dispose providers only after the last callback physically returned. */
588
+ async close(): Promise<void> {
589
+ if (this.#callbacks.size || this.#destroying) throw new Error("Guest still owns physical work");
590
+ if (this.#closed) return;
591
+ this.#closed = true;
592
+ this.exports = undefined;
593
+ this.#retired.abort();
594
+ // Providers are disposed only after their last physical operation settled.
595
+ while (this.#physical.size) await Promise.allSettled([...this.#physical]);
596
+ await this.dispose();
597
+ }
598
+ }