@statewalker/webrun-http-browser 0.6.5 → 0.7.1
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 +302 -52
- package/dist/core/data-calls.d.ts +17 -0
- package/dist/core/data-calls.d.ts.map +1 -1
- package/dist/core/service-worker-control.d.ts +3 -1
- package/dist/core/service-worker-control.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4218 -301
- package/dist/link/async-dispose.d.ts +10 -0
- package/dist/link/async-dispose.d.ts.map +1 -0
- package/dist/link/errors.d.ts +2 -0
- package/dist/link/errors.d.ts.map +1 -0
- package/dist/link/http-link.d.ts +72 -0
- package/dist/link/http-link.d.ts.map +1 -0
- package/dist/link/index.d.ts +4 -0
- package/dist/link/index.d.ts.map +1 -0
- package/dist/link/locks.d.ts +39 -0
- package/dist/link/locks.d.ts.map +1 -0
- package/dist/link/rendezvous.d.ts +21 -0
- package/dist/link/rendezvous.d.ts.map +1 -0
- package/dist/relay/index-sw.d.ts +12 -2
- package/dist/relay/index-sw.d.ts.map +1 -1
- package/dist/relay/index.d.ts +66 -8
- package/dist/relay/index.d.ts.map +1 -1
- package/dist/relay-sw.js +1328 -64
- package/dist/relay-worker.js +1329 -64
- package/dist/sw/handler-endpoint.d.ts +81 -0
- package/dist/sw/handler-endpoint.d.ts.map +1 -0
- package/dist/sw/handler-table.d.ts +53 -0
- package/dist/sw/handler-table.d.ts.map +1 -0
- package/dist/sw/http-sw-dispatcher.d.ts +162 -21
- package/dist/sw/http-sw-dispatcher.d.ts.map +1 -1
- package/dist/sw/index.d.ts +5 -0
- package/dist/sw/index.d.ts.map +1 -1
- package/dist/sw/protocol.d.ts +115 -0
- package/dist/sw/protocol.d.ts.map +1 -0
- package/dist/sw/sw-dispatcher.d.ts.map +1 -1
- package/dist/sw/sw-http-adapter.d.ts +199 -0
- package/dist/sw/sw-http-adapter.d.ts.map +1 -0
- package/dist/sw/sw-websocket.d.ts +16 -0
- package/dist/sw/sw-websocket.d.ts.map +1 -0
- package/dist/sw/worker-service.d.ts +45 -0
- package/dist/sw/worker-service.d.ts.map +1 -0
- package/dist/sw/worker-url.d.ts +9 -0
- package/dist/sw/worker-url.d.ts.map +1 -0
- package/dist/sw-worker.js +2403 -265
- package/dist/sw.d.ts +2 -0
- package/dist/sw.d.ts.map +1 -1
- package/dist/sw.js +4189 -546
- package/dist/worker.d.ts +10 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +3780 -0
- package/dist/ws/client.d.ts +73 -0
- package/dist/ws/client.d.ts.map +1 -0
- package/dist/ws/frames.d.ts +68 -0
- package/dist/ws/frames.d.ts.map +1 -0
- package/dist/ws/index.d.ts +6 -0
- package/dist/ws/index.d.ts.map +1 -0
- package/dist/ws/server.d.ts +53 -0
- package/dist/ws/server.d.ts.map +1 -0
- package/dist/ws/socket-core.d.ts +91 -0
- package/dist/ws/socket-core.d.ts.map +1 -0
- package/dist/ws/upgrade.d.ts +93 -0
- package/dist/ws/upgrade.d.ts.map +1 -0
- package/package.json +10 -5
- package/src/core/data-calls.ts +52 -2
- package/src/core/service-worker-control.ts +7 -1
- package/src/index.ts +3 -0
- package/src/link/async-dispose.ts +22 -0
- package/src/link/errors.ts +3 -0
- package/src/link/http-link.ts +238 -0
- package/src/link/index.ts +3 -0
- package/src/link/locks.ts +97 -0
- package/src/link/rendezvous.ts +60 -0
- package/src/relay/index-sw.ts +84 -12
- package/src/relay/index.ts +203 -27
- package/src/sw/handler-endpoint.ts +278 -0
- package/src/sw/handler-table.ts +130 -0
- package/src/sw/http-sw-dispatcher.ts +649 -90
- package/src/sw/index.ts +5 -0
- package/src/sw/protocol.ts +103 -0
- package/src/sw/sw-dispatcher.ts +1 -20
- package/src/sw/sw-http-adapter.ts +613 -0
- package/src/sw/sw-websocket.ts +43 -0
- package/src/sw/worker-service.ts +133 -0
- package/src/sw/worker-url.ts +19 -0
- package/src/sw-worker.ts +8 -3
- package/src/sw.ts +2 -0
- package/src/worker.ts +9 -0
- package/src/ws/client.ts +346 -0
- package/src/ws/frames.ts +119 -0
- package/src/ws/index.ts +11 -0
- package/src/ws/server.ts +132 -0
- package/src/ws/socket-core.ts +251 -0
- package/src/ws/upgrade.ts +200 -0
package/dist/sw-worker.js
CHANGED
|
@@ -1,4 +1,55 @@
|
|
|
1
1
|
(function() {
|
|
2
|
+
//#region ../../node_modules/.pnpm/idb-keyval@6.3.0/node_modules/idb-keyval/dist/index.js
|
|
3
|
+
function promisifyRequest(request) {
|
|
4
|
+
return new Promise((resolve, reject) => {
|
|
5
|
+
request.oncomplete = request.onsuccess = () => resolve(request.result);
|
|
6
|
+
request.onabort = request.onerror = () => reject(request.error);
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
function createStore(dbName, storeName) {
|
|
10
|
+
let dbp;
|
|
11
|
+
const getDB = () => {
|
|
12
|
+
if (dbp) return dbp;
|
|
13
|
+
const request = indexedDB.open(dbName);
|
|
14
|
+
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
|
|
15
|
+
dbp = promisifyRequest(request);
|
|
16
|
+
dbp.then((db) => {
|
|
17
|
+
db.onclose = () => dbp = void 0;
|
|
18
|
+
}, () => {
|
|
19
|
+
dbp = void 0;
|
|
20
|
+
});
|
|
21
|
+
return dbp;
|
|
22
|
+
};
|
|
23
|
+
return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
|
|
24
|
+
}
|
|
25
|
+
let defaultGetStoreFunc;
|
|
26
|
+
function defaultGetStore() {
|
|
27
|
+
if (!defaultGetStoreFunc) defaultGetStoreFunc = createStore("keyval-store", "keyval");
|
|
28
|
+
return defaultGetStoreFunc;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Get a value by its key.
|
|
32
|
+
*
|
|
33
|
+
* @param key
|
|
34
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
35
|
+
*/
|
|
36
|
+
function get(key, customStore = defaultGetStore()) {
|
|
37
|
+
return customStore("readonly", (store) => promisifyRequest(store.get(key)));
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Set a value with a key.
|
|
41
|
+
*
|
|
42
|
+
* @param key
|
|
43
|
+
* @param value
|
|
44
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
45
|
+
*/
|
|
46
|
+
function set(key, value, customStore = defaultGetStore()) {
|
|
47
|
+
return customStore("readwrite", (store) => {
|
|
48
|
+
store.put(value, key);
|
|
49
|
+
return promisifyRequest(store.transaction);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
2
53
|
//#region ../webrun-streams/dist/index.js
|
|
3
54
|
function serializeError(error) {
|
|
4
55
|
if (error instanceof Error) {
|
|
@@ -23,8 +74,6 @@
|
|
|
23
74
|
const payload = typeof error === "string" ? { message: error } : error;
|
|
24
75
|
return Object.assign(new Error(payload.message), payload);
|
|
25
76
|
}
|
|
26
|
-
new TextEncoder();
|
|
27
|
-
new TextDecoder();
|
|
28
77
|
/**
|
|
29
78
|
* The newAsyncGenerator function creates async generators from callback-based initialization
|
|
30
79
|
* functions, providing a bridge between imperative event handling and declarative async
|
|
@@ -177,7 +226,6 @@
|
|
|
177
226
|
drainQueue();
|
|
178
227
|
}
|
|
179
228
|
}
|
|
180
|
-
new TextEncoder();
|
|
181
229
|
/**
|
|
182
230
|
* The iterator ↔ `ReadableStream` boundary.
|
|
183
231
|
*
|
|
@@ -282,6 +330,110 @@
|
|
|
282
330
|
});
|
|
283
331
|
}
|
|
284
332
|
}
|
|
333
|
+
const DEFAULT_CHUNK_SIZE = 16384;
|
|
334
|
+
/**
|
|
335
|
+
* Curried `Duplex`-shaped transformer that splits incoming `Uint8Array`s into
|
|
336
|
+
* chunks no larger than `size` bytes. Empty input chunks are skipped; small
|
|
337
|
+
* input chunks pass through unchanged (zero-copy `subarray` views are used
|
|
338
|
+
* when splitting, so no allocation per chunk).
|
|
339
|
+
*
|
|
340
|
+
* Use to respect transport MTUs before reaching `channel.send`. Reassembly on
|
|
341
|
+
* the receive side is not needed — consumers iterate a continuous byte stream.
|
|
342
|
+
*/
|
|
343
|
+
function toChunks(size = DEFAULT_CHUNK_SIZE) {
|
|
344
|
+
if (!(Number.isInteger(size) && size > 0)) throw new RangeError(`toChunks: size must be a positive integer, got ${size}`);
|
|
345
|
+
return async function* (input) {
|
|
346
|
+
for await (const block of input) {
|
|
347
|
+
if (block.byteLength === 0) continue;
|
|
348
|
+
if (block.byteLength <= size) {
|
|
349
|
+
yield block;
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
let offset = 0;
|
|
353
|
+
while (offset < block.byteLength) {
|
|
354
|
+
const end = Math.min(offset + size, block.byteLength);
|
|
355
|
+
yield block.subarray(offset, end);
|
|
356
|
+
offset = end;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
//#endregion
|
|
362
|
+
//#region src/core/data-calls.ts
|
|
363
|
+
const TRANSFER = Symbol.for("webrun-http-browser:transfer");
|
|
364
|
+
/**
|
|
365
|
+
* A channel call's result that carries transferables, a `MessagePort` say:
|
|
366
|
+
* return `withTransfer({ port }, [port])` from a `handleChannelCalls` handler
|
|
367
|
+
* and `callChannel` resolves with `{ port }`.
|
|
368
|
+
*/
|
|
369
|
+
function withTransfer(value, transfer) {
|
|
370
|
+
return {
|
|
371
|
+
[TRANSFER]: true,
|
|
372
|
+
value,
|
|
373
|
+
transfer
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function isTransferResult(value) {
|
|
377
|
+
return typeof value === "object" && value !== null && TRANSFER in value;
|
|
378
|
+
}
|
|
379
|
+
/** Splits a handler's result into the value to post and its transfer list. */
|
|
380
|
+
function unwrapTransfer(result) {
|
|
381
|
+
return isTransferResult(result) ? {
|
|
382
|
+
value: result.value,
|
|
383
|
+
transfer: result.transfer
|
|
384
|
+
} : {
|
|
385
|
+
value: result,
|
|
386
|
+
transfer: []
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
function callChannel(target, callType, params, ...transfers) {
|
|
390
|
+
return new Promise((resolve, reject) => {
|
|
391
|
+
const channel = new MessageChannel();
|
|
392
|
+
channel.port1.onmessage = (ev) => {
|
|
393
|
+
const { result, error } = ev.data;
|
|
394
|
+
if (error) reject(deserializeError(error));
|
|
395
|
+
else resolve(result);
|
|
396
|
+
};
|
|
397
|
+
target.postMessage({
|
|
398
|
+
type: callType,
|
|
399
|
+
params
|
|
400
|
+
}, [channel.port2, ...transfers]);
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
function handleChannelCalls(target, callType, handler) {
|
|
404
|
+
const listener = async (event) => {
|
|
405
|
+
if (!event.data || event.data.type !== callType) return;
|
|
406
|
+
const [port, ...transfers] = event.ports ?? [];
|
|
407
|
+
const response = {};
|
|
408
|
+
let transfer = [];
|
|
409
|
+
try {
|
|
410
|
+
const result = await handler(event, event.data.params, ...transfers);
|
|
411
|
+
({value: response.result, transfer} = unwrapTransfer(result));
|
|
412
|
+
} catch (error) {
|
|
413
|
+
response.error = serializeError(error);
|
|
414
|
+
}
|
|
415
|
+
port?.postMessage(response, transfer);
|
|
416
|
+
};
|
|
417
|
+
target.addEventListener("message", listener);
|
|
418
|
+
target.start?.();
|
|
419
|
+
return () => target.removeEventListener("message", listener);
|
|
420
|
+
}
|
|
421
|
+
//#endregion
|
|
422
|
+
//#region src/core/service-worker-control.ts
|
|
423
|
+
/** Channel call a page sends to ask its ServiceWorker to `clients.claim()` it. */
|
|
424
|
+
const CLAIM_CALL = "CLAIM";
|
|
425
|
+
/**
|
|
426
|
+
* ServiceWorker side: answers the page's `CLAIM` request with
|
|
427
|
+
* `clients.claim()`, which takes over every uncontrolled client in scope.
|
|
428
|
+
* Returns a function that stops answering.
|
|
429
|
+
*/
|
|
430
|
+
function handleClaimRequests(self) {
|
|
431
|
+
return handleChannelCalls(self, CLAIM_CALL, (event) => {
|
|
432
|
+
const claimed = self.clients.claim().then(() => true);
|
|
433
|
+
event.waitUntil?.(claimed);
|
|
434
|
+
return claimed;
|
|
435
|
+
});
|
|
436
|
+
}
|
|
285
437
|
//#endregion
|
|
286
438
|
//#region ../webrun-http-streams/dist/index.js
|
|
287
439
|
const CR = 13;
|
|
@@ -419,8 +571,8 @@
|
|
|
419
571
|
const NEWLINE = 10;
|
|
420
572
|
/** Mirrors the HTTP/1.1 codec's default `maxHeaderBytes`. */
|
|
421
573
|
const MAX_ENVELOPE_BYTES = 65536;
|
|
422
|
-
const encoder$1 = new TextEncoder();
|
|
423
|
-
const decoder = new TextDecoder();
|
|
574
|
+
const encoder$1 = /* @__PURE__ */ new TextEncoder();
|
|
575
|
+
const decoder = /* @__PURE__ */ new TextDecoder();
|
|
424
576
|
/**
|
|
425
577
|
* Encode an HTTP envelope plus optional body as one continuous byte stream:
|
|
426
578
|
*
|
|
@@ -674,15 +826,15 @@
|
|
|
674
826
|
};
|
|
675
827
|
return { kind: "none" };
|
|
676
828
|
}
|
|
677
|
-
const CRLF = new Uint8Array([13, 10]);
|
|
678
|
-
const LAST_CHUNK = new Uint8Array([
|
|
829
|
+
const CRLF = /* @__PURE__ */ new Uint8Array([13, 10]);
|
|
830
|
+
const LAST_CHUNK = /* @__PURE__ */ new Uint8Array([
|
|
679
831
|
48,
|
|
680
832
|
13,
|
|
681
833
|
10,
|
|
682
834
|
13,
|
|
683
835
|
10
|
|
684
836
|
]);
|
|
685
|
-
const encoder = new TextEncoder();
|
|
837
|
+
const encoder = /* @__PURE__ */ new TextEncoder();
|
|
686
838
|
/**
|
|
687
839
|
* Chunk sizes are written in HEXADECIMAL — a 21-byte chunk is `15`. Writing
|
|
688
840
|
* them in decimal is the defect note 15 found in @libp2p/http, and it is the
|
|
@@ -987,7 +1139,7 @@
|
|
|
987
1139
|
decodeResponse: (input, o) => decodeResponse(input, opts, o.method)
|
|
988
1140
|
};
|
|
989
1141
|
}
|
|
990
|
-
const httpCodec = newHttpCodec();
|
|
1142
|
+
const httpCodec = /* @__PURE__ */ newHttpCodec();
|
|
991
1143
|
/**
|
|
992
1144
|
* Dispatches on byte 0. The formats are self-identifying — a JSON envelope
|
|
993
1145
|
* always begins `{`, which is not a token character and so can never begin an
|
|
@@ -1033,11 +1185,245 @@
|
|
|
1033
1185
|
}
|
|
1034
1186
|
};
|
|
1035
1187
|
}
|
|
1036
|
-
|
|
1188
|
+
/**
|
|
1189
|
+
* Writes HTTP/1.1; accepts HTTP/1.1 or the legacy JSON envelope. Used whenever
|
|
1190
|
+
* no `codec` option is supplied.
|
|
1191
|
+
*/
|
|
1192
|
+
const defaultCodec = /* @__PURE__ */ newSniffingCodec({
|
|
1037
1193
|
write: httpCodec,
|
|
1038
1194
|
accept: [httpCodec, jsonEnvelopeCodec]
|
|
1039
1195
|
});
|
|
1040
1196
|
/**
|
|
1197
|
+
* Makes `target` disposable with `await using`: installs `dispose` as its
|
|
1198
|
+
* `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
|
|
1199
|
+
* iterators lose what a native generator gets from `AsyncIteratorPrototype`;
|
|
1200
|
+
* this gives it back. A no-op where the symbol is missing. Kept off the
|
|
1201
|
+
* declared types, which would require consumers to compile with the
|
|
1202
|
+
* `esnext.disposable` lib.
|
|
1203
|
+
*/
|
|
1204
|
+
function asyncDisposable$2(target, dispose) {
|
|
1205
|
+
const asyncDispose = Symbol.asyncDispose;
|
|
1206
|
+
if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
|
|
1207
|
+
value: async () => {
|
|
1208
|
+
await dispose();
|
|
1209
|
+
},
|
|
1210
|
+
configurable: true,
|
|
1211
|
+
writable: true
|
|
1212
|
+
});
|
|
1213
|
+
return target;
|
|
1214
|
+
}
|
|
1215
|
+
/** Carries the serialized JS error between two webrun peers. */
|
|
1216
|
+
const PEER_ERROR_HEADER = "x-webrun-error";
|
|
1217
|
+
/** Hard cap on the peer-error header (M3): see `encodeErrorResponse`. */
|
|
1218
|
+
const MAX_DETAIL_CHARS = 4096;
|
|
1219
|
+
/**
|
|
1220
|
+
* JSON with every non-printable-ASCII character escaped, so the result is a
|
|
1221
|
+
* legal latin-1 header value whatever the error message contained.
|
|
1222
|
+
*/
|
|
1223
|
+
function asciiJson(value) {
|
|
1224
|
+
return JSON.stringify(value).replace(/[^\x20-\x7E]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Decision 13: a real HTTP peer cannot receive a JavaScript exception, only a
|
|
1228
|
+
* response. So an uncaught handler error becomes a conforming 500 whose body
|
|
1229
|
+
* carries the message, with the serialized error in a namespaced header that
|
|
1230
|
+
* another webrun peer re-throws from.
|
|
1231
|
+
*/
|
|
1232
|
+
function encodeErrorResponse(codec, error, method, status = 500, statusText = "Internal Server Error") {
|
|
1233
|
+
const serialized = serializeError(error);
|
|
1234
|
+
let detail = asciiJson(serialized);
|
|
1235
|
+
if (detail.length > MAX_DETAIL_CHARS) detail = asciiJson({ message: serialized.message });
|
|
1236
|
+
if (detail.length > MAX_DETAIL_CHARS) detail = detail.slice(0, MAX_DETAIL_CHARS);
|
|
1237
|
+
const message = serialized.message ?? statusText;
|
|
1238
|
+
return codec.encodeResponse({
|
|
1239
|
+
status,
|
|
1240
|
+
statusText,
|
|
1241
|
+
headers: [["Content-Type", "text/plain; charset=utf-8"], [PEER_ERROR_HEADER, detail]]
|
|
1242
|
+
}, [new TextEncoder().encode(message)], { method });
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* `output` is the `Duplex` call's own generator — one logical call, per the
|
|
1246
|
+
* `Duplex` contract in `@statewalker/webrun-streams`: "Consumer `.return()`
|
|
1247
|
+
* on the output → producer's `finally` runs." On a mux transport
|
|
1248
|
+
* (`emulateMux`), that `finally` is what frees the stream-table slot; skip it
|
|
1249
|
+
* and every peer-error response leaks one slot, unboundedly, until the mux
|
|
1250
|
+
* itself is exhausted (`maxStreams` reached, every further call rejected).
|
|
1251
|
+
*
|
|
1252
|
+
* Cancelling `output` here — not inside the codec's own decode logic — is
|
|
1253
|
+
* deliberate. `codec.decodeResponse` already pulled from `output` to read the
|
|
1254
|
+
* head before this function runs, so unlike the body case above there's no
|
|
1255
|
+
* suspended-start no-op to worry about. And it's safe specifically *because*
|
|
1256
|
+
* this is the client's own response-only generator: the request was already
|
|
1257
|
+
* fully sent before we got here, so there is nothing left to write on it.
|
|
1258
|
+
* The equivalent is NOT safe inside `src/http1/decode.ts`'s `ByteReader` —
|
|
1259
|
+
* that code also runs when a caller wires `codec.decodeRequest`/
|
|
1260
|
+
* `decodeResponse` directly onto a raw bidirectional socket (see
|
|
1261
|
+
* `tests/http1-node-interop.test.ts`), where the *same* object is read from
|
|
1262
|
+
* and then written back to (a server reads the request, then replies on the
|
|
1263
|
+
* same socket); cancelling the read side there tears down the whole
|
|
1264
|
+
* connection out from under the pending write. That was tried and reverted —
|
|
1265
|
+
* see the Task 11 report for the "socket hang up" failure it caused.
|
|
1266
|
+
*/
|
|
1267
|
+
async function throwIfPeerError(result, output) {
|
|
1268
|
+
const found = result.envelope.headers.find(([k]) => k.toLowerCase() === PEER_ERROR_HEADER);
|
|
1269
|
+
if (!found) return;
|
|
1270
|
+
await discard(result.body);
|
|
1271
|
+
try {
|
|
1272
|
+
await output.return?.(void 0);
|
|
1273
|
+
} catch {}
|
|
1274
|
+
let payload;
|
|
1275
|
+
try {
|
|
1276
|
+
payload = JSON.parse(found[1]);
|
|
1277
|
+
} catch {
|
|
1278
|
+
payload = { message: found[1] };
|
|
1279
|
+
}
|
|
1280
|
+
throw deserializeError(payload);
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Initiate an HTTP call over a `Duplex`. The caller's `call: Duplex` is
|
|
1284
|
+
* obtained from any `webrun-streams-*` adapter's `connect`. Returns the
|
|
1285
|
+
* response envelope and an async iterable over the response body bytes.
|
|
1286
|
+
*
|
|
1287
|
+
* The call is one logical Duplex invocation; multiplexing of concurrent
|
|
1288
|
+
* calls is the adapter's concern (native or `emulateMux`).
|
|
1289
|
+
*/
|
|
1290
|
+
async function httpFetch(call, env, body, options = {}) {
|
|
1291
|
+
const codec = options.codec ?? defaultCodec;
|
|
1292
|
+
const { signal } = options;
|
|
1293
|
+
if (signal?.aborted) throw abortReason$1(signal);
|
|
1294
|
+
const output = call(codec.encodeRequest(env, body));
|
|
1295
|
+
let released;
|
|
1296
|
+
const release = () => {
|
|
1297
|
+
released ??= (async () => {
|
|
1298
|
+
try {
|
|
1299
|
+
await output.return?.(void 0);
|
|
1300
|
+
} catch {}
|
|
1301
|
+
})();
|
|
1302
|
+
return released;
|
|
1303
|
+
};
|
|
1304
|
+
let finished = false;
|
|
1305
|
+
const finish = () => {
|
|
1306
|
+
if (finished || released) return;
|
|
1307
|
+
finished = true;
|
|
1308
|
+
if (signal?.aborted) {
|
|
1309
|
+
release();
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
const onAbort = () => void release();
|
|
1313
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1314
|
+
drain(output).finally(() => signal?.removeEventListener("abort", onAbort));
|
|
1315
|
+
};
|
|
1316
|
+
let decoded;
|
|
1317
|
+
try {
|
|
1318
|
+
decoded = await untilAborted(codec.decodeResponse(output, { method: env.method }), signal);
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
if (signal?.aborted) release();
|
|
1321
|
+
else await release();
|
|
1322
|
+
throw error;
|
|
1323
|
+
}
|
|
1324
|
+
const result = {
|
|
1325
|
+
envelope: decoded.envelope,
|
|
1326
|
+
body: releasingOnExit(decoded.body, finish, release),
|
|
1327
|
+
release,
|
|
1328
|
+
finish
|
|
1329
|
+
};
|
|
1330
|
+
await throwIfPeerError(result, output);
|
|
1331
|
+
return result;
|
|
1332
|
+
}
|
|
1333
|
+
/** `promise`, rejected with the signal's reason if it aborts first. */
|
|
1334
|
+
function untilAborted(promise, signal) {
|
|
1335
|
+
if (!signal) return promise;
|
|
1336
|
+
return new Promise((resolve, reject) => {
|
|
1337
|
+
const onAbort = () => reject(abortReason$1(signal));
|
|
1338
|
+
if (signal.aborted) return onAbort();
|
|
1339
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1340
|
+
promise.then((value) => {
|
|
1341
|
+
signal.removeEventListener("abort", onAbort);
|
|
1342
|
+
resolve(value);
|
|
1343
|
+
}, (error) => {
|
|
1344
|
+
signal.removeEventListener("abort", onAbort);
|
|
1345
|
+
reject(error);
|
|
1346
|
+
});
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
/** The signal's reason as an `Error` (`AbortError` when it gave none). */
|
|
1350
|
+
function abortReason$1(signal) {
|
|
1351
|
+
const reason = signal.reason;
|
|
1352
|
+
if (reason instanceof Error) return reason;
|
|
1353
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
1354
|
+
err.name = "AbortError";
|
|
1355
|
+
return err;
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* `body`, ending the call however it is left: read to its end, or left early.
|
|
1359
|
+
*
|
|
1360
|
+
* The body the codec hands back is a generator of its own over a `ByteReader`,
|
|
1361
|
+
* and its ending never reaches the call's `output` (see `throwIfPeerError` for
|
|
1362
|
+
* why the codec must not do that itself). A caller that stopped reading — an
|
|
1363
|
+
* aborted `fetch`, a cancelled response stream — left the peer's producer
|
|
1364
|
+
* parked forever; and one that read the body to its end left the call itself
|
|
1365
|
+
* open, which on a multiplexed transport is one port per exchange until the
|
|
1366
|
+
* multiplexer refuses to open more (`maxPorts`).
|
|
1367
|
+
*
|
|
1368
|
+
* Left early, the call is abandoned (`.return()`): the peer's producer is
|
|
1369
|
+
* released. Read to its end, the call is not cut short but read to ITS end, in
|
|
1370
|
+
* the background: the peer ends it once its side of the exchange is over,
|
|
1371
|
+
* which may be later than the response — a handler that answered before it
|
|
1372
|
+
* read the request body is still receiving it (`HttpDataHandlerResult.settled`),
|
|
1373
|
+
* and abandoning the call would abort that upload.
|
|
1374
|
+
*/
|
|
1375
|
+
async function* releasingOnExit(body, finish, release) {
|
|
1376
|
+
let completed = false;
|
|
1377
|
+
try {
|
|
1378
|
+
yield* body;
|
|
1379
|
+
completed = true;
|
|
1380
|
+
} finally {
|
|
1381
|
+
if (completed) finish();
|
|
1382
|
+
else await release();
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
/** Reads `output` to its end, discarding what is left, ignoring a failure. */
|
|
1386
|
+
async function drain(output) {
|
|
1387
|
+
try {
|
|
1388
|
+
for (let r = await output.next(); !r.done; r = await output.next());
|
|
1389
|
+
} catch {}
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Wrap an HTTP handler as a `Duplex` so it can be registered with any
|
|
1393
|
+
* `webrun-streams-*` adapter's `serve`.
|
|
1394
|
+
*/
|
|
1395
|
+
function httpServe(handler, options = {}) {
|
|
1396
|
+
const codec = options.codec ?? defaultCodec;
|
|
1397
|
+
return async function* httpHandlerDuplex(input) {
|
|
1398
|
+
let decoded;
|
|
1399
|
+
try {
|
|
1400
|
+
decoded = await codec.decodeRequest(input);
|
|
1401
|
+
} catch (error) {
|
|
1402
|
+
if (!(error instanceof HttpParseError)) throw error;
|
|
1403
|
+
yield* encodeErrorResponse(error.codec ?? codec, error, "GET", 400, "Bad Request");
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
const replyCodec = decoded.codec ?? codec;
|
|
1407
|
+
let result;
|
|
1408
|
+
try {
|
|
1409
|
+
result = await handler(decoded.envelope, decoded.body);
|
|
1410
|
+
} catch (error) {
|
|
1411
|
+
yield* encodeErrorResponse(replyCodec, error, decoded.envelope.method);
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
let completed = false;
|
|
1415
|
+
try {
|
|
1416
|
+
yield* replyCodec.encodeResponse(result.envelope, result.body, { method: decoded.envelope.method });
|
|
1417
|
+
completed = true;
|
|
1418
|
+
await result.settled?.();
|
|
1419
|
+
} finally {
|
|
1420
|
+
if (!completed) try {
|
|
1421
|
+
await result.release?.();
|
|
1422
|
+
} catch {}
|
|
1423
|
+
}
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1041
1427
|
* The one place that knows a runtime may not implement request body streams,
|
|
1042
1428
|
* and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
|
|
1043
1429
|
* carry a client and a server direction that must agree on the answer, so the
|
|
@@ -1080,6 +1466,31 @@
|
|
|
1080
1466
|
function supportsRequestStreams() {
|
|
1081
1467
|
return typeof Request === "function" && Object.getOwnPropertyDescriptor(Request.prototype, "body") != null;
|
|
1082
1468
|
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Drain a body iterable into one contiguous buffer. Only the fallbacks need it.
|
|
1471
|
+
* Allocates its own buffer rather than reusing `bytes.ts`'s `concatChunks`,
|
|
1472
|
+
* which passes a single chunk straight through: that chunk is a view onto the
|
|
1473
|
+
* decoder's own read buffer, and the result here is handed to `new Request` and
|
|
1474
|
+
* outlives the decode. The allocation is also what makes it a
|
|
1475
|
+
* `Uint8Array<ArrayBuffer>`, which `BodyInit` accepts and the looser
|
|
1476
|
+
* `Uint8Array<ArrayBufferLike>` does not.
|
|
1477
|
+
*/
|
|
1478
|
+
async function collectBytes(source) {
|
|
1479
|
+
const parts = [];
|
|
1480
|
+
let total = 0;
|
|
1481
|
+
for await (const chunk of source) {
|
|
1482
|
+
if (chunk.byteLength === 0) continue;
|
|
1483
|
+
parts.push(chunk);
|
|
1484
|
+
total += chunk.byteLength;
|
|
1485
|
+
}
|
|
1486
|
+
const out = new Uint8Array(total);
|
|
1487
|
+
let offset = 0;
|
|
1488
|
+
for (const part of parts) {
|
|
1489
|
+
out.set(part, offset);
|
|
1490
|
+
offset += part.byteLength;
|
|
1491
|
+
}
|
|
1492
|
+
return out;
|
|
1493
|
+
}
|
|
1083
1494
|
const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
|
|
1084
1495
|
101,
|
|
1085
1496
|
103,
|
|
@@ -1142,51 +1553,292 @@
|
|
|
1142
1553
|
return new Response(toReadableStream(result.content[Symbol.asyncIterator]()), responseOptions);
|
|
1143
1554
|
};
|
|
1144
1555
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1556
|
+
/**
|
|
1557
|
+
* Connection-scoped headers. The codec surfaces them verbatim (decision 12),
|
|
1558
|
+
* but they are meaningless to a `Request`/`Response`, and re-emitting them
|
|
1559
|
+
* from a relay would corrupt its framing.
|
|
1560
|
+
*/
|
|
1561
|
+
const HOP_BY_HOP = /* @__PURE__ */ new Set([
|
|
1562
|
+
"connection",
|
|
1563
|
+
"host",
|
|
1564
|
+
"keep-alive",
|
|
1565
|
+
"proxy-authenticate",
|
|
1566
|
+
"proxy-authorization",
|
|
1567
|
+
"te",
|
|
1568
|
+
"trailer",
|
|
1569
|
+
"transfer-encoding",
|
|
1570
|
+
"upgrade"
|
|
1571
|
+
]);
|
|
1572
|
+
function forwardableHeaders(headers) {
|
|
1573
|
+
return headers.filter(([name]) => !HOP_BY_HOP.has(name.toLowerCase()));
|
|
1574
|
+
}
|
|
1575
|
+
function headersToArray(headers) {
|
|
1576
|
+
const out = [];
|
|
1577
|
+
headers.forEach((value, key) => {
|
|
1578
|
+
out.push([key, value]);
|
|
1579
|
+
});
|
|
1580
|
+
return out;
|
|
1581
|
+
}
|
|
1582
|
+
async function* readableToAsyncIterable(stream) {
|
|
1583
|
+
if (!stream) return;
|
|
1584
|
+
const reader = stream.getReader();
|
|
1585
|
+
let consumed = false;
|
|
1586
|
+
try {
|
|
1587
|
+
while (true) {
|
|
1588
|
+
const { done, value } = await reader.read();
|
|
1589
|
+
if (done) {
|
|
1590
|
+
consumed = true;
|
|
1591
|
+
return;
|
|
1592
|
+
}
|
|
1593
|
+
if (value) yield value;
|
|
1177
1594
|
}
|
|
1178
|
-
}
|
|
1179
|
-
|
|
1595
|
+
} finally {
|
|
1596
|
+
if (!consumed) try {
|
|
1597
|
+
await reader.cancel();
|
|
1598
|
+
} catch {}
|
|
1180
1599
|
try {
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1600
|
+
reader.releaseLock();
|
|
1601
|
+
} catch {}
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
function asyncIterableToReadable(iter) {
|
|
1605
|
+
const it = iter[Symbol.asyncIterator]();
|
|
1606
|
+
return new ReadableStream({
|
|
1607
|
+
async pull(controller) {
|
|
1608
|
+
try {
|
|
1609
|
+
const { done, value } = await it.next();
|
|
1610
|
+
if (done) {
|
|
1611
|
+
controller.close();
|
|
1612
|
+
return;
|
|
1613
|
+
}
|
|
1614
|
+
controller.enqueue(value);
|
|
1615
|
+
} catch (err) {
|
|
1616
|
+
controller.error(err);
|
|
1617
|
+
}
|
|
1618
|
+
},
|
|
1619
|
+
async cancel() {
|
|
1620
|
+
await it.return?.();
|
|
1185
1621
|
}
|
|
1622
|
+
});
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Run a `Request` through a `Duplex` call and reconstruct the `Response` on
|
|
1626
|
+
* the other side. The request's `signal` is plumbed into the body iteration —
|
|
1627
|
+
* abort terminates the underlying call.
|
|
1628
|
+
*/
|
|
1629
|
+
async function fetchOverDuplex(call, request, options = {}) {
|
|
1630
|
+
if (request.signal?.aborted) throw abortReason$1(request.signal);
|
|
1631
|
+
const env = {
|
|
1632
|
+
url: request.url,
|
|
1633
|
+
method: request.method,
|
|
1634
|
+
headers: headersToArray(request.headers)
|
|
1186
1635
|
};
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1636
|
+
let body;
|
|
1637
|
+
if (request.body != null) body = readableToAsyncIterable(request.body);
|
|
1638
|
+
else if (!supportsRequestStreams()) {
|
|
1639
|
+
const buffered = new Uint8Array(await request.arrayBuffer());
|
|
1640
|
+
if (buffered.byteLength > 0) body = [buffered];
|
|
1641
|
+
}
|
|
1642
|
+
const { envelope, body: respBody, release, finish } = await httpFetch(call, env, body, {
|
|
1643
|
+
...options,
|
|
1644
|
+
signal: request.signal ?? void 0
|
|
1645
|
+
});
|
|
1646
|
+
const responseInit = {
|
|
1647
|
+
status: envelope.status,
|
|
1648
|
+
statusText: envelope.statusText,
|
|
1649
|
+
headers: forwardableHeaders(envelope.headers)
|
|
1650
|
+
};
|
|
1651
|
+
if (request.method === "HEAD" || request.method === "OPTIONS" || NULL_BODY_STATUSES.has(envelope.status)) {
|
|
1652
|
+
if (finish) finish();
|
|
1653
|
+
else await release?.();
|
|
1654
|
+
return new Response(null, responseInit);
|
|
1655
|
+
}
|
|
1656
|
+
return new Response(asyncIterableToReadable(withAbort(respBody, request.signal)), responseInit);
|
|
1657
|
+
}
|
|
1658
|
+
/**
|
|
1659
|
+
* Wrap a `(Request) => Promise<Response>` handler as a `Duplex` so it can be
|
|
1660
|
+
* registered with any `webrun-streams-*` adapter's `serve`.
|
|
1661
|
+
*/
|
|
1662
|
+
function serveFetchOverDuplex(handler, options = {}) {
|
|
1663
|
+
return httpServe(async (env, body) => {
|
|
1664
|
+
const reqInit = {
|
|
1665
|
+
method: env.method,
|
|
1666
|
+
headers: forwardableHeaders(env.headers)
|
|
1667
|
+
};
|
|
1668
|
+
let upload;
|
|
1669
|
+
if (env.method !== "GET" && env.method !== "HEAD") {
|
|
1670
|
+
if (supportsRequestStreams()) {
|
|
1671
|
+
upload = trackingEnd(body);
|
|
1672
|
+
reqInit.body = asyncIterableToReadable(upload.source);
|
|
1673
|
+
reqInit.duplex = "half";
|
|
1674
|
+
} else reqInit.body = await collectBytes(body);
|
|
1675
|
+
}
|
|
1676
|
+
const request = new Request(env.url, reqInit);
|
|
1677
|
+
const response = await handler(request);
|
|
1678
|
+
const settled = async () => {
|
|
1679
|
+
if (!upload) return;
|
|
1680
|
+
if (!request.bodyUsed && !request.body?.locked) request.body?.cancel().catch(() => {});
|
|
1681
|
+
await upload.settle(options.requestIdleMs ?? 3e4);
|
|
1682
|
+
};
|
|
1683
|
+
const respEnv = {
|
|
1684
|
+
status: response.status,
|
|
1685
|
+
statusText: response.statusText,
|
|
1686
|
+
headers: headersToArray(response.headers)
|
|
1687
|
+
};
|
|
1688
|
+
if (env.method === "HEAD" || env.method === "OPTIONS" || NULL_BODY_STATUSES.has(response.status)) {
|
|
1689
|
+
await response.body?.cancel();
|
|
1690
|
+
return {
|
|
1691
|
+
envelope: respEnv,
|
|
1692
|
+
body: void 0,
|
|
1693
|
+
settled
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
return {
|
|
1697
|
+
envelope: respEnv,
|
|
1698
|
+
body: response.body ? readableToAsyncIterable(response.body) : void 0,
|
|
1699
|
+
release: () => response.body?.cancel(),
|
|
1700
|
+
settled
|
|
1701
|
+
};
|
|
1702
|
+
}, options);
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* `source`, and `settle(idleMs)`: resolves once it is done — read to its end,
|
|
1706
|
+
* failed, or abandoned (`return()` included before the first `next()`, which a
|
|
1707
|
+
* generator's `finally` would not see) — or once nobody has asked it for a
|
|
1708
|
+
* chunk for `idleMs`, in which case it is abandoned: later reads fail.
|
|
1709
|
+
*
|
|
1710
|
+
* Idle counts only while no `next()` is pending: a reader waiting for a slow
|
|
1711
|
+
* sender is still reading.
|
|
1712
|
+
*/
|
|
1713
|
+
function trackingEnd(source) {
|
|
1714
|
+
let end = () => {};
|
|
1715
|
+
let isEnded = false;
|
|
1716
|
+
const ended = new Promise((resolve) => {
|
|
1717
|
+
end = () => {
|
|
1718
|
+
isEnded = true;
|
|
1719
|
+
resolve();
|
|
1720
|
+
};
|
|
1721
|
+
});
|
|
1722
|
+
let abandoned;
|
|
1723
|
+
let pending = 0;
|
|
1724
|
+
let idleSince = Date.now();
|
|
1725
|
+
const it = source[Symbol.asyncIterator]();
|
|
1726
|
+
const abandon = (reason) => {
|
|
1727
|
+
abandoned ??= reason;
|
|
1728
|
+
end();
|
|
1729
|
+
Promise.resolve(it.return?.(void 0)).catch(() => {});
|
|
1730
|
+
};
|
|
1731
|
+
const tracked = {
|
|
1732
|
+
[Symbol.asyncIterator]() {
|
|
1733
|
+
return tracked;
|
|
1734
|
+
},
|
|
1735
|
+
async next() {
|
|
1736
|
+
if (abandoned) throw abandoned;
|
|
1737
|
+
pending++;
|
|
1738
|
+
try {
|
|
1739
|
+
const r = await it.next();
|
|
1740
|
+
if (r.done) end();
|
|
1741
|
+
return r;
|
|
1742
|
+
} catch (error) {
|
|
1743
|
+
end();
|
|
1744
|
+
throw error;
|
|
1745
|
+
} finally {
|
|
1746
|
+
if (--pending === 0) idleSince = Date.now();
|
|
1747
|
+
}
|
|
1748
|
+
},
|
|
1749
|
+
async return(value) {
|
|
1750
|
+
end();
|
|
1751
|
+
try {
|
|
1752
|
+
await it.return?.(value);
|
|
1753
|
+
} catch {}
|
|
1754
|
+
return {
|
|
1755
|
+
done: true,
|
|
1756
|
+
value: void 0
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
};
|
|
1760
|
+
asyncDisposable$2(tracked, () => tracked.return?.() ?? Promise.resolve());
|
|
1761
|
+
const settle = (idleMs) => {
|
|
1762
|
+
if (isEnded || !Number.isFinite(idleMs)) return ended;
|
|
1763
|
+
return new Promise((resolve) => {
|
|
1764
|
+
let timer;
|
|
1765
|
+
const check = () => {
|
|
1766
|
+
if (isEnded) return resolve();
|
|
1767
|
+
const idle = pending === 0 ? Date.now() - idleSince : 0;
|
|
1768
|
+
if (idle >= idleMs) {
|
|
1769
|
+
abandon(/* @__PURE__ */ new Error(`webrun-http-streams: the request body was left unread for ${idleMs} ms after the response; abandoned`));
|
|
1770
|
+
return resolve();
|
|
1771
|
+
}
|
|
1772
|
+
timer = setTimeout(check, Math.max(1, Math.min(idleMs - idle, 1e3)));
|
|
1773
|
+
timer.unref?.();
|
|
1774
|
+
};
|
|
1775
|
+
ended.then(() => {
|
|
1776
|
+
clearTimeout(timer);
|
|
1777
|
+
resolve();
|
|
1778
|
+
});
|
|
1779
|
+
check();
|
|
1780
|
+
});
|
|
1781
|
+
};
|
|
1782
|
+
return {
|
|
1783
|
+
source: tracked,
|
|
1784
|
+
settle
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
async function* withAbort(iter, signal) {
|
|
1788
|
+
if (!signal) {
|
|
1789
|
+
yield* iter;
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
for await (const chunk of iter) {
|
|
1793
|
+
if (signal.aborted) throw abortReason$1(signal);
|
|
1794
|
+
yield chunk;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
//#endregion
|
|
1798
|
+
//#region src/core/data-channels.ts
|
|
1799
|
+
const MESSAGE_TYPE_REQUEST = "REQUEST";
|
|
1800
|
+
const MESSAGE_TYPE_RESPONSE = "RESPONSE";
|
|
1801
|
+
let __invocationCounter = 0;
|
|
1802
|
+
function newInvokationChannel({ port, handler = () => {
|
|
1803
|
+
throw new Error("Handler not implemented");
|
|
1804
|
+
}, onError = console.error, newCallId = () => ++__invocationCounter }) {
|
|
1805
|
+
const requests = {};
|
|
1806
|
+
const listener = async (event) => {
|
|
1807
|
+
const data = event.data ?? {};
|
|
1808
|
+
if (data.type === MESSAGE_TYPE_REQUEST) try {
|
|
1809
|
+
const result = await handler(data.request, ...event.ports);
|
|
1810
|
+
const [response, ...transfers] = Array.isArray(result) ? result : result !== void 0 ? [result] : [];
|
|
1811
|
+
port.postMessage({
|
|
1812
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
1813
|
+
callId: data.callId,
|
|
1814
|
+
response
|
|
1815
|
+
}, transfers);
|
|
1816
|
+
} catch (error) {
|
|
1817
|
+
port.postMessage({
|
|
1818
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
1819
|
+
callId: data.callId,
|
|
1820
|
+
error: serializeError(error)
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
else if (data.type === MESSAGE_TYPE_RESPONSE) {
|
|
1824
|
+
const pending = requests[data.callId];
|
|
1825
|
+
delete requests[data.callId];
|
|
1826
|
+
if (!pending) return;
|
|
1827
|
+
if (data.error) pending.reject(deserializeError(data.error));
|
|
1828
|
+
else pending.resolve(data.response);
|
|
1829
|
+
}
|
|
1830
|
+
};
|
|
1831
|
+
const start = async () => {
|
|
1832
|
+
try {
|
|
1833
|
+
port.addEventListener("message", listener);
|
|
1834
|
+
await port.start?.();
|
|
1835
|
+
} catch (e) {
|
|
1836
|
+
onError(e);
|
|
1837
|
+
}
|
|
1838
|
+
};
|
|
1839
|
+
const close = async () => {
|
|
1840
|
+
try {
|
|
1841
|
+
port.removeEventListener("message", listener);
|
|
1190
1842
|
await port.close?.();
|
|
1191
1843
|
} catch (e) {
|
|
1192
1844
|
onError(e);
|
|
@@ -1341,266 +1993,1751 @@
|
|
|
1341
1993
|
})(request);
|
|
1342
1994
|
}
|
|
1343
1995
|
//#endregion
|
|
1344
|
-
//#region
|
|
1345
|
-
function
|
|
1346
|
-
return
|
|
1347
|
-
|
|
1348
|
-
|
|
1996
|
+
//#region src/link/errors.ts
|
|
1997
|
+
function errorMessage(error) {
|
|
1998
|
+
return error instanceof Error ? error.message : String(error);
|
|
1999
|
+
}
|
|
2000
|
+
//#endregion
|
|
2001
|
+
//#region ../webrun-rpc/dist/index.js
|
|
2002
|
+
const closeSignals = /* @__PURE__ */ new WeakMap();
|
|
2003
|
+
/**
|
|
2004
|
+
* Internal: register a port's close signal. Called once by `bindBytesToPort`.
|
|
2005
|
+
*
|
|
2006
|
+
* @internal
|
|
2007
|
+
*/
|
|
2008
|
+
function setPortCloseSignal(port, signal) {
|
|
2009
|
+
closeSignals.set(port, signal);
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* Return the AbortSignal that fires when `port`'s transport closes, or
|
|
2013
|
+
* `undefined` if `port` is not transport-backed (e.g., a raw
|
|
2014
|
+
* `MessageChannel().port1`).
|
|
2015
|
+
*/
|
|
2016
|
+
function getPortCloseSignal(port) {
|
|
2017
|
+
return closeSignals.get(port);
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* Pass as `timeout` to install no deadline at all. Used by the stream tier,
|
|
2021
|
+
* where the deadline belongs to the stream rather than to one chunk (spec D8):
|
|
2022
|
+
* a slow consumer is throttled, never failed.
|
|
2023
|
+
*/
|
|
2024
|
+
const NO_TIMEOUT = Number.POSITIVE_INFINITY;
|
|
2025
|
+
/**
|
|
2026
|
+
* Asynchronous request/response over any `MessageTarget`.
|
|
2027
|
+
*
|
|
2028
|
+
* Sends `params` to the peer listening with `listenPort`, waits up to
|
|
2029
|
+
* `timeout` ms for a matching reply, and either resolves with the result or
|
|
2030
|
+
* rejects with the deserialised error.
|
|
2031
|
+
*/
|
|
2032
|
+
function callPort(port, params, { timeout = 1e3, channelName = "", log = () => {}, newCallId = () => `call-${Date.now()}-${String(Math.random()).substring(2)}`, signal } = {}) {
|
|
2033
|
+
const callId = newCallId();
|
|
2034
|
+
log("[callPort]", {
|
|
2035
|
+
channelName,
|
|
2036
|
+
callId,
|
|
2037
|
+
params
|
|
2038
|
+
});
|
|
2039
|
+
const combinedSignal = combineSignals(signal, getPortCloseSignal(port));
|
|
2040
|
+
let timerId;
|
|
2041
|
+
let onMessage;
|
|
2042
|
+
let onAbort;
|
|
2043
|
+
const promise = new Promise((resolve, reject) => {
|
|
2044
|
+
if (combinedSignal?.aborted) {
|
|
2045
|
+
reject(abortReason(combinedSignal));
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
if (Number.isFinite(timeout) && timeout > 0) timerId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Call timeout. CallId: "${callId}".`)), timeout);
|
|
2049
|
+
onMessage = (event) => {
|
|
2050
|
+
const data = event.data;
|
|
2051
|
+
if (!data) return;
|
|
2052
|
+
if (data.channelName !== channelName) return;
|
|
2053
|
+
if (data.callId !== callId) return;
|
|
2054
|
+
if (data.type === "response:error") reject(deserializeError(data.error));
|
|
2055
|
+
else if (data.type === "response:result") resolve(data.result);
|
|
2056
|
+
};
|
|
2057
|
+
port.addEventListener("message", onMessage);
|
|
2058
|
+
if (combinedSignal) {
|
|
2059
|
+
onAbort = () => reject(abortReason(combinedSignal));
|
|
2060
|
+
combinedSignal.addEventListener("abort", onAbort, { once: true });
|
|
2061
|
+
}
|
|
1349
2062
|
});
|
|
2063
|
+
promise.catch(() => {}).finally(() => {
|
|
2064
|
+
if (timerId !== void 0) clearTimeout(timerId);
|
|
2065
|
+
if (onMessage) port.removeEventListener("message", onMessage);
|
|
2066
|
+
if (onAbort && combinedSignal) combinedSignal.removeEventListener("abort", onAbort);
|
|
2067
|
+
});
|
|
2068
|
+
port.postMessage({
|
|
2069
|
+
type: "request",
|
|
2070
|
+
channelName,
|
|
2071
|
+
callId,
|
|
2072
|
+
params
|
|
2073
|
+
});
|
|
2074
|
+
return promise;
|
|
1350
2075
|
}
|
|
1351
|
-
function
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
2076
|
+
function abortReason(signal) {
|
|
2077
|
+
const reason = signal.reason;
|
|
2078
|
+
if (reason instanceof Error) return reason;
|
|
2079
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
2080
|
+
err.name = "AbortError";
|
|
2081
|
+
return err;
|
|
2082
|
+
}
|
|
2083
|
+
function combineSignals(...signals) {
|
|
2084
|
+
const live = signals.filter((s) => s !== void 0);
|
|
2085
|
+
if (live.length === 0) return void 0;
|
|
2086
|
+
if (live.length === 1) return live[0];
|
|
2087
|
+
return AbortSignal.any(live);
|
|
2088
|
+
}
|
|
2089
|
+
/**
|
|
2090
|
+
* Installs `handler` as the server side of a `callPort` / `listenPort`
|
|
2091
|
+
* request/response pair on `port`.
|
|
2092
|
+
*
|
|
2093
|
+
* Returns a cleanup function that removes the listener.
|
|
2094
|
+
*/
|
|
2095
|
+
function listenPort(port, handler, { channelName = "", log = () => {} } = {}) {
|
|
2096
|
+
const onMessage = async (event) => {
|
|
2097
|
+
const data = event.data;
|
|
2098
|
+
if (!data || data.channelName !== channelName || data.type !== "request") return;
|
|
2099
|
+
const { callId, params } = data;
|
|
2100
|
+
log("[listenPort]", {
|
|
2101
|
+
channelName,
|
|
2102
|
+
callId,
|
|
2103
|
+
params
|
|
2104
|
+
});
|
|
2105
|
+
let result;
|
|
2106
|
+
let error;
|
|
2107
|
+
let type;
|
|
2108
|
+
try {
|
|
2109
|
+
result = await handler(params);
|
|
2110
|
+
type = "response:result";
|
|
2111
|
+
} catch (e) {
|
|
2112
|
+
error = serializeError(e);
|
|
2113
|
+
type = "response:error";
|
|
2114
|
+
}
|
|
2115
|
+
port.postMessage({
|
|
2116
|
+
callId,
|
|
2117
|
+
channelName,
|
|
2118
|
+
type,
|
|
2119
|
+
result,
|
|
2120
|
+
error
|
|
1362
2121
|
});
|
|
1363
|
-
return dbp;
|
|
1364
2122
|
};
|
|
1365
|
-
|
|
2123
|
+
port.addEventListener("message", onMessage);
|
|
2124
|
+
return () => port.removeEventListener("message", onMessage);
|
|
1366
2125
|
}
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
2126
|
+
/**
|
|
2127
|
+
* Wraps an async iterable so that an `AbortSignal` firing causes the wrapper
|
|
2128
|
+
* to return cleanly, forwarding `return()` to the underlying iterator so the
|
|
2129
|
+
* producer (e.g., a user-supplied generator) sees its own `finally` blocks
|
|
2130
|
+
* run immediately rather than waiting for the next yield.
|
|
2131
|
+
*/
|
|
2132
|
+
async function* throughAbort(input, signal) {
|
|
2133
|
+
const iter = input[Symbol.asyncIterator] ? input[Symbol.asyncIterator]() : input[Symbol.iterator]();
|
|
2134
|
+
const onAbort = () => {
|
|
2135
|
+
iter.return?.(void 0);
|
|
2136
|
+
};
|
|
2137
|
+
if (signal.aborted) {
|
|
2138
|
+
iter.return?.(void 0);
|
|
2139
|
+
return;
|
|
2140
|
+
}
|
|
2141
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2142
|
+
try {
|
|
2143
|
+
while (true) {
|
|
2144
|
+
const r = await iter.next();
|
|
2145
|
+
if (r.done) return;
|
|
2146
|
+
if (signal.aborted) return;
|
|
2147
|
+
yield r.value;
|
|
2148
|
+
}
|
|
2149
|
+
} finally {
|
|
2150
|
+
signal.removeEventListener("abort", onAbort);
|
|
2151
|
+
}
|
|
1371
2152
|
}
|
|
1372
2153
|
/**
|
|
1373
|
-
*
|
|
2154
|
+
* Makes `target` disposable with `await using`: installs `dispose` as its
|
|
2155
|
+
* `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
|
|
2156
|
+
* iterators lose what a native generator gets from `AsyncIteratorPrototype`;
|
|
2157
|
+
* this gives it back. A no-op where the symbol is missing. Kept off the
|
|
2158
|
+
* declared types, which would require consumers to compile with the
|
|
2159
|
+
* `esnext.disposable` lib.
|
|
2160
|
+
*/
|
|
2161
|
+
function asyncDisposable$1(target, dispose) {
|
|
2162
|
+
const asyncDispose = Symbol.asyncDispose;
|
|
2163
|
+
if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
|
|
2164
|
+
value: async () => {
|
|
2165
|
+
await dispose();
|
|
2166
|
+
},
|
|
2167
|
+
configurable: true,
|
|
2168
|
+
writable: true
|
|
2169
|
+
});
|
|
2170
|
+
return target;
|
|
2171
|
+
}
|
|
2172
|
+
/**
|
|
2173
|
+
* `gen`, except that `return()` and `throw()` take effect at once.
|
|
1374
2174
|
*
|
|
1375
|
-
*
|
|
1376
|
-
*
|
|
2175
|
+
* On an async generator both are queued behind a `next()` that is still
|
|
2176
|
+
* pending: a consumer that gives up on a stream while it waits for the peer's
|
|
2177
|
+
* next chunk — an aborted fetch whose response head has not come, say — cannot
|
|
2178
|
+
* end it until that chunk arrives, which for a peer that never answers is
|
|
2179
|
+
* never. The stream's `finally` (which closes its port and tells the peer)
|
|
2180
|
+
* then never runs, and on a multiplexer the port is kept for good.
|
|
2181
|
+
*
|
|
2182
|
+
* So `abandon` runs first, synchronously: it must make the pending `next()`
|
|
2183
|
+
* settle (abort the stream), which then resolves done, after which the
|
|
2184
|
+
* generator's own `return()` / `throw()` proceeds as usual. On a generator
|
|
2185
|
+
* suspended at a `yield` it is the same ending, a step earlier. `abandon` runs once, whichever comes first.
|
|
1377
2186
|
*/
|
|
1378
|
-
function
|
|
1379
|
-
|
|
2187
|
+
function returningAtOnce(gen, abandon) {
|
|
2188
|
+
let abandoned = false;
|
|
2189
|
+
const giveUp = (reason) => {
|
|
2190
|
+
if (abandoned) return;
|
|
2191
|
+
abandoned = true;
|
|
2192
|
+
abandon(reason);
|
|
2193
|
+
};
|
|
2194
|
+
const wrapped = {
|
|
2195
|
+
next: (...args) => gen.next(...args).catch((error) => {
|
|
2196
|
+
if (abandoned) return {
|
|
2197
|
+
done: true,
|
|
2198
|
+
value: void 0
|
|
2199
|
+
};
|
|
2200
|
+
throw error;
|
|
2201
|
+
}),
|
|
2202
|
+
return(value) {
|
|
2203
|
+
giveUp();
|
|
2204
|
+
return gen.return(value);
|
|
2205
|
+
},
|
|
2206
|
+
throw(error) {
|
|
2207
|
+
giveUp(error);
|
|
2208
|
+
return gen.throw(error);
|
|
2209
|
+
},
|
|
2210
|
+
[Symbol.asyncIterator]() {
|
|
2211
|
+
return wrapped;
|
|
2212
|
+
}
|
|
2213
|
+
};
|
|
2214
|
+
return asyncDisposable$1(wrapped, () => wrapped.return(void 0));
|
|
1380
2215
|
}
|
|
1381
2216
|
/**
|
|
1382
|
-
*
|
|
2217
|
+
* The `type` of the out-of-band notice a side posts when it abandons a stream.
|
|
1383
2218
|
*
|
|
1384
|
-
*
|
|
1385
|
-
*
|
|
1386
|
-
*
|
|
2219
|
+
* Layer 1's `close` is not observable to layer 2 — a closed virtual port drops
|
|
2220
|
+
* its listeners silently and is indistinguishable from a working port nobody
|
|
2221
|
+
* is answering — so the peer would otherwise wait forever. Exported because
|
|
2222
|
+
* tests and adapters assert on it.
|
|
1387
2223
|
*/
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
2224
|
+
const STREAM_ABORT = "webrun-rpc:stream-abort";
|
|
2225
|
+
/** Caller's input travels on this channel; the handler listens on it. */
|
|
2226
|
+
const CHANNEL_IN = "in";
|
|
2227
|
+
/** The handler's output travels on this channel; the caller listens on it. */
|
|
2228
|
+
const CHANNEL_OUT = "out";
|
|
2229
|
+
/**
|
|
2230
|
+
* One port in, one `Duplex` out (spec D9).
|
|
2231
|
+
*
|
|
2232
|
+
* The returned `Duplex` runs a single stream on `port`: the caller's `input`
|
|
2233
|
+
* is sent chunk by chunk with `callPort`, and the handler's output arrives the
|
|
2234
|
+
* same way on the other channel. Within each direction the next chunk is never
|
|
2235
|
+
* sent until the previous one has been delivered *and* pulled past by the
|
|
2236
|
+
* consumer (spec D11) — the reply to a chunk call *is* the confirmation, and
|
|
2237
|
+
* `listenPort` withholds it until then.
|
|
2238
|
+
*
|
|
2239
|
+
* A stream port carries exactly one invocation. To make several calls, open
|
|
2240
|
+
* several ports: `mux.openPort({ kind: "stream" })` per call.
|
|
2241
|
+
*/
|
|
2242
|
+
function duplexOverPort(port, options = {}) {
|
|
2243
|
+
return (input) => runCallerSide(port, input, options);
|
|
1393
2244
|
}
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
2245
|
+
/**
|
|
2246
|
+
* Installs `handler` as the serving side of one stream on `port`. Returns an
|
|
2247
|
+
* idempotent teardown that abandons the stream and notifies the peer.
|
|
2248
|
+
*/
|
|
2249
|
+
function serveDuplexOverPort(port, handler, options = {}) {
|
|
2250
|
+
const controller = new AbortController();
|
|
2251
|
+
const notice = installAbortNotice(port, controller);
|
|
2252
|
+
abortOnPortClose(port, controller);
|
|
2253
|
+
const clock = installStreamTimeout(controller, options.timeout);
|
|
2254
|
+
const inbound = receiveChunks(port, CHANNEL_IN, controller, clock.touch);
|
|
2255
|
+
let output;
|
|
2256
|
+
try {
|
|
2257
|
+
output = handler(inbound.stream);
|
|
2258
|
+
} catch (err) {
|
|
2259
|
+
const pump = sendChunks(port, CHANNEL_OUT, failing(err), options, controller.signal, clock.touch);
|
|
2260
|
+
pump.catch(() => {});
|
|
2261
|
+
disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
|
|
2262
|
+
return teardownOnce(controller, notice, clock, inbound, void 0);
|
|
2263
|
+
}
|
|
2264
|
+
const pump = sendChunks(port, CHANNEL_OUT, output, options, controller.signal, clock.touch);
|
|
2265
|
+
pump.catch(() => {});
|
|
2266
|
+
disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
|
|
2267
|
+
return teardownOnce(controller, notice, clock, inbound, output);
|
|
2268
|
+
}
|
|
2269
|
+
/**
|
|
2270
|
+
* A stream that completes normally has nobody left to call the returned
|
|
2271
|
+
* teardown — the caller only knows the stream ended, not that it must also
|
|
2272
|
+
* dispose the serve-side handle. Without this, the last `touch()`'s timer
|
|
2273
|
+
* stays armed for up to `timeout` ms after real completion, doing nothing
|
|
2274
|
+
* but holding the event loop open.
|
|
2275
|
+
*
|
|
2276
|
+
* Only disarms once BOTH `pump` (our output) and `inboundEnded` (the peer's
|
|
2277
|
+
* declared end of input, or an abort) have settled. Disarming on `pump`
|
|
2278
|
+
* alone is not safe: under half-close the handler can finish producing
|
|
2279
|
+
* output while the caller is still sending input, and a clock stopped then
|
|
2280
|
+
* would leave that still-open half with no deadline at all — worse than the
|
|
2281
|
+
* leak this fixes.
|
|
2282
|
+
*/
|
|
2283
|
+
function disarmClockWhenBothSidesSettle(clock, pump, inboundEnded) {
|
|
2284
|
+
Promise.allSettled([pump, inboundEnded]).then(() => {
|
|
2285
|
+
clock.stop();
|
|
1408
2286
|
});
|
|
1409
2287
|
}
|
|
1410
|
-
function
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
2288
|
+
async function* failing(err) {
|
|
2289
|
+
throw err;
|
|
2290
|
+
}
|
|
2291
|
+
function teardownOnce(controller, notice, clock, inbound, output) {
|
|
2292
|
+
let torn = false;
|
|
2293
|
+
return () => {
|
|
2294
|
+
if (torn) return;
|
|
2295
|
+
torn = true;
|
|
2296
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: stream torn down"));
|
|
2297
|
+
notice.post();
|
|
2298
|
+
notice.stop();
|
|
2299
|
+
clock.stop();
|
|
2300
|
+
inbound.stop();
|
|
2301
|
+
output?.return(void 0).catch(() => {});
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
function runCallerSide(port, input, options) {
|
|
2305
|
+
const controller = new AbortController();
|
|
2306
|
+
const notice = installAbortNotice(port, controller);
|
|
2307
|
+
abortOnPortClose(port, controller);
|
|
2308
|
+
const clock = installStreamTimeout(controller, options.timeout);
|
|
2309
|
+
const inbound = receiveChunks(port, CHANNEL_OUT, controller, clock.touch);
|
|
2310
|
+
const pump = sendChunks(port, CHANNEL_IN, input, options, controller.signal, clock.touch);
|
|
2311
|
+
pump.catch(() => {});
|
|
2312
|
+
return returningAtOnce((async function* () {
|
|
1415
2313
|
try {
|
|
1416
|
-
|
|
1417
|
-
}
|
|
1418
|
-
|
|
2314
|
+
yield* inbound.stream;
|
|
2315
|
+
} finally {
|
|
2316
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
|
|
2317
|
+
notice.post();
|
|
2318
|
+
notice.stop();
|
|
2319
|
+
clock.stop();
|
|
2320
|
+
inbound.stop();
|
|
2321
|
+
await pump.catch(() => {});
|
|
2322
|
+
try {
|
|
2323
|
+
await port.close?.();
|
|
2324
|
+
} catch {}
|
|
1419
2325
|
}
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
target.start?.();
|
|
1424
|
-
return () => target.removeEventListener("message", listener);
|
|
2326
|
+
})(), () => {
|
|
2327
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
|
|
2328
|
+
});
|
|
1425
2329
|
}
|
|
1426
|
-
//#endregion
|
|
1427
|
-
//#region src/core/service-worker-control.ts
|
|
1428
|
-
/** Channel call a page sends to ask its ServiceWorker to `clients.claim()` it. */
|
|
1429
|
-
const CLAIM_CALL = "CLAIM";
|
|
1430
2330
|
/**
|
|
1431
|
-
*
|
|
1432
|
-
* `
|
|
1433
|
-
*
|
|
2331
|
+
* Listens for the peer's abort notice, and can post our own. The notice is a
|
|
2332
|
+
* plain message with no `channelName` and a `type` that is not `"request"`,
|
|
2333
|
+
* so neither `callPort` nor `listenPort` reacts to it, and it carries no
|
|
2334
|
+
* numeric `id`, so `structuredCodec` never mistakes it for a layer 1 envelope.
|
|
1434
2335
|
*/
|
|
1435
|
-
function
|
|
1436
|
-
|
|
1437
|
-
const
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
}
|
|
2336
|
+
function installAbortNotice(port, controller) {
|
|
2337
|
+
const onMessage = (event) => {
|
|
2338
|
+
const data = event.data;
|
|
2339
|
+
if (!data || data.type !== "webrun-rpc:stream-abort") return;
|
|
2340
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the peer abandoned the stream"));
|
|
2341
|
+
};
|
|
2342
|
+
port.addEventListener("message", onMessage);
|
|
2343
|
+
let posted = false;
|
|
2344
|
+
return {
|
|
2345
|
+
post() {
|
|
2346
|
+
if (posted) return;
|
|
2347
|
+
posted = true;
|
|
2348
|
+
try {
|
|
2349
|
+
port.postMessage({ type: STREAM_ABORT });
|
|
2350
|
+
} catch {}
|
|
2351
|
+
},
|
|
2352
|
+
stop() {
|
|
2353
|
+
port.removeEventListener("message", onMessage);
|
|
2354
|
+
}
|
|
2355
|
+
};
|
|
1441
2356
|
}
|
|
1442
|
-
//#endregion
|
|
1443
|
-
//#region src/sw/sw-dispatcher.ts
|
|
1444
2357
|
/**
|
|
1445
|
-
*
|
|
1446
|
-
*
|
|
2358
|
+
* Aborts the stream when its port closes underneath it — the multiplexer was
|
|
2359
|
+
* closed, or the peer closed the port — for ports that report it (see
|
|
2360
|
+
* `getPortCloseSignal`). Without this a stream waiting for the peer's next
|
|
2361
|
+
* chunk would wait forever on a port that can no longer deliver one: the
|
|
2362
|
+
* outbound half's `callPort` already fails on the close signal, but nothing
|
|
2363
|
+
* failed the inbound half.
|
|
1447
2364
|
*/
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
*/
|
|
1458
|
-
claimedKeys = /* @__PURE__ */ new Set();
|
|
1459
|
-
_cleanup;
|
|
1460
|
-
_activationPromise;
|
|
1461
|
-
constructor({ self, log = () => {} }) {
|
|
1462
|
-
this.self = self;
|
|
1463
|
-
this.log = log;
|
|
2365
|
+
function abortOnPortClose(port, controller) {
|
|
2366
|
+
const closed = getPortCloseSignal(port);
|
|
2367
|
+
if (!closed) return;
|
|
2368
|
+
const onClose = () => {
|
|
2369
|
+
if (!controller.signal.aborted) controller.abort(closed.reason);
|
|
2370
|
+
};
|
|
2371
|
+
if (closed.aborted) {
|
|
2372
|
+
onClose();
|
|
2373
|
+
return;
|
|
1464
2374
|
}
|
|
1465
|
-
|
|
1466
|
-
|
|
2375
|
+
closed.addEventListener("abort", onClose, { once: true });
|
|
2376
|
+
controller.signal.addEventListener("abort", () => closed.removeEventListener("abort", onClose), { once: true });
|
|
2377
|
+
}
|
|
2378
|
+
/**
|
|
2379
|
+
* The per-stream inactivity timeout (spec D8). Reset by any chunk in either
|
|
2380
|
+
* direction; elapsing aborts the stream. Unset, zero or non-finite installs no
|
|
2381
|
+
* timer at all, which is the default: a slow consumer is throttled, not failed.
|
|
2382
|
+
*/
|
|
2383
|
+
function installStreamTimeout(controller, timeout) {
|
|
2384
|
+
if (timeout === void 0 || !Number.isFinite(timeout) || timeout <= 0) return {
|
|
2385
|
+
touch() {},
|
|
2386
|
+
stop() {}
|
|
2387
|
+
};
|
|
2388
|
+
let timer;
|
|
2389
|
+
let stopped = false;
|
|
2390
|
+
const arm = () => {
|
|
2391
|
+
timer = setTimeout(() => {
|
|
2392
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(`webrun-rpc: stream idle for ${timeout} ms`));
|
|
2393
|
+
}, timeout);
|
|
2394
|
+
};
|
|
2395
|
+
arm();
|
|
2396
|
+
return {
|
|
2397
|
+
touch() {
|
|
2398
|
+
if (stopped) return;
|
|
2399
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
2400
|
+
arm();
|
|
2401
|
+
},
|
|
2402
|
+
stop() {
|
|
2403
|
+
stopped = true;
|
|
2404
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
2405
|
+
timer = void 0;
|
|
2406
|
+
}
|
|
2407
|
+
};
|
|
2408
|
+
}
|
|
2409
|
+
/**
|
|
2410
|
+
* The receiving half of one direction.
|
|
2411
|
+
*
|
|
2412
|
+
* The `listenPort` listener is installed **eagerly**, not lazily inside
|
|
2413
|
+
* `recieveIterator`'s installer, because a handler that never drains its input
|
|
2414
|
+
* would otherwise leave the peer's chunk calls with nobody to answer them. If
|
|
2415
|
+
* the local consumer has not started iterating, an inbound chunk waits for it —
|
|
2416
|
+
* which is the correct backpressure, and different from having no listener.
|
|
2417
|
+
*/
|
|
2418
|
+
function receiveChunks(port, channelName, controller, touch) {
|
|
2419
|
+
let deliver;
|
|
2420
|
+
const waiting = [];
|
|
2421
|
+
let finished = false;
|
|
2422
|
+
let outstanding = false;
|
|
2423
|
+
let poison;
|
|
2424
|
+
let resolveEnded = () => {};
|
|
2425
|
+
const ended = new Promise((resolve) => {
|
|
2426
|
+
resolveEnded = resolve;
|
|
2427
|
+
});
|
|
2428
|
+
let aborted = false;
|
|
2429
|
+
let abortReason;
|
|
2430
|
+
const ready = () => deliver || finished ? Promise.resolve() : new Promise((r) => waiting.push(r));
|
|
2431
|
+
const wake = () => {
|
|
2432
|
+
for (const r of waiting.splice(0)) r();
|
|
2433
|
+
};
|
|
2434
|
+
const off = listenPort(port, async ({ done, value, error }) => {
|
|
2435
|
+
touch();
|
|
2436
|
+
if (poison) throw poison;
|
|
2437
|
+
if (outstanding) {
|
|
2438
|
+
poison = /* @__PURE__ */ new Error("webrun-rpc: peer sent a second unconfirmed chunk; the stream port is closed");
|
|
2439
|
+
controller.abort(poison);
|
|
2440
|
+
setTimeout(() => {
|
|
2441
|
+
try {
|
|
2442
|
+
port.close?.();
|
|
2443
|
+
} catch {}
|
|
2444
|
+
}, 0);
|
|
2445
|
+
throw poison;
|
|
2446
|
+
}
|
|
2447
|
+
outstanding = true;
|
|
2448
|
+
try {
|
|
2449
|
+
await ready();
|
|
2450
|
+
if (finished) throw poison ?? /* @__PURE__ */ new Error("webrun-rpc: the stream is closed");
|
|
2451
|
+
await deliver?.({
|
|
2452
|
+
done,
|
|
2453
|
+
value,
|
|
2454
|
+
error: error ? deserializeError(error) : void 0
|
|
2455
|
+
});
|
|
2456
|
+
} finally {
|
|
2457
|
+
outstanding = false;
|
|
2458
|
+
}
|
|
2459
|
+
if (done) resolveEnded();
|
|
2460
|
+
}, { channelName });
|
|
2461
|
+
const detach = () => {
|
|
2462
|
+
finished = true;
|
|
2463
|
+
wake();
|
|
2464
|
+
off();
|
|
2465
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
2466
|
+
resolveEnded();
|
|
2467
|
+
};
|
|
2468
|
+
const onAbort = () => {
|
|
2469
|
+
aborted = true;
|
|
2470
|
+
abortReason = controller.signal.reason;
|
|
2471
|
+
finished = true;
|
|
2472
|
+
wake();
|
|
2473
|
+
deliver?.({
|
|
2474
|
+
done: true,
|
|
2475
|
+
error: abortReason
|
|
2476
|
+
});
|
|
2477
|
+
resolveEnded();
|
|
2478
|
+
};
|
|
2479
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
2480
|
+
return {
|
|
2481
|
+
stream: recieveIterator((d) => {
|
|
2482
|
+
if (aborted) {
|
|
2483
|
+
d({
|
|
2484
|
+
done: true,
|
|
2485
|
+
error: abortReason
|
|
2486
|
+
});
|
|
2487
|
+
return detach;
|
|
2488
|
+
}
|
|
2489
|
+
deliver = d;
|
|
2490
|
+
wake();
|
|
2491
|
+
return detach;
|
|
2492
|
+
}),
|
|
2493
|
+
stop: detach,
|
|
2494
|
+
ended
|
|
2495
|
+
};
|
|
2496
|
+
}
|
|
2497
|
+
/**
|
|
2498
|
+
* The sending half of one direction: one `callPort` per chunk, one call
|
|
2499
|
+
* outstanding at a time (spec D11/D12), with no per-chunk deadline (spec D8).
|
|
2500
|
+
*/
|
|
2501
|
+
async function sendChunks(port, channelName, output, { maxMessageSize, log }, signal, touch) {
|
|
2502
|
+
const stream = throughAbort(maxMessageSize ? toChunks(maxMessageSize)(output) : output, signal);
|
|
2503
|
+
try {
|
|
2504
|
+
await sendIterator(async ({ done, value, error }) => {
|
|
2505
|
+
if (signal.aborted) return;
|
|
2506
|
+
const chunk = {
|
|
2507
|
+
done,
|
|
2508
|
+
value,
|
|
2509
|
+
error: error === void 0 ? void 0 : serializeError(error)
|
|
2510
|
+
};
|
|
2511
|
+
log?.("[duplexOverPort] send", {
|
|
2512
|
+
channelName,
|
|
2513
|
+
done,
|
|
2514
|
+
size: value?.byteLength
|
|
2515
|
+
});
|
|
2516
|
+
await callPort(port, chunk, {
|
|
2517
|
+
channelName,
|
|
2518
|
+
timeout: NO_TIMEOUT,
|
|
2519
|
+
signal
|
|
2520
|
+
});
|
|
2521
|
+
touch();
|
|
2522
|
+
}, stream);
|
|
2523
|
+
} catch (err) {
|
|
2524
|
+
if (signal.aborted) return;
|
|
2525
|
+
throw err;
|
|
1467
2526
|
}
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
2527
|
+
}
|
|
2528
|
+
/**
|
|
2529
|
+
* One virtual port.
|
|
2530
|
+
*
|
|
2531
|
+
* `deliver` and `markClosed` are deliberately not on `port`: the consumer holds
|
|
2532
|
+
* only a `MessageTarget`, so it cannot forge inbound traffic or close the port
|
|
2533
|
+
* out from under the multiplexer's bookkeeping.
|
|
2534
|
+
*/
|
|
2535
|
+
function newVirtualPort(send, requestClose) {
|
|
2536
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2537
|
+
let closed = false;
|
|
2538
|
+
const closing = new AbortController();
|
|
2539
|
+
const abort = (reason) => {
|
|
2540
|
+
if (closing.signal.aborted) return;
|
|
2541
|
+
closing.abort(reason ?? /* @__PURE__ */ new Error("webrun-rpc: the port was closed"));
|
|
2542
|
+
};
|
|
2543
|
+
const port = {
|
|
2544
|
+
addEventListener(_type, listener) {
|
|
2545
|
+
listeners.add(listener);
|
|
2546
|
+
},
|
|
2547
|
+
removeEventListener(_type, listener) {
|
|
2548
|
+
listeners.delete(listener);
|
|
2549
|
+
},
|
|
2550
|
+
postMessage(message, transfer) {
|
|
2551
|
+
if (closed) return;
|
|
2552
|
+
send(message, transfer);
|
|
2553
|
+
},
|
|
2554
|
+
close() {
|
|
2555
|
+
if (closed) return;
|
|
2556
|
+
closed = true;
|
|
2557
|
+
const notify = requestClose;
|
|
2558
|
+
listeners.clear();
|
|
2559
|
+
notify();
|
|
2560
|
+
abort();
|
|
2561
|
+
}
|
|
2562
|
+
};
|
|
2563
|
+
setPortCloseSignal(port, closing.signal);
|
|
2564
|
+
return {
|
|
2565
|
+
port,
|
|
2566
|
+
deliver(payload) {
|
|
2567
|
+
if (closed) return;
|
|
2568
|
+
const event = new MessageEvent("message", { data: payload });
|
|
2569
|
+
for (const listener of [...listeners]) try {
|
|
2570
|
+
listener(event);
|
|
2571
|
+
} catch {}
|
|
2572
|
+
},
|
|
2573
|
+
markClosed(reason) {
|
|
2574
|
+
closed = true;
|
|
2575
|
+
listeners.clear();
|
|
2576
|
+
abort(reason);
|
|
2577
|
+
},
|
|
2578
|
+
isClosed() {
|
|
2579
|
+
return closed;
|
|
2580
|
+
}
|
|
2581
|
+
};
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* The message of the error that fails the calls still in flight on a
|
|
2585
|
+
* multiplexer when it is closed (`PortMux.close()`).
|
|
2586
|
+
*/
|
|
2587
|
+
const MUX_CLOSED_MESSAGE = "webrun-rpc: the multiplexer was closed";
|
|
2588
|
+
/** Ceiling on concurrently open virtual ports. Bounds the id table only. */
|
|
2589
|
+
const DEFAULT_MAX_PORTS = 1024;
|
|
2590
|
+
/**
|
|
2591
|
+
* The default `PortMux`: emulates multiplexing over a single port.
|
|
2592
|
+
*
|
|
2593
|
+
* A transport that already multiplexes natively supplies its own `PortMux`
|
|
2594
|
+
* instead — this implementation is for transports that offer one pipe.
|
|
2595
|
+
*/
|
|
2596
|
+
function multiplexPort(port, options) {
|
|
2597
|
+
const { codec, onPort, side = "initiator", maxPorts = DEFAULT_MAX_PORTS, maxMessageSize } = options;
|
|
2598
|
+
const open = /* @__PURE__ */ new Map();
|
|
2599
|
+
let nextId = side === "initiator" ? 0 : 1;
|
|
2600
|
+
let muxClosed = false;
|
|
2601
|
+
const post = (envelope, transfer) => {
|
|
2602
|
+
if (muxClosed) return;
|
|
2603
|
+
try {
|
|
2604
|
+
codec.post(port, envelope, transfer);
|
|
2605
|
+
} catch {}
|
|
2606
|
+
};
|
|
2607
|
+
const attach = (id) => {
|
|
2608
|
+
let self;
|
|
2609
|
+
self = newVirtualPort((payload, transfer) => post({
|
|
2610
|
+
type: "message",
|
|
2611
|
+
id,
|
|
2612
|
+
payload
|
|
2613
|
+
}, transfer), (reason) => {
|
|
2614
|
+
post({
|
|
2615
|
+
type: "close",
|
|
2616
|
+
id,
|
|
2617
|
+
reason
|
|
2618
|
+
});
|
|
2619
|
+
open.delete(id);
|
|
2620
|
+
self.markClosed();
|
|
2621
|
+
});
|
|
2622
|
+
open.set(id, self);
|
|
2623
|
+
return self;
|
|
2624
|
+
};
|
|
2625
|
+
const handleEnvelope = (envelope) => {
|
|
2626
|
+
if (muxClosed) return;
|
|
2627
|
+
if (envelope.type === "open") {
|
|
2628
|
+
if (open.has(envelope.id)) return;
|
|
2629
|
+
if (open.size >= maxPorts) {
|
|
2630
|
+
post({
|
|
2631
|
+
type: "close",
|
|
2632
|
+
id: envelope.id,
|
|
2633
|
+
reason: "max-ports"
|
|
2634
|
+
});
|
|
2635
|
+
return;
|
|
2636
|
+
}
|
|
2637
|
+
const handle = attach(envelope.id);
|
|
2638
|
+
let accepted = false;
|
|
2639
|
+
if (onPort) try {
|
|
2640
|
+
accepted = onPort(handle.port, envelope.meta) !== false;
|
|
2641
|
+
} catch {
|
|
2642
|
+
accepted = false;
|
|
2643
|
+
}
|
|
2644
|
+
if (!accepted) {
|
|
2645
|
+
open.delete(envelope.id);
|
|
2646
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the port was rejected"));
|
|
2647
|
+
post({
|
|
2648
|
+
type: "close",
|
|
2649
|
+
id: envelope.id,
|
|
2650
|
+
reason: "rejected"
|
|
2651
|
+
});
|
|
2652
|
+
}
|
|
2653
|
+
return;
|
|
2654
|
+
}
|
|
2655
|
+
const handle = open.get(envelope.id);
|
|
2656
|
+
if (envelope.type === "message") {
|
|
2657
|
+
if (!handle) return;
|
|
2658
|
+
handle.deliver(envelope.payload);
|
|
2659
|
+
return;
|
|
2660
|
+
}
|
|
2661
|
+
if (!handle) return;
|
|
2662
|
+
open.delete(envelope.id);
|
|
2663
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the peer closed the port"));
|
|
2664
|
+
};
|
|
2665
|
+
const listener = (event) => {
|
|
2666
|
+
const envelope = codec.read(event);
|
|
2667
|
+
if (envelope) handleEnvelope(envelope);
|
|
2668
|
+
};
|
|
2669
|
+
port.addEventListener("message", listener);
|
|
2670
|
+
port.start?.();
|
|
2671
|
+
return {
|
|
2672
|
+
maxMessageSize,
|
|
2673
|
+
async openPort(meta) {
|
|
2674
|
+
if (muxClosed) throw new Error("webrun-rpc: the multiplexer is closed");
|
|
2675
|
+
if (open.size >= maxPorts) throw new RangeError(`webrun-rpc: maxPorts (${maxPorts}) reached`);
|
|
2676
|
+
while (open.has(nextId)) nextId += 2;
|
|
2677
|
+
const id = nextId;
|
|
2678
|
+
nextId += 2;
|
|
2679
|
+
const handle = attach(id);
|
|
2680
|
+
post({
|
|
2681
|
+
type: "open",
|
|
2682
|
+
id,
|
|
2683
|
+
meta
|
|
2684
|
+
});
|
|
2685
|
+
return handle.port;
|
|
2686
|
+
},
|
|
2687
|
+
async close() {
|
|
2688
|
+
if (muxClosed) return;
|
|
2689
|
+
for (const [id, handle] of [...open]) {
|
|
2690
|
+
post({
|
|
2691
|
+
type: "close",
|
|
2692
|
+
id
|
|
2693
|
+
});
|
|
2694
|
+
open.delete(id);
|
|
2695
|
+
handle.markClosed(/* @__PURE__ */ new Error(MUX_CLOSED_MESSAGE));
|
|
1482
2696
|
}
|
|
1483
|
-
|
|
2697
|
+
muxClosed = true;
|
|
2698
|
+
port.removeEventListener("message", listener);
|
|
2699
|
+
await port.close?.();
|
|
1484
2700
|
}
|
|
2701
|
+
};
|
|
2702
|
+
}
|
|
2703
|
+
/**
|
|
2704
|
+
* Announced with every port this pair opens. Layer 1 never reads `meta` — it is
|
|
2705
|
+
* here so a peer running something else over the same multiplexer can tell a
|
|
2706
|
+
* stream port from whatever else it hands out, and so a packet capture says
|
|
2707
|
+
* what the port is for.
|
|
2708
|
+
*/
|
|
2709
|
+
const STREAM_META = { kind: "stream" };
|
|
2710
|
+
/**
|
|
2711
|
+
* One port source in, one caller `Duplex` out.
|
|
2712
|
+
*
|
|
2713
|
+
* A call is a port: the mux allocates one, `duplexOverPort` runs the single
|
|
2714
|
+
* invocation on it, and closing the stream closes the port. No stream ids, no
|
|
2715
|
+
* framing and no credit accounting live here — the mux owns the first, and
|
|
2716
|
+
* `duplexOverPort` owns the one-chunk window that makes memory bounded.
|
|
2717
|
+
*/
|
|
2718
|
+
const connect = async ({ mux: factory, timeout }) => {
|
|
2719
|
+
const mux = await factory();
|
|
2720
|
+
const streamOptions = {
|
|
2721
|
+
maxMessageSize: mux.maxMessageSize,
|
|
2722
|
+
timeout
|
|
2723
|
+
};
|
|
2724
|
+
const call = (input) => {
|
|
2725
|
+
let stream;
|
|
2726
|
+
let abandoned = false;
|
|
2727
|
+
return returningAtOnce((async function* () {
|
|
2728
|
+
const port = await mux.openPort(STREAM_META);
|
|
2729
|
+
if (abandoned) {
|
|
2730
|
+
await port.close?.();
|
|
2731
|
+
return;
|
|
2732
|
+
}
|
|
2733
|
+
stream = duplexOverPort(port, streamOptions)(input);
|
|
2734
|
+
yield* stream;
|
|
2735
|
+
})(), () => {
|
|
2736
|
+
abandoned = true;
|
|
2737
|
+
stream?.return(void 0).catch(() => {});
|
|
2738
|
+
});
|
|
2739
|
+
};
|
|
2740
|
+
return {
|
|
2741
|
+
call,
|
|
2742
|
+
async close() {
|
|
2743
|
+
await mux.close();
|
|
2744
|
+
}
|
|
2745
|
+
};
|
|
2746
|
+
};
|
|
2747
|
+
/**
|
|
2748
|
+
* One port source in, `handler` serving every call that arrives on it.
|
|
2749
|
+
*
|
|
2750
|
+
* Each inbound port is one invocation, so the factory's `onPort` is the accept
|
|
2751
|
+
* loop: it installs `handler` on the new port and nothing else. The returned
|
|
2752
|
+
* teardown abandons the streams still running *before* dropping the mux, so
|
|
2753
|
+
* the peer's callers reject with "the peer abandoned the stream" instead of
|
|
2754
|
+
* parking forever on a port that has silently gone inert — layer 1's close is
|
|
2755
|
+
* not observable to layer 2, which is why the notice has to be posted
|
|
2756
|
+
* deliberately.
|
|
2757
|
+
*/
|
|
2758
|
+
const serve = async ({ mux: factory, timeout }, handler) => {
|
|
2759
|
+
const live = /* @__PURE__ */ new Set();
|
|
2760
|
+
let streamOptions = { timeout };
|
|
2761
|
+
const mux = await factory((port) => {
|
|
2762
|
+
let off;
|
|
2763
|
+
let finished = false;
|
|
2764
|
+
const tracked = (input) => (async function* () {
|
|
2765
|
+
try {
|
|
2766
|
+
yield* handler(input);
|
|
2767
|
+
} finally {
|
|
2768
|
+
finished = true;
|
|
2769
|
+
if (off) live.delete(off);
|
|
2770
|
+
}
|
|
2771
|
+
})();
|
|
2772
|
+
off = serveDuplexOverPort(port, tracked, streamOptions);
|
|
2773
|
+
if (!finished) live.add(off);
|
|
2774
|
+
});
|
|
2775
|
+
streamOptions = {
|
|
2776
|
+
maxMessageSize: mux.maxMessageSize,
|
|
2777
|
+
timeout
|
|
2778
|
+
};
|
|
2779
|
+
let torn = false;
|
|
2780
|
+
return async () => {
|
|
2781
|
+
if (torn) return;
|
|
2782
|
+
torn = true;
|
|
2783
|
+
for (const off of [...live]) {
|
|
2784
|
+
live.delete(off);
|
|
2785
|
+
try {
|
|
2786
|
+
off();
|
|
2787
|
+
} catch {}
|
|
2788
|
+
}
|
|
2789
|
+
await mux.close();
|
|
2790
|
+
};
|
|
2791
|
+
};
|
|
2792
|
+
/**
|
|
2793
|
+
* Ports over ONE PIPE OF BYTES — a `MessagePort`, a worker, a WebSocket.
|
|
2794
|
+
*
|
|
2795
|
+
* There is no second port to be had, so `multiplexPort`'s id table invents
|
|
2796
|
+
* them. Use this when the transport gives you exactly one channel.
|
|
2797
|
+
*/
|
|
2798
|
+
function overPipe(pipe, options) {
|
|
2799
|
+
return (onPort) => multiplexPort(pipe, {
|
|
2800
|
+
...options,
|
|
2801
|
+
onPort
|
|
2802
|
+
});
|
|
2803
|
+
}
|
|
2804
|
+
function isEnvelope(value) {
|
|
2805
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2806
|
+
const candidate = value;
|
|
2807
|
+
if (typeof candidate.id !== "number") return false;
|
|
2808
|
+
if (!Number.isInteger(candidate.id) || candidate.id < 0) return false;
|
|
2809
|
+
return candidate.type === "open" || candidate.type === "message" || candidate.type === "close";
|
|
2810
|
+
}
|
|
2811
|
+
/**
|
|
2812
|
+
* For ports whose messages are structured values — a real `MessagePort`, a
|
|
2813
|
+
* worker, an iframe.
|
|
2814
|
+
*
|
|
2815
|
+
* Envelopes are posted as-is, so nothing is encoded, `ArrayBuffer`s move
|
|
2816
|
+
* zero-copy through the transfer list, and structured clone does the work the
|
|
2817
|
+
* platform already does well. This is a performance choice only: layer 2 may
|
|
2818
|
+
* not send anything a byte codec could not also carry.
|
|
2819
|
+
*/
|
|
2820
|
+
const structuredCodec = {
|
|
2821
|
+
post(port, envelope, transfer) {
|
|
2822
|
+
if (transfer && transfer.length > 0) port.postMessage(envelope, transfer);
|
|
2823
|
+
else port.postMessage(envelope);
|
|
2824
|
+
},
|
|
2825
|
+
read(event) {
|
|
2826
|
+
return isEnvelope(event.data) ? event.data : void 0;
|
|
2827
|
+
}
|
|
2828
|
+
};
|
|
2829
|
+
//#endregion
|
|
2830
|
+
//#region src/link/async-dispose.ts
|
|
2831
|
+
/**
|
|
2832
|
+
* Makes `target` disposable with `await using`: installs `dispose` as its
|
|
2833
|
+
* `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
|
|
2834
|
+
* iterators lose what a native generator gets from `AsyncIteratorPrototype`;
|
|
2835
|
+
* this gives it back. A no-op where the symbol is missing. Kept off the
|
|
2836
|
+
* declared types, which would require consumers to compile with the
|
|
2837
|
+
* `esnext.disposable` lib.
|
|
2838
|
+
*/
|
|
2839
|
+
function asyncDisposable(target, dispose) {
|
|
2840
|
+
const asyncDispose = Symbol.asyncDispose;
|
|
2841
|
+
if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
|
|
2842
|
+
value: async () => {
|
|
2843
|
+
await dispose();
|
|
2844
|
+
},
|
|
2845
|
+
configurable: true,
|
|
2846
|
+
writable: true
|
|
2847
|
+
});
|
|
2848
|
+
return target;
|
|
2849
|
+
}
|
|
2850
|
+
//#endregion
|
|
2851
|
+
//#region src/link/http-link.ts
|
|
2852
|
+
/**
|
|
2853
|
+
* The version of the HTTP-over-`MessagePort` protocol this package speaks,
|
|
2854
|
+
* sent in every hand-shake that sets up a link. Version 1 was this package's
|
|
2855
|
+
* own `handleStreams` / `sendStream` (no backpressure); version 2 is
|
|
2856
|
+
* webrun-rpc's `connect` / `serve` over `overPipe` with webrun-http-streams'
|
|
2857
|
+
* `fetchOverDuplex` / `serveFetchOverDuplex`: one port per link, calls
|
|
2858
|
+
* multiplexed on it, each call a stream with a one-chunk window in both
|
|
2859
|
+
* directions, and cancellation that reaches the handler.
|
|
2860
|
+
*/
|
|
2861
|
+
const HTTP_LINK_PROTOCOL = "webrun-http-link/2";
|
|
2862
|
+
/**
|
|
2863
|
+
* Why a request failed when its link went away under it: the far side (the
|
|
2864
|
+
* handler, or the ServiceWorker) was lost. The request may or may not have
|
|
2865
|
+
* been applied.
|
|
2866
|
+
*/
|
|
2867
|
+
var LinkLostError = class extends Error {
|
|
2868
|
+
constructor(message = "The link was lost while this request was in flight") {
|
|
2869
|
+
super(`${message}; it may or may not have been applied.`);
|
|
2870
|
+
this.name = "LinkLostError";
|
|
1485
2871
|
}
|
|
1486
|
-
|
|
2872
|
+
};
|
|
2873
|
+
/**
|
|
2874
|
+
* Posted on a link's port by the calling end when it closes the link, so the
|
|
2875
|
+
* answering end can release it: a `MessagePort` never reports that its other
|
|
2876
|
+
* end is gone.
|
|
2877
|
+
*/
|
|
2878
|
+
const LINK_CLOSE = "webrun-http:link-close";
|
|
2879
|
+
/** Opens the calling end of a link on `port` (one port per link). */
|
|
2880
|
+
async function connectHttpLink(port, { streamTimeout, maxPorts } = {}) {
|
|
2881
|
+
const { call, close } = await connect({
|
|
2882
|
+
mux: overPipe(port, {
|
|
2883
|
+
codec: structuredCodec,
|
|
2884
|
+
side: "initiator",
|
|
2885
|
+
maxPorts
|
|
2886
|
+
}),
|
|
2887
|
+
timeout: streamTimeout
|
|
2888
|
+
});
|
|
2889
|
+
return trackedLink((request) => fetchOverDuplex(call, request), async () => {
|
|
2890
|
+
try {
|
|
2891
|
+
port.postMessage({ type: LINK_CLOSE });
|
|
2892
|
+
} catch {}
|
|
2893
|
+
await close();
|
|
2894
|
+
});
|
|
2895
|
+
}
|
|
2896
|
+
/**
|
|
2897
|
+
* Serves `handler` on the answering end of a link. Resolves with a teardown
|
|
2898
|
+
* that abandons the requests still running (their handlers see the
|
|
2899
|
+
* cancellation) and releases the port.
|
|
2900
|
+
*/
|
|
2901
|
+
async function serveHttpLink(port, handler, { streamTimeout, maxPorts, requestIdleMs } = {}) {
|
|
2902
|
+
const teardown = await serve({
|
|
2903
|
+
mux: overPipe(port, {
|
|
2904
|
+
codec: structuredCodec,
|
|
2905
|
+
side: "responder",
|
|
2906
|
+
maxPorts
|
|
2907
|
+
}),
|
|
2908
|
+
timeout: streamTimeout
|
|
2909
|
+
}, serveFetchOverDuplex(async (request) => await handler(request), { requestIdleMs }));
|
|
2910
|
+
const onClose = (event) => {
|
|
2911
|
+
if (event.data?.type === LINK_CLOSE) close();
|
|
2912
|
+
};
|
|
2913
|
+
const close = async () => {
|
|
2914
|
+
port.removeEventListener("message", onClose);
|
|
2915
|
+
await teardown();
|
|
2916
|
+
};
|
|
2917
|
+
port.addEventListener("message", onClose);
|
|
2918
|
+
return close;
|
|
2919
|
+
}
|
|
2920
|
+
/**
|
|
2921
|
+
* Wraps a `send` so the link knows its requests in flight (for draining and
|
|
2922
|
+
* load-based routing) and can fail them all at once when it is closed.
|
|
2923
|
+
*/
|
|
2924
|
+
function trackedLink(send, release) {
|
|
2925
|
+
let inflight = 0;
|
|
2926
|
+
let closed = false;
|
|
2927
|
+
let lostReason;
|
|
2928
|
+
const failers = /* @__PURE__ */ new Set();
|
|
2929
|
+
const idleWaiters = [];
|
|
2930
|
+
const done = () => {
|
|
2931
|
+
inflight--;
|
|
2932
|
+
if (inflight === 0) for (const resolve of idleWaiters.splice(0)) resolve();
|
|
2933
|
+
};
|
|
2934
|
+
const link = {
|
|
2935
|
+
get inflight() {
|
|
2936
|
+
return inflight;
|
|
2937
|
+
},
|
|
2938
|
+
get closed() {
|
|
2939
|
+
return closed;
|
|
2940
|
+
},
|
|
2941
|
+
whenIdle() {
|
|
2942
|
+
return inflight === 0 ? Promise.resolve() : new Promise((r) => idleWaiters.push(r));
|
|
2943
|
+
},
|
|
2944
|
+
async send(request) {
|
|
2945
|
+
if (closed) throw lostReason ?? new LinkLostError("The link is closed");
|
|
2946
|
+
inflight++;
|
|
2947
|
+
let finished = false;
|
|
2948
|
+
const finish = () => {
|
|
2949
|
+
if (finished) return;
|
|
2950
|
+
finished = true;
|
|
2951
|
+
failers.delete(fail);
|
|
2952
|
+
done();
|
|
2953
|
+
};
|
|
2954
|
+
let fail = () => {};
|
|
2955
|
+
const lost = new Promise((_, reject) => {
|
|
2956
|
+
fail = reject;
|
|
2957
|
+
});
|
|
2958
|
+
failers.add(fail);
|
|
2959
|
+
lost.catch(() => {});
|
|
2960
|
+
let response;
|
|
2961
|
+
try {
|
|
2962
|
+
response = await Promise.race([send(request), lost]);
|
|
2963
|
+
} catch (error) {
|
|
2964
|
+
finish();
|
|
2965
|
+
throw lostReason ?? error;
|
|
2966
|
+
}
|
|
2967
|
+
if (!response.body) {
|
|
2968
|
+
finish();
|
|
2969
|
+
return response;
|
|
2970
|
+
}
|
|
2971
|
+
return new Response(guardBody(response.body, lost, () => lostReason, finish), {
|
|
2972
|
+
status: response.status,
|
|
2973
|
+
statusText: response.statusText,
|
|
2974
|
+
headers: response.headers
|
|
2975
|
+
});
|
|
2976
|
+
},
|
|
2977
|
+
async close(reason) {
|
|
2978
|
+
if (closed) return;
|
|
2979
|
+
closed = true;
|
|
2980
|
+
lostReason = reason ?? new LinkLostError("The link was closed");
|
|
2981
|
+
for (const fail of [...failers]) fail(lostReason);
|
|
2982
|
+
try {
|
|
2983
|
+
await release();
|
|
2984
|
+
} catch {}
|
|
2985
|
+
}
|
|
2986
|
+
};
|
|
2987
|
+
return asyncDisposable(link, () => link.close());
|
|
2988
|
+
}
|
|
2989
|
+
/**
|
|
2990
|
+
* A response body that reports its end (done, cancelled or failed) and fails
|
|
2991
|
+
* with the link's reason when the link is lost mid-stream.
|
|
2992
|
+
*/
|
|
2993
|
+
function guardBody(body, lost, reason, finish) {
|
|
2994
|
+
const reader = body.getReader();
|
|
2995
|
+
return new ReadableStream({
|
|
2996
|
+
async pull(controller) {
|
|
2997
|
+
try {
|
|
2998
|
+
const { done, value } = await Promise.race([reader.read(), lost]);
|
|
2999
|
+
if (done) {
|
|
3000
|
+
finish();
|
|
3001
|
+
controller.close();
|
|
3002
|
+
return;
|
|
3003
|
+
}
|
|
3004
|
+
controller.enqueue(value);
|
|
3005
|
+
} catch (error) {
|
|
3006
|
+
finish();
|
|
3007
|
+
reader.cancel().catch(() => {});
|
|
3008
|
+
controller.error(reason() ?? error);
|
|
3009
|
+
}
|
|
3010
|
+
},
|
|
3011
|
+
async cancel(why) {
|
|
3012
|
+
finish();
|
|
3013
|
+
await reader.cancel(why).catch(() => {});
|
|
3014
|
+
}
|
|
3015
|
+
});
|
|
3016
|
+
}
|
|
3017
|
+
//#endregion
|
|
3018
|
+
//#region src/link/locks.ts
|
|
3019
|
+
function lockManager() {
|
|
3020
|
+
return globalThis.navigator?.locks;
|
|
3021
|
+
}
|
|
3022
|
+
function locksAvailable() {
|
|
3023
|
+
return lockManager() !== void 0;
|
|
3024
|
+
}
|
|
3025
|
+
/** A fresh lock name: `<prefix>:<uuid>`. */
|
|
3026
|
+
function newLockName(prefix) {
|
|
3027
|
+
return `${prefix}:${crypto.randomUUID()}`;
|
|
3028
|
+
}
|
|
3029
|
+
/**
|
|
3030
|
+
* Takes the lock `name` and holds it until the returned release is called or
|
|
3031
|
+
* this context dies. Resolves once the lock is held; with no Web Locks,
|
|
3032
|
+
* resolves at once.
|
|
3033
|
+
*/
|
|
3034
|
+
async function holdLock(name) {
|
|
3035
|
+
const locks = lockManager();
|
|
3036
|
+
if (!locks) return () => {};
|
|
3037
|
+
let release = () => {};
|
|
3038
|
+
const released = new Promise((resolve) => {
|
|
3039
|
+
release = resolve;
|
|
3040
|
+
});
|
|
3041
|
+
await new Promise((held) => {
|
|
3042
|
+
locks.request(name, {}, () => {
|
|
3043
|
+
held();
|
|
3044
|
+
return released;
|
|
3045
|
+
}).catch(() => held());
|
|
3046
|
+
});
|
|
3047
|
+
return release;
|
|
3048
|
+
}
|
|
3049
|
+
/**
|
|
3050
|
+
* Calls `onLost` once the lock `name` is granted to this context — that is,
|
|
3051
|
+
* once whoever holds it is gone — and releases it at once. Returns a function
|
|
3052
|
+
* that stops watching. With no Web Locks, never calls `onLost`.
|
|
3053
|
+
*/
|
|
3054
|
+
function watchLock(name, onLost) {
|
|
3055
|
+
const locks = lockManager();
|
|
3056
|
+
if (!locks) return () => {};
|
|
3057
|
+
const controller = new AbortController();
|
|
3058
|
+
locks.request(name, { signal: controller.signal }, () => {
|
|
3059
|
+
if (!controller.signal.aborted) onLost();
|
|
3060
|
+
}).catch(() => {});
|
|
3061
|
+
return () => controller.abort();
|
|
3062
|
+
}
|
|
3063
|
+
/**
|
|
3064
|
+
* The names of the locks held right now in this origin, or `undefined` where
|
|
3065
|
+
* that cannot be asked. A backup for `watchLock`: a grant can be late, a query
|
|
3066
|
+
* cannot.
|
|
3067
|
+
*/
|
|
3068
|
+
async function heldLockNames() {
|
|
3069
|
+
const locks = lockManager();
|
|
3070
|
+
if (!locks?.query) return void 0;
|
|
3071
|
+
try {
|
|
3072
|
+
const { held = [] } = await locks.query();
|
|
3073
|
+
return new Set(held.map((lock) => lock.name ?? ""));
|
|
3074
|
+
} catch {
|
|
3075
|
+
return;
|
|
3076
|
+
}
|
|
3077
|
+
}
|
|
3078
|
+
//#endregion
|
|
3079
|
+
//#region src/link/rendezvous.ts
|
|
3080
|
+
/**
|
|
3081
|
+
* Matches replies to requests by id, for the control messages that hand
|
|
3082
|
+
* WebSocket ports across: each waiting request has a deadline, and all of a
|
|
3083
|
+
* peer's waiting requests can be failed at once when the peer is lost.
|
|
3084
|
+
*/
|
|
3085
|
+
var PortRendezvous = class {
|
|
3086
|
+
_prefix;
|
|
3087
|
+
_waiting = /* @__PURE__ */ new Map();
|
|
3088
|
+
_counter = 0;
|
|
3089
|
+
constructor(_prefix = "r") {
|
|
3090
|
+
this._prefix = _prefix;
|
|
3091
|
+
}
|
|
3092
|
+
/** A fresh id for a request. */
|
|
3093
|
+
newId() {
|
|
3094
|
+
return `${this._prefix}:${++this._counter}`;
|
|
3095
|
+
}
|
|
3096
|
+
get size() {
|
|
3097
|
+
return this._waiting.size;
|
|
3098
|
+
}
|
|
3099
|
+
/** Waits for the reply to `id`, failing after `timeoutMs`. */
|
|
3100
|
+
wait(id, timeoutMs, describe = "the reply") {
|
|
3101
|
+
return new Promise((resolve, reject) => {
|
|
3102
|
+
const timer = setTimeout(() => {
|
|
3103
|
+
this._waiting.delete(id);
|
|
3104
|
+
reject(/* @__PURE__ */ new Error(`No answer to ${describe} within ${timeoutMs} ms`));
|
|
3105
|
+
}, timeoutMs);
|
|
3106
|
+
this._waiting.set(id, {
|
|
3107
|
+
resolve,
|
|
3108
|
+
reject,
|
|
3109
|
+
timer
|
|
3110
|
+
});
|
|
3111
|
+
});
|
|
3112
|
+
}
|
|
3113
|
+
/** Delivers the reply to `id`. `false` when nobody waits for it (it timed out). */
|
|
3114
|
+
settle(id, value) {
|
|
3115
|
+
const waiting = this._waiting.get(id);
|
|
3116
|
+
if (!waiting) return false;
|
|
3117
|
+
this._waiting.delete(id);
|
|
3118
|
+
clearTimeout(waiting.timer);
|
|
3119
|
+
waiting.resolve(value);
|
|
3120
|
+
return true;
|
|
3121
|
+
}
|
|
3122
|
+
fail(id, error) {
|
|
3123
|
+
const waiting = this._waiting.get(id);
|
|
3124
|
+
if (!waiting) return;
|
|
3125
|
+
this._waiting.delete(id);
|
|
3126
|
+
clearTimeout(waiting.timer);
|
|
3127
|
+
waiting.reject(error);
|
|
3128
|
+
}
|
|
3129
|
+
failAll(error) {
|
|
3130
|
+
for (const id of [...this._waiting.keys()]) this.fail(id, error);
|
|
3131
|
+
}
|
|
3132
|
+
};
|
|
3133
|
+
//#endregion
|
|
3134
|
+
//#region src/ws/upgrade.ts
|
|
3135
|
+
/**
|
|
3136
|
+
* The upgrade, as an HTTP exchange: a `GET` with `Upgrade: websocket` goes to
|
|
3137
|
+
* an ordinary `(Request) => Response` handler, and a `101` answer carrying a
|
|
3138
|
+
* server socket means accepted. Anything else is a refusal, with its status.
|
|
3139
|
+
*
|
|
3140
|
+
* FORBIDDEN HEADERS. A browser drops `Upgrade`, `Connection` and every
|
|
3141
|
+
* `Sec-*` header from a `new Request()`. The upgrade request therefore carries
|
|
3142
|
+
* its headers as an own `headers` property, a standalone `Headers` that keeps
|
|
3143
|
+
* them, so handler code reads `request.headers.get("upgrade")` as usual.
|
|
3144
|
+
*
|
|
3145
|
+
* NO 101 IN A `Response`. The constructor refuses statuses below 200, so the
|
|
3146
|
+
* response `upgradeWebSocket` returns reports 101 through an own `status`
|
|
3147
|
+
* property; the port that goes back to the caller is found with `takePort`.
|
|
3148
|
+
*/
|
|
3149
|
+
/** The request header carrying the client's version of the frame protocol. */
|
|
3150
|
+
const WS_VERSION_HEADER = "x-webrun-ws-version";
|
|
3151
|
+
/**
|
|
3152
|
+
* The `GET` a handler sees for `new WebSocket(url, protocols)`. A `ws:` or
|
|
3153
|
+
* `wss:` url is given as `http:` or `https:`, as a server sees it.
|
|
3154
|
+
*/
|
|
3155
|
+
function newWebSocketUpgradeRequest(url, { protocols = [], headers } = {}) {
|
|
3156
|
+
const httpUrl = new URL(`${url}`);
|
|
3157
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
3158
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
3159
|
+
const all = new Headers(headers);
|
|
3160
|
+
all.set("upgrade", "websocket");
|
|
3161
|
+
all.set("connection", "Upgrade");
|
|
3162
|
+
all.set("sec-websocket-version", "13");
|
|
3163
|
+
if (!all.has("sec-websocket-key")) all.set("sec-websocket-key", randomKey());
|
|
3164
|
+
if (protocols.length > 0) all.set("sec-websocket-protocol", protocols.join(", "));
|
|
3165
|
+
if (!all.has("x-webrun-ws-version")) all.set(WS_VERSION_HEADER, `2`);
|
|
3166
|
+
return withHeaders(new Request(httpUrl, {
|
|
3167
|
+
method: "GET",
|
|
3168
|
+
headers: all
|
|
3169
|
+
}), all);
|
|
3170
|
+
}
|
|
3171
|
+
/**
|
|
3172
|
+
* Re-attaches `headers` to `request` as its own `headers` property, keeping
|
|
3173
|
+
* the forbidden ones a browser dropped. Returns `request`.
|
|
3174
|
+
*/
|
|
3175
|
+
function withHeaders(request, headers) {
|
|
3176
|
+
Object.defineProperty(request, "headers", {
|
|
3177
|
+
value: headers,
|
|
3178
|
+
configurable: true
|
|
3179
|
+
});
|
|
3180
|
+
return request;
|
|
3181
|
+
}
|
|
3182
|
+
function randomKey() {
|
|
3183
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
3184
|
+
crypto.getRandomValues(bytes);
|
|
3185
|
+
return btoa(String.fromCharCode(...bytes));
|
|
3186
|
+
}
|
|
3187
|
+
//#endregion
|
|
3188
|
+
//#region src/sw/handler-table.ts
|
|
3189
|
+
/**
|
|
3190
|
+
* The default route: the handler with the fewest requests in flight, the
|
|
3191
|
+
* oldest on a tie. With one handler per key — one tab — that is the first
|
|
3192
|
+
* live handler of the key, as before routing was pluggable.
|
|
3193
|
+
*/
|
|
3194
|
+
const leastInflightRoute = (_request, _key, handlers) => {
|
|
3195
|
+
let best;
|
|
3196
|
+
for (const handler of handlers) if (best === void 0 || handler.inflight < best.inflight || handler.inflight === best.inflight && handler.attachedAt < best.attachedAt) best = handler;
|
|
3197
|
+
return best;
|
|
3198
|
+
};
|
|
3199
|
+
var HandlerTable = class {
|
|
3200
|
+
_entries = /* @__PURE__ */ new Map();
|
|
3201
|
+
_waiters = [];
|
|
3202
|
+
/** Adds `entry`. Returns the entry it replaces (same key and id), if any. */
|
|
3203
|
+
add(entry) {
|
|
3204
|
+
let slots = this._entries.get(entry.key);
|
|
3205
|
+
if (!slots) {
|
|
3206
|
+
slots = /* @__PURE__ */ new Map();
|
|
3207
|
+
this._entries.set(entry.key, slots);
|
|
3208
|
+
}
|
|
3209
|
+
const replaced = slots.get(entry.id);
|
|
3210
|
+
slots.set(entry.id, entry);
|
|
3211
|
+
if (!entry.draining) this._waiters = this._waiters.filter(({ key, resolve }) => {
|
|
3212
|
+
if (key !== entry.key) return true;
|
|
3213
|
+
resolve(true);
|
|
3214
|
+
return false;
|
|
3215
|
+
});
|
|
3216
|
+
return replaced;
|
|
3217
|
+
}
|
|
3218
|
+
/** Removes `entry` if it is still the one in its slot. */
|
|
3219
|
+
remove(entry) {
|
|
3220
|
+
const slots = this._entries.get(entry.key);
|
|
3221
|
+
if (slots?.get(entry.id) !== entry) return false;
|
|
3222
|
+
slots.delete(entry.id);
|
|
3223
|
+
if (slots.size === 0) this._entries.delete(entry.key);
|
|
3224
|
+
return true;
|
|
3225
|
+
}
|
|
3226
|
+
get(key, id) {
|
|
3227
|
+
return this._entries.get(key)?.get(id);
|
|
3228
|
+
}
|
|
3229
|
+
/** Every entry of `key`, draining or not. */
|
|
3230
|
+
all(key) {
|
|
3231
|
+
return [...this._entries.get(key)?.values() ?? []];
|
|
3232
|
+
}
|
|
3233
|
+
/** The entries of `key` that take new requests. */
|
|
3234
|
+
live(key) {
|
|
3235
|
+
return this.all(key).filter((entry) => !entry.draining);
|
|
3236
|
+
}
|
|
3237
|
+
entries() {
|
|
3238
|
+
return [...this._entries.values()].flatMap((slots) => [...slots.values()]);
|
|
3239
|
+
}
|
|
3240
|
+
get size() {
|
|
3241
|
+
let size = 0;
|
|
3242
|
+
for (const slots of this._entries.values()) size += slots.size;
|
|
3243
|
+
return size;
|
|
3244
|
+
}
|
|
3245
|
+
/**
|
|
3246
|
+
* Resolves `true` once a live entry for `key` is added (at once if there is
|
|
3247
|
+
* one, unless `next`), `false` after `ms`.
|
|
3248
|
+
*/
|
|
3249
|
+
waitFor(key, ms, next = false) {
|
|
3250
|
+
if (!next && this.live(key).length > 0) return Promise.resolve(true);
|
|
3251
|
+
return new Promise((resolve) => {
|
|
3252
|
+
const waiter = {
|
|
3253
|
+
key,
|
|
3254
|
+
resolve: (found) => {
|
|
3255
|
+
clearTimeout(timer);
|
|
3256
|
+
resolve(found);
|
|
3257
|
+
}
|
|
3258
|
+
};
|
|
3259
|
+
const timer = setTimeout(() => {
|
|
3260
|
+
this._waiters = this._waiters.filter((w) => w !== waiter);
|
|
3261
|
+
resolve(false);
|
|
3262
|
+
}, ms);
|
|
3263
|
+
this._waiters.push(waiter);
|
|
3264
|
+
});
|
|
3265
|
+
}
|
|
3266
|
+
};
|
|
3267
|
+
//#endregion
|
|
3268
|
+
//#region src/sw/protocol.ts
|
|
3269
|
+
/**
|
|
3270
|
+
* The messages between pages, Dedicated Workers and the same-origin
|
|
3271
|
+
* ServiceWorker. Internal: the shapes may change between versions, which is
|
|
3272
|
+
* why every hand-shake carries `HTTP_LINK_PROTOCOL`.
|
|
3273
|
+
*
|
|
3274
|
+
* THREE PORTS PER HANDLER LINK. A page makes the channels and hands one end of
|
|
3275
|
+
* each to the handler (itself, or a worker) and the other to the
|
|
3276
|
+
* ServiceWorker; after that it carries nothing:
|
|
3277
|
+
*
|
|
3278
|
+
* - `down`: ServiceWorker → handler, the requests the handler serves;
|
|
3279
|
+
* - `ctl`: a raw port next to them, for what HTTP over a stream cannot carry,
|
|
3280
|
+
* transferred `MessagePort`s (WebSocket hand-over);
|
|
3281
|
+
* - `up` (workers only): handler → ServiceWorker, the requests the handler
|
|
3282
|
+
* sends through the router (to other handlers).
|
|
3283
|
+
*/
|
|
3284
|
+
/** Page → ServiceWorker: attach a handler link. The name is the one version 1 used. */
|
|
3285
|
+
const ATTACH_CALL = "UPDATE_COMMUNICATION_PORT";
|
|
3286
|
+
/** Page → ServiceWorker: remove a handler link now. */
|
|
3287
|
+
const DETACH_CALL = "webrun-http:detach";
|
|
3288
|
+
/** Page → ServiceWorker: stop routing to a link, let its requests finish, then remove it. */
|
|
3289
|
+
const DRAIN_CALL = "webrun-http:drain";
|
|
3290
|
+
/** Page → ServiceWorker: open a WebSocket to a handler. */
|
|
3291
|
+
const WS_CONNECT_CALL = "webrun-http:ws-connect";
|
|
3292
|
+
/** ServiceWorker → pages: attach your links again (the ServiceWorker restarted). */
|
|
3293
|
+
const NEED_LINKS_CALL = "webrun-http:need-links";
|
|
3294
|
+
//#endregion
|
|
3295
|
+
//#region src/sw/http-sw-dispatcher.ts
|
|
3296
|
+
/** One attached handler link, as the ServiceWorker holds it. */
|
|
3297
|
+
var HandlerEntry = class {
|
|
3298
|
+
key;
|
|
3299
|
+
id;
|
|
3300
|
+
owner;
|
|
3301
|
+
meta;
|
|
3302
|
+
link;
|
|
3303
|
+
ctl;
|
|
3304
|
+
clientId;
|
|
3305
|
+
ownerLock;
|
|
3306
|
+
draining = false;
|
|
3307
|
+
attachedAt = Date.now();
|
|
3308
|
+
sockets;
|
|
3309
|
+
stopWatch = () => {};
|
|
3310
|
+
closeUp;
|
|
3311
|
+
constructor(key, id, owner, meta, link, ctl, clientId, ownerLock) {
|
|
3312
|
+
this.key = key;
|
|
3313
|
+
this.id = id;
|
|
3314
|
+
this.owner = owner;
|
|
3315
|
+
this.meta = meta;
|
|
3316
|
+
this.link = link;
|
|
3317
|
+
this.ctl = ctl;
|
|
3318
|
+
this.clientId = clientId;
|
|
3319
|
+
this.ownerLock = ownerLock;
|
|
3320
|
+
this.sockets = new PortRendezvous(`s:${id}`);
|
|
3321
|
+
}
|
|
3322
|
+
get inflight() {
|
|
3323
|
+
return this.link.inflight;
|
|
3324
|
+
}
|
|
3325
|
+
};
|
|
3326
|
+
/** The reason requests fail with when their handler dies under them. */
|
|
3327
|
+
const HANDLER_LOST_MESSAGE = "The handler was lost while this request was in flight";
|
|
3328
|
+
const TIMED_OUT = Symbol("timed-out");
|
|
3329
|
+
/**
|
|
3330
|
+
* The same-origin ServiceWorker: routes `fetch` events under its scope to
|
|
3331
|
+
* handler links that pages attach — handlers in the pages themselves
|
|
3332
|
+
* (`SwHttpAdapter.register`) or in Dedicated Workers
|
|
3333
|
+
* (`SwHttpAdapter.attachWorker` + `serveHttpInWorker`).
|
|
3334
|
+
*
|
|
3335
|
+
* A url `<scope>/<key>/...` belongs to the handlers of `key`. Of those, the
|
|
3336
|
+
* `route` option picks one per request. Requests and responses stream with
|
|
3337
|
+
* backpressure in both directions, and an aborted fetch reaches the handler
|
|
3338
|
+
* as a cancellation (webrun-rpc + webrun-http-streams).
|
|
3339
|
+
*
|
|
3340
|
+
* Urls of keys this worker never served go to the network untouched: the
|
|
3341
|
+
* worker does not call `respondWith` for them.
|
|
3342
|
+
*
|
|
3343
|
+
* RESTARTS. The browser stops an idle ServiceWorker, and every port it held
|
|
3344
|
+
* dies with it. Nothing is persisted but the set of keys ever served: the
|
|
3345
|
+
* first request after a restart asks every window to attach its links again
|
|
3346
|
+
* (`NEED_LINKS`) and waits for them.
|
|
3347
|
+
*
|
|
3348
|
+
* LIVENESS. Each handler holds an owner lock; when it is granted to this
|
|
3349
|
+
* worker, the handler is gone and its requests in flight fail at once (502).
|
|
3350
|
+
* This worker holds a router lock that handlers watch the same way.
|
|
3351
|
+
*/
|
|
3352
|
+
var SwHttpDispatcher = class {
|
|
3353
|
+
self;
|
|
3354
|
+
log;
|
|
3355
|
+
options;
|
|
3356
|
+
table = new HandlerTable();
|
|
3357
|
+
/**
|
|
3358
|
+
* Keys that were served at some point on this worker (sticky, kept in
|
|
3359
|
+
* IndexedDB). Lets a fetch tell "a site url whose handler is gone → 404"
|
|
3360
|
+
* from "an unknown url under the scope → the network".
|
|
3361
|
+
*/
|
|
3362
|
+
claimedKeys = /* @__PURE__ */ new Set();
|
|
3363
|
+
/** The Web Lock this worker holds while it lives; handlers watch it. */
|
|
3364
|
+
routerLock;
|
|
3365
|
+
_routerHeld = Promise.resolve();
|
|
3366
|
+
_restored = Promise.resolve();
|
|
3367
|
+
_restoreSettled = false;
|
|
3368
|
+
_cleanup = [];
|
|
3369
|
+
_livenessTimer;
|
|
3370
|
+
_relinkRounds = /* @__PURE__ */ new Map();
|
|
3371
|
+
/** Keys whose last handler was drained: until the time stored, requests wait for the next. */
|
|
3372
|
+
_vacant = /* @__PURE__ */ new Map();
|
|
3373
|
+
constructor(options) {
|
|
3374
|
+
this.options = options;
|
|
3375
|
+
this.self = options.self;
|
|
3376
|
+
this.log = options.log ?? (() => {});
|
|
3377
|
+
if (locksAvailable()) this.routerLock = newLockName("webrun-http-router");
|
|
3378
|
+
}
|
|
3379
|
+
get scope() {
|
|
3380
|
+
return `${new URL("./", this.self.location.href)}`;
|
|
3381
|
+
}
|
|
3382
|
+
/** The key `url` belongs to: its first path segment under the scope. */
|
|
3383
|
+
keyOf(url) {
|
|
3384
|
+
const href = `${url}`;
|
|
3385
|
+
const scope = this.scope;
|
|
3386
|
+
if (!href.startsWith(scope)) return void 0;
|
|
3387
|
+
const key = href.substring(scope.length).replace(/[?#].*$/, "").split("/")[0];
|
|
3388
|
+
return key ? decodeURIComponent(key) : void 0;
|
|
3389
|
+
}
|
|
3390
|
+
/** Whether `key` has ever been served on this worker. */
|
|
1487
3391
|
isClaimedKey(key) {
|
|
1488
3392
|
return this.claimedKeys.has(key);
|
|
1489
3393
|
}
|
|
3394
|
+
/** Whether requests for `key` are this worker's to answer. */
|
|
3395
|
+
serves(key) {
|
|
3396
|
+
return this.claimedKeys.has(key) || this.table.all(key).length > 0;
|
|
3397
|
+
}
|
|
1490
3398
|
start() {
|
|
1491
|
-
const
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
...channelInfo,
|
|
1497
|
-
port,
|
|
1498
|
-
clientId
|
|
1499
|
-
});
|
|
1500
|
-
return { ...channelInfo };
|
|
1501
|
-
});
|
|
1502
|
-
this._cleanup = () => {
|
|
1503
|
-
stopClaims();
|
|
1504
|
-
stopPortUpdates();
|
|
3399
|
+
const self = this.self;
|
|
3400
|
+
if (this.routerLock) this._routerHeld = holdLock(this.routerLock).then(() => {});
|
|
3401
|
+
this._restored = this._restoreClaimedKeys();
|
|
3402
|
+
const latch = () => {
|
|
3403
|
+
this._restoreSettled = true;
|
|
1505
3404
|
};
|
|
1506
|
-
this.
|
|
1507
|
-
|
|
1508
|
-
this.
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
3405
|
+
this._restored.then(latch, latch);
|
|
3406
|
+
this._cleanup.push(handleClaimRequests(self), handleChannelCalls(self, ATTACH_CALL, (event, params, ...ports) => this._attach(event, params, ports)), handleChannelCalls(self, DETACH_CALL, (_event, params) => {
|
|
3407
|
+
const entry = this._find(params);
|
|
3408
|
+
if (!entry) return false;
|
|
3409
|
+
this._close(entry, new LinkLostError("The handler was detached"));
|
|
3410
|
+
return true;
|
|
3411
|
+
}), handleChannelCalls(self, DRAIN_CALL, async (_event, params) => {
|
|
3412
|
+
const entry = this._find(params);
|
|
3413
|
+
if (!entry) return false;
|
|
3414
|
+
this._vacant.set(entry.key, Date.now() + (this.options.attachTimeoutMs ?? 15e3));
|
|
3415
|
+
await this._retire(entry, params.ms ?? this.options.handoverMs ?? 5e3);
|
|
3416
|
+
return true;
|
|
3417
|
+
}), handleChannelCalls(self, WS_CONNECT_CALL, async (event, params) => {
|
|
3418
|
+
if (!this._isOwnClient(event)) throw new Error("Only this origin's pages may open sockets");
|
|
3419
|
+
const { url, protocols } = params;
|
|
3420
|
+
const connection = await this.connectWebSocket(url, protocols ?? []);
|
|
3421
|
+
return withTransfer(connection, [connection.port]);
|
|
3422
|
+
}));
|
|
3423
|
+
const onMessage = (event) => {
|
|
3424
|
+
const type = event.data?.type;
|
|
3425
|
+
if (type === "webrun-http:wake") event.waitUntil(this._askForLinks());
|
|
3426
|
+
else if (type === "webrun-http:keepalive") event.waitUntil(Promise.resolve());
|
|
3427
|
+
};
|
|
3428
|
+
self.addEventListener("message", onMessage);
|
|
3429
|
+
this._cleanup.push(() => self.removeEventListener("message", onMessage));
|
|
3430
|
+
const onInstall = (event) => {
|
|
3431
|
+
this.log("Skip waiting on install.");
|
|
3432
|
+
event.waitUntil(self.skipWaiting());
|
|
3433
|
+
};
|
|
3434
|
+
const onActivate = (event) => {
|
|
3435
|
+
this.log("Claim control over all clients.");
|
|
3436
|
+
event.waitUntil(self.clients.claim());
|
|
3437
|
+
};
|
|
3438
|
+
const onFetch = (event) => this._onFetch(event);
|
|
3439
|
+
self.addEventListener("install", onInstall);
|
|
3440
|
+
self.addEventListener("activate", onActivate);
|
|
3441
|
+
self.addEventListener("fetch", onFetch);
|
|
3442
|
+
this._cleanup.push(() => {
|
|
3443
|
+
self.removeEventListener("install", onInstall);
|
|
3444
|
+
self.removeEventListener("activate", onActivate);
|
|
3445
|
+
self.removeEventListener("fetch", onFetch);
|
|
1516
3446
|
});
|
|
1517
3447
|
}
|
|
1518
3448
|
async stop() {
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
}
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
const
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
3449
|
+
for (const cleanup of this._cleanup.splice(0)) cleanup();
|
|
3450
|
+
if (this._livenessTimer) clearInterval(this._livenessTimer);
|
|
3451
|
+
this._livenessTimer = void 0;
|
|
3452
|
+
for (const entry of this.table.entries()) this._close(entry, new LinkLostError("The ServiceWorker dispatcher stopped"));
|
|
3453
|
+
}
|
|
3454
|
+
/**
|
|
3455
|
+
* Answers `request` as a fetch under the scope would be: through the
|
|
3456
|
+
* handler its key routes to. A url outside the scope, or of a key this
|
|
3457
|
+
* worker never served, goes to the network.
|
|
3458
|
+
*/
|
|
3459
|
+
async dispatch(request) {
|
|
3460
|
+
const key = this.keyOf(request.url);
|
|
3461
|
+
if (key === void 0) return await fetch(request);
|
|
3462
|
+
await this._restored.catch(() => {});
|
|
3463
|
+
const entry = await this._acquire(request, key);
|
|
3464
|
+
if (entry === TIMED_OUT) return new Response(null, {
|
|
3465
|
+
status: 503,
|
|
3466
|
+
statusText: "Service Unavailable (no handler attached in time)"
|
|
3467
|
+
});
|
|
3468
|
+
if (!entry) {
|
|
3469
|
+
if (!this.serves(key)) return await fetch(request);
|
|
3470
|
+
return new Response(null, {
|
|
3471
|
+
status: 404,
|
|
3472
|
+
statusText: "Not Found (no active handler)"
|
|
1539
3473
|
});
|
|
1540
3474
|
}
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
3475
|
+
try {
|
|
3476
|
+
return await entry.link.send(request);
|
|
3477
|
+
} catch (error) {
|
|
3478
|
+
this.log("[dispatch] failed", key, error);
|
|
3479
|
+
return new Response(errorMessage(error), {
|
|
3480
|
+
status: 502,
|
|
3481
|
+
statusText: "Bad Gateway",
|
|
3482
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
3483
|
+
});
|
|
1549
3484
|
}
|
|
1550
|
-
await this._updateClientIds([]);
|
|
1551
3485
|
}
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
3486
|
+
/**
|
|
3487
|
+
* Opens a socket to the handler `url` routes to: the handler accepts or
|
|
3488
|
+
* refuses it like an HTTP upgrade, and the socket's port comes back. After
|
|
3489
|
+
* that the socket runs between the caller and the handler directly; this
|
|
3490
|
+
* worker is not on its data path.
|
|
3491
|
+
*/
|
|
3492
|
+
async connectWebSocket(url, protocols = [], headers) {
|
|
3493
|
+
const request = newWebSocketUpgradeRequest(url, {
|
|
3494
|
+
protocols,
|
|
3495
|
+
headers
|
|
3496
|
+
});
|
|
3497
|
+
const key = this.keyOf(request.url);
|
|
3498
|
+
if (key === void 0) throw new Error(`${url} is outside this ServiceWorker's scope`);
|
|
3499
|
+
await this._restored.catch(() => {});
|
|
3500
|
+
const entry = await this._acquire(request, key);
|
|
3501
|
+
if (!entry || entry === TIMED_OUT) throw new Error(`No handler serves ${url}`);
|
|
3502
|
+
if (!entry.ctl) throw new Error(`The handler of ${url} does not accept sockets`);
|
|
3503
|
+
const id = entry.sockets.newId();
|
|
3504
|
+
const answer = entry.sockets.wait(id, this.options.wsConnectTimeoutMs ?? 15e3, `the socket request for ${url}`);
|
|
3505
|
+
entry.ctl.postMessage({
|
|
3506
|
+
t: "ws-connect",
|
|
3507
|
+
id,
|
|
3508
|
+
url: request.url,
|
|
3509
|
+
protocols,
|
|
3510
|
+
headers
|
|
3511
|
+
});
|
|
3512
|
+
return await answer;
|
|
1557
3513
|
}
|
|
1558
|
-
|
|
1559
|
-
const
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
if (
|
|
1565
|
-
|
|
3514
|
+
_onFetch(event) {
|
|
3515
|
+
const request = event.request;
|
|
3516
|
+
const key = this.keyOf(request.url);
|
|
3517
|
+
if (key === void 0) return;
|
|
3518
|
+
if (this._restoreSettled) {
|
|
3519
|
+
if (this.serves(key)) event.respondWith(this.dispatch(request));
|
|
3520
|
+
else if (request.mode === "navigate") event.respondWith(fetch(request));
|
|
3521
|
+
return;
|
|
1566
3522
|
}
|
|
1567
|
-
|
|
1568
|
-
|
|
3523
|
+
event.respondWith((async () => {
|
|
3524
|
+
await this._restored.catch(() => {});
|
|
3525
|
+
if (!this.serves(key)) return await fetch(request);
|
|
3526
|
+
return await this.dispatch(request);
|
|
3527
|
+
})());
|
|
1569
3528
|
}
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
3529
|
+
async _attach(event, params, ports) {
|
|
3530
|
+
const clientId = event.source?.id;
|
|
3531
|
+
const [down, ...rest] = ports;
|
|
3532
|
+
if (!down) throw new Error("An attach carries at least one port");
|
|
3533
|
+
this.log("[attach]", clientId, params);
|
|
3534
|
+
if (params.wire === void 0) {
|
|
3535
|
+
const link = trackedLink((request) => sendHttpRequest(down, request), () => down.close());
|
|
3536
|
+
const id = clientId ?? crypto.randomUUID();
|
|
3537
|
+
this._add(new HandlerEntry(params.key, id, id, void 0, link, void 0, clientId, void 0));
|
|
3538
|
+
return { ...params };
|
|
3539
|
+
}
|
|
3540
|
+
if (params.wire !== "webrun-http-link/2") {
|
|
3541
|
+
for (const port of ports) port.close();
|
|
3542
|
+
throw new Error(`This ServiceWorker speaks ${HTTP_LINK_PROTOCOL}, the page ${params.wire}. Reload the page so that both run the same version of @statewalker/webrun-http-browser.`);
|
|
3543
|
+
}
|
|
3544
|
+
const ctl = params.ctl ? rest.shift() : void 0;
|
|
3545
|
+
const up = params.up ? rest.shift() : void 0;
|
|
3546
|
+
const streamTimeout = this.options.streamTimeout;
|
|
3547
|
+
const link = await connectHttpLink(down, { streamTimeout });
|
|
3548
|
+
const entry = new HandlerEntry(params.key, params.id ?? clientId ?? crypto.randomUUID(), params.owner ?? crypto.randomUUID(), params.meta, link, ctl, clientId, params.ownerLock);
|
|
3549
|
+
if (up) entry.closeUp = await serveHttpLink(up, (request) => this.dispatch(request), { streamTimeout });
|
|
3550
|
+
if (ctl) ctl.onmessage = (message) => this._onControl(entry, message.data);
|
|
3551
|
+
if (params.ownerLock) entry.stopWatch = watchLock(params.ownerLock, () => {
|
|
3552
|
+
this.log("[owner lost]", entry.key, entry.id);
|
|
3553
|
+
this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE));
|
|
3554
|
+
});
|
|
3555
|
+
this._add(entry);
|
|
3556
|
+
await this._routerHeld;
|
|
3557
|
+
return {
|
|
3558
|
+
accepted: HTTP_LINK_PROTOCOL,
|
|
3559
|
+
routerLock: this.routerLock
|
|
3560
|
+
};
|
|
1577
3561
|
}
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
});
|
|
3562
|
+
_add(entry) {
|
|
3563
|
+
this._vacant.delete(entry.key);
|
|
3564
|
+
const replaced = this.table.add(entry);
|
|
3565
|
+
if (replaced && replaced !== entry) this._retire(replaced, this.options.handoverMs ?? 5e3, false);
|
|
3566
|
+
this._claim(entry.key);
|
|
3567
|
+
if (entry.ownerLock) this._watchLiveness();
|
|
3568
|
+
}
|
|
3569
|
+
/**
|
|
3570
|
+
* The backup of the owner-lock watches: every `livenessCheckMs`, drops the
|
|
3571
|
+
* handlers whose owner lock is no longer held. Runs only while some handler
|
|
3572
|
+
* has an owner lock, and keeps nothing awake: a timer is not an event.
|
|
3573
|
+
*/
|
|
3574
|
+
_watchLiveness() {
|
|
3575
|
+
const period = this.options.livenessCheckMs ?? 5e3;
|
|
3576
|
+
if (this._livenessTimer || period <= 0) return;
|
|
3577
|
+
this._livenessTimer = setInterval(async () => {
|
|
3578
|
+
const watched = this.table.entries().filter((entry) => entry.ownerLock);
|
|
3579
|
+
if (watched.length === 0) {
|
|
3580
|
+
clearInterval(this._livenessTimer);
|
|
3581
|
+
this._livenessTimer = void 0;
|
|
3582
|
+
return;
|
|
1600
3583
|
}
|
|
1601
|
-
|
|
3584
|
+
const held = await heldLockNames();
|
|
3585
|
+
if (!held) return;
|
|
3586
|
+
for (const entry of watched) if (entry.ownerLock && !held.has(entry.ownerLock) && this.table.remove(entry)) {
|
|
3587
|
+
this.log("[owner gone]", entry.key, entry.id);
|
|
3588
|
+
this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE), false);
|
|
3589
|
+
}
|
|
3590
|
+
}, period);
|
|
3591
|
+
}
|
|
3592
|
+
/** The entry a drain or detach names, if its owner token still matches. */
|
|
3593
|
+
_find({ key, id, owner }) {
|
|
3594
|
+
const entry = this.table.get(key, id);
|
|
3595
|
+
return entry && entry.owner === owner ? entry : void 0;
|
|
3596
|
+
}
|
|
3597
|
+
/**
|
|
3598
|
+
* Stops routing to `entry`, lets its requests in flight run for up to `ms`,
|
|
3599
|
+
* then closes it. Requests that arrive meanwhile wait for the next owner.
|
|
3600
|
+
*/
|
|
3601
|
+
async _retire(entry, ms, inTable = true) {
|
|
3602
|
+
entry.draining = true;
|
|
3603
|
+
let timer;
|
|
3604
|
+
await Promise.race([entry.link.whenIdle(), new Promise((resolve) => {
|
|
3605
|
+
timer = setTimeout(resolve, ms);
|
|
3606
|
+
})]);
|
|
3607
|
+
clearTimeout(timer);
|
|
3608
|
+
this._close(entry, new LinkLostError("The handler was drained"), inTable);
|
|
3609
|
+
}
|
|
3610
|
+
_close(entry, reason, inTable = true) {
|
|
3611
|
+
if (inTable) this.table.remove(entry);
|
|
3612
|
+
entry.stopWatch();
|
|
3613
|
+
entry.sockets.failAll(reason);
|
|
3614
|
+
entry.link.close(reason);
|
|
3615
|
+
entry.closeUp?.().catch(() => {});
|
|
3616
|
+
if (entry.ctl) {
|
|
3617
|
+
entry.ctl.onmessage = null;
|
|
3618
|
+
entry.ctl.close();
|
|
3619
|
+
}
|
|
3620
|
+
}
|
|
3621
|
+
/**
|
|
3622
|
+
* The handler for `request`: picked by `route` among the live handlers of
|
|
3623
|
+
* its key, waiting for one when there is none.
|
|
3624
|
+
*/
|
|
3625
|
+
async _acquire(request, key) {
|
|
3626
|
+
const picked = await this._pick(request, key);
|
|
3627
|
+
if (picked) return picked;
|
|
3628
|
+
if (this.table.all(key).length > 0) return await this.table.waitFor(key, this.options.attachTimeoutMs ?? 15e3, this.table.live(key).length > 0) ? await this._pick(request, key) ?? TIMED_OUT : TIMED_OUT;
|
|
3629
|
+
const vacantUntil = this._vacant.get(key) ?? 0;
|
|
3630
|
+
if (vacantUntil > Date.now()) return await this.table.waitFor(key, vacantUntil - Date.now()) ? await this._pick(request, key) ?? TIMED_OUT : TIMED_OUT;
|
|
3631
|
+
if (!this.serves(key)) return void 0;
|
|
3632
|
+
await this._askForLinks(key);
|
|
3633
|
+
return await this._pick(request, key);
|
|
3634
|
+
}
|
|
3635
|
+
async _pick(request, key) {
|
|
3636
|
+
let live = this.table.live(key);
|
|
3637
|
+
for (const entry of live) {
|
|
3638
|
+
if (entry.ownerLock || !entry.clientId) continue;
|
|
3639
|
+
if (!await this.self.clients.get(entry.clientId)) this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE));
|
|
3640
|
+
}
|
|
3641
|
+
live = this.table.live(key);
|
|
3642
|
+
if (live.length === 0) return void 0;
|
|
3643
|
+
return (this.options.route ?? leastInflightRoute)(request, key, live);
|
|
3644
|
+
}
|
|
3645
|
+
/**
|
|
3646
|
+
* Asks every window to attach its links again, and waits until a handler
|
|
3647
|
+
* for `key` is back, every window answered, or `relinkTimeoutMs` passed.
|
|
3648
|
+
* At most one round per key every 10 s: a key whose tab is simply gone
|
|
3649
|
+
* should not cost every request the wait.
|
|
3650
|
+
*/
|
|
3651
|
+
_askForLinks(key = "") {
|
|
3652
|
+
const round = this._relinkRounds.get(key);
|
|
3653
|
+
if (round && Date.now() - round.at < 1e4) return round.done;
|
|
3654
|
+
const done = this._linkRound(key);
|
|
3655
|
+
this._relinkRounds.set(key, {
|
|
3656
|
+
at: Date.now(),
|
|
3657
|
+
done
|
|
3658
|
+
});
|
|
3659
|
+
return done;
|
|
3660
|
+
}
|
|
3661
|
+
async _linkRound(key) {
|
|
3662
|
+
const timeout = this.options.relinkTimeoutMs ?? 3e3;
|
|
3663
|
+
const windows = await this.self.clients.matchAll({
|
|
3664
|
+
type: "window",
|
|
3665
|
+
includeUncontrolled: true
|
|
3666
|
+
});
|
|
3667
|
+
this.log("[need-links]", key, windows.length);
|
|
3668
|
+
const params = { routerLock: this.routerLock };
|
|
3669
|
+
const pending = new Set(windows);
|
|
3670
|
+
const answered = Promise.allSettled(windows.map((client) => callChannel(client, NEED_LINKS_CALL, params).then(() => pending.delete(client))));
|
|
3671
|
+
let timer;
|
|
3672
|
+
const timedOut = new Promise((resolve) => {
|
|
3673
|
+
timer = setTimeout(resolve, timeout);
|
|
3674
|
+
});
|
|
3675
|
+
await Promise.race([answered, timedOut]);
|
|
3676
|
+
clearTimeout(timer);
|
|
3677
|
+
for (const client of pending) this._askLegacyPage(client);
|
|
3678
|
+
}
|
|
3679
|
+
/** Asks a version-1 page for a fresh port, as version 1's worker did. */
|
|
3680
|
+
_askLegacyPage(client) {
|
|
3681
|
+
const channel = new MessageChannel();
|
|
3682
|
+
callChannel(client, ATTACH_CALL, {}, channel.port2).then((info) => {
|
|
3683
|
+
if (!info?.key || info.wire !== void 0) return;
|
|
3684
|
+
const link = trackedLink((request) => sendHttpRequest(channel.port1, request), () => channel.port1.close());
|
|
3685
|
+
this._add(new HandlerEntry(info.key, client.id, client.id, void 0, link, void 0, client.id, void 0));
|
|
3686
|
+
}, () => channel.port1.close());
|
|
3687
|
+
}
|
|
3688
|
+
_onControl(entry, message) {
|
|
3689
|
+
if (!message || typeof message !== "object") return;
|
|
3690
|
+
switch (message.t) {
|
|
3691
|
+
case "ws-accept":
|
|
3692
|
+
if (!entry.sockets.settle(message.id, {
|
|
3693
|
+
port: message.port,
|
|
3694
|
+
protocol: message.protocol
|
|
3695
|
+
})) message.port.close();
|
|
3696
|
+
return;
|
|
3697
|
+
case "ws-refuse":
|
|
3698
|
+
entry.sockets.fail(message.id, new Error(message.message));
|
|
3699
|
+
return;
|
|
3700
|
+
case "ws-open":
|
|
3701
|
+
this.connectWebSocket(message.url, message.protocols).then(({ port, protocol }) => entry.ctl?.postMessage({
|
|
3702
|
+
t: "ws-opened",
|
|
3703
|
+
id: message.id,
|
|
3704
|
+
protocol,
|
|
3705
|
+
port
|
|
3706
|
+
}, [port]), (error) => entry.ctl?.postMessage({
|
|
3707
|
+
t: "ws-failed",
|
|
3708
|
+
id: message.id,
|
|
3709
|
+
message: errorMessage(error)
|
|
3710
|
+
}));
|
|
3711
|
+
return;
|
|
3712
|
+
}
|
|
3713
|
+
}
|
|
3714
|
+
_isOwnClient(event) {
|
|
3715
|
+
const source = event.source;
|
|
3716
|
+
if (!source?.url) return false;
|
|
3717
|
+
try {
|
|
3718
|
+
return new URL(source.url).origin === this.self.location.origin;
|
|
3719
|
+
} catch {
|
|
3720
|
+
return false;
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
async _claim(key) {
|
|
3724
|
+
if (!key || this.claimedKeys.has(key)) return;
|
|
3725
|
+
this.claimedKeys.add(key);
|
|
3726
|
+
try {
|
|
3727
|
+
await set("claimedKeys", [...this.claimedKeys].sort());
|
|
3728
|
+
} catch (error) {
|
|
3729
|
+
this.log("[claimedKeys] not stored", error);
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
async _restoreClaimedKeys() {
|
|
3733
|
+
const stored = await get("claimedKeys") ?? [];
|
|
3734
|
+
for (const key of stored) this.claimedKeys.add(key);
|
|
1602
3735
|
}
|
|
1603
3736
|
};
|
|
3737
|
+
/**
|
|
3738
|
+
* Starts the same-origin dispatcher in a ServiceWorker. Returns a function
|
|
3739
|
+
* that stops it.
|
|
3740
|
+
*/
|
|
1604
3741
|
function startHttpDispatcher(options) {
|
|
1605
3742
|
const dispatcher = new SwHttpDispatcher(options);
|
|
1606
3743
|
dispatcher.start();
|
|
@@ -1611,8 +3748,9 @@
|
|
|
1611
3748
|
//#endregion
|
|
1612
3749
|
//#region src/sw-worker.ts
|
|
1613
3750
|
startHttpDispatcher({
|
|
1614
|
-
|
|
1615
|
-
|
|
3751
|
+
log: console.log,
|
|
3752
|
+
...self.HTTP_DISPATCHER_OPTIONS,
|
|
3753
|
+
self
|
|
1616
3754
|
});
|
|
1617
3755
|
//#endregion
|
|
1618
3756
|
})();
|