@panyam/tsappkit 0.7.4 → 0.7.6

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.
@@ -139,8 +139,9 @@ interface LaneOptions {
139
139
  * maxMemoryBytes. The stats are taken after a collection, so heap.heapAlloc is the live heap,
140
140
  * and a worker whose live heap is near its memory would come back just as large; replacing one
141
141
  * pays when memoryBytes is far above it. With maxMemoryBytes as well, the lane restarts only when
142
- * the worker is past that limit and this returns true. heap is absent for a wasm built against
143
- * goapplib before 0.7.4.
142
+ * the worker is past that limit and this returns true, and a worker under the limit isn't asked
143
+ * to collect. Without maxMemoryBytes every idle moment pays a collection (187 ms on a 377 MB
144
+ * live heap in agni), so set both. heap is absent for a wasm built against goapplib before 0.7.4.
144
145
  */
145
146
  restartIf?: (stats: WorkerStats) => boolean;
146
147
  /** Called when the lane replaces its worker for maxMemoryBytes or restartIf, with its stats. */
@@ -139,8 +139,9 @@ interface LaneOptions {
139
139
  * maxMemoryBytes. The stats are taken after a collection, so heap.heapAlloc is the live heap,
140
140
  * and a worker whose live heap is near its memory would come back just as large; replacing one
141
141
  * pays when memoryBytes is far above it. With maxMemoryBytes as well, the lane restarts only when
142
- * the worker is past that limit and this returns true. heap is absent for a wasm built against
143
- * goapplib before 0.7.4.
142
+ * the worker is past that limit and this returns true, and a worker under the limit isn't asked
143
+ * to collect. Without maxMemoryBytes every idle moment pays a collection (187 ms on a 377 MB
144
+ * live heap in agni), so set both. heap is absent for a wasm built against goapplib before 0.7.4.
144
145
  */
145
146
  restartIf?: (stats: WorkerStats) => boolean;
146
147
  /** Called when the lane replaces its worker for maxMemoryBytes or restartIf, with its stats. */
@@ -296,15 +296,21 @@ function startLane(opts, lane = {}) {
296
296
  let inFlight = 0;
297
297
  const checksMemory = lane.maxMemoryBytes !== void 0 || lane.restartIf !== void 0;
298
298
  const checkMemory = async (w, of) => {
299
+ const idle = () => inFlight === 0 && current === of && !closed;
299
300
  let stats;
300
301
  try {
301
- stats = await workerStats(w, { gc: lane.restartIf !== void 0 });
302
+ if (lane.maxMemoryBytes !== void 0) {
303
+ stats = await workerStats(w);
304
+ if (stats.memoryBytes <= lane.maxMemoryBytes || !idle()) return;
305
+ }
306
+ if (lane.restartIf) {
307
+ stats = await workerStats(w, { gc: true });
308
+ if (!idle() || !lane.restartIf(stats)) return;
309
+ }
302
310
  } catch {
303
311
  return;
304
312
  }
305
- if (lane.maxMemoryBytes !== void 0 && stats.memoryBytes <= lane.maxMemoryBytes) return;
306
- if (inFlight !== 0 || current !== of || closed) return;
307
- if (lane.restartIf && !lane.restartIf(stats)) return;
313
+ if (!stats) return;
308
314
  lane.onRestart?.(stats);
309
315
  void replace(w, new Error("wasm host lane: restarted past its memory limit")).catch(() => {
310
316
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/wasmhost/client.ts","../../src/wasmhost/drop.ts","../../src/wasmhost/lane.ts"],"names":["abortReason"],"mappings":";;;AAsBA,IAAM,UAAN,MAAc;AAAA,EAQZ,YAAoB,MAAA,EAAgB;AAAhB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAPpB,IAAA,IAAA,CAAQ,IAAA,GAAO,CAAA;AACf,IAAA,IAAA,CAAQ,OAAA,uBAAc,GAAA,EAGpB;AACF,IAAA,IAAA,CAAQ,IAAA,GAAqB,IAAA;AAG3B,IAAA,MAAA,CAAO,gBAAA,CAAiB,SAAA,EAAW,CAAC,EAAA,KAAyD;AAC3F,MAAA,MAAM,IAAI,EAAA,CAAG,IAAA;AACb,MAAA,IAAI,YAAY,CAAA,EAAG;AACjB,QAAA,IAAA,CAAK,KAAK,IAAI,KAAA,CAAM,cAAc,CAAA,CAAE,MAAM,EAAE,CAAC,CAAA;AAAA,MAC/C,CAAA,MAAA,IAAW,WAAW,CAAA,EAAG;AACvB,QAAA,IAAA,CAAK,QAAQ,GAAA,CAAI,CAAA,CAAE,EAAE,CAAA,EAAG,UAAU,CAAC,CAAA;AAAA,MACrC,CAAA,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AA;AAAA,IACH,CAAA;AAAA,IACA,QAAQ,MAAM,OAAA;AAAA,IACd,MAAM,OAAA,GAAU;AACd,MAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,KAAA,CAAM,MAAM,MAAS,CAAA;AAC/C,MAAA,OAAO,GAAA,GAAM,QAAQ,GAAA,EAAK,IAAI,MAAM,2BAA2B,CAAC,IAAI,IAAA,EAAK,CAAA;AAAA,IAC3E,CAAA;AAAA,IACA,KAAA,GAAQ;AACN,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,KAAK,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,SAAA,CAAU,CAAA,EAAG,IAAI,KAAA,CAAM,wBAAwB,CAAC,CAAA,EAAG,MAAM;AAAA,MAAC,CAAC,CAAA;AAAA,IACtF;AAAA,GACF;AACF;AAEA,SAASA,aAAY,MAAA,EAA8B;AACjD,EAAA,OAAO,MAAA,CAAO,MAAA,IAAU,IAAI,YAAA,CAAa,6BAA6B,YAAY,CAAA;AACpF","file":"index.js","sourcesContent":["// The page's side of a wasm host worker (goapplib issue 32). startWorker loads the app's Go wasm in\n// a Web Worker; workerFetch is a fetch to hand a Connect transport, so the app's generated clients\n// talk to the worker exactly as they would to a server; mountFiles pushes files in before the\n// requests that read them.\nimport type { Files, HeapStats, HostChunk, HostReply, HostRequest, HostStatus } from \"./protocol\";\n\nexport type { Files } from \"./protocol\";\n\n/** Where the worker's pieces are served, and the global name the Go side exports under. */\nexport interface StartWorkerOptions {\n /** The built worker script, @panyam/tsappkit/wasmhost/worker.js, as your bundler serves it. */\n worker: string | URL;\n /** The Go wasm build. */\n wasm: string | URL;\n /** Go's wasm_exec.js, from `$(go env GOROOT)/lib/wasm`, matching the Go that built the wasm. */\n exec: string | URL;\n /** The ns the Go program passed to wasmhost.Serve. */\n ns: string;\n}\n\ntype Unsent = HostRequest extends infer R ? (R extends HostRequest ? Omit<R, \"id\"> : never) : never;\n\nclass Channel {\n private next = 1;\n private pending = new Map<\n number,\n { resolve: (r: HostReply) => void; reject: (e: Error) => void; onChunk?: (c: HostChunk) => void }\n >();\n private dead: Error | null = null;\n\n constructor(private worker: Worker) {\n worker.addEventListener(\"message\", (ev: MessageEvent<HostReply | HostStatus | HostChunk>) => {\n const m = ev.data;\n if (\"exited\" in m) {\n this.fail(new Error(`wasm host: ${m.exited}`));\n } else if (\"chunk\" in m) {\n this.pending.get(m.id)?.onChunk?.(m);\n } else if (\"id\" in m) {\n this.pending.get(m.id)?.resolve(m);\n this.pending.delete(m.id);\n }\n });\n worker.addEventListener(\"error\", (ev: ErrorEvent) => this.fail(new Error(`wasm host worker: ${ev.message}`)));\n }\n\n /** Sends req and returns its id with the final reply; chunks before it go to onChunk. */\n start(req: Unsent, transfer: Transferable[], onChunk?: (c: HostChunk) => void): { id: number; done: Promise<HostReply> } {\n const id = this.next++;\n if (this.dead) return { id, done: Promise.reject(this.dead) };\n const done = new Promise<HostReply>((resolve, reject) => {\n this.pending.set(id, { resolve, reject, onChunk });\n this.worker.postMessage({ ...req, id }, transfer);\n });\n return { id, done };\n }\n\n call(req: Unsent, transfer: Transferable[]): Promise<HostReply> {\n return this.start(req, transfer).done;\n }\n\n fail(err: Error) {\n this.dead = err;\n for (const p of this.pending.values()) p.reject(err);\n this.pending.clear();\n }\n}\n\nconst channels = new WeakMap<Worker, Channel>();\n\n/**\n * Terminates worker and rejects every request still waiting on it with `err`, which terminate\n * alone wouldn't do: a terminated worker never replies, so its pending requests would wait forever.\n * For lane.ts; not exported from the package.\n */\nexport function endWorker(worker: Worker, err: Error): void {\n channels.get(worker)?.fail(err);\n worker.terminate();\n}\n\nfunction channel(worker: Worker): Channel {\n let c = channels.get(worker);\n if (!c) {\n c = new Channel(worker);\n channels.set(worker, c);\n }\n return c;\n}\n\n/**\n * Starts the worker and resolves with it once the Go program has installed its exports, or rejects\n * with why it couldn't load (and terminates it, since it can't answer anything). Relative URLs\n * resolve against the page, not the worker script.\n */\nexport function startWorker(opts: StartWorkerOptions): Promise<Worker> {\n const abs = (u: string | URL) => new URL(u, location.href).href;\n const url = new URL(abs(opts.worker));\n url.searchParams.set(\"wasm\", abs(opts.wasm));\n url.searchParams.set(\"exec\", abs(opts.exec));\n url.searchParams.set(\"ns\", opts.ns);\n const worker = new Worker(url);\n channel(worker);\n return new Promise((resolve, reject) => {\n const onMessage = (ev: MessageEvent<HostStatus | HostReply>) => {\n const m = ev.data;\n if (!(\"ready\" in m)) return;\n worker.removeEventListener(\"message\", onMessage);\n if (m.ready) {\n resolve(worker);\n return;\n }\n worker.terminate();\n reject(new Error(`wasm host failed to load: ${m.error}`));\n };\n worker.addEventListener(\"message\", onMessage);\n worker.addEventListener(\n \"error\",\n (ev: ErrorEvent) => {\n worker.terminate();\n reject(new Error(`wasm host worker: ${ev.message}`));\n },\n { once: true },\n );\n });\n}\n\n// Statuses whose Response must have no body.\nconst NULL_BODY = new Set([101, 103, 204, 205, 304]);\n\n/**\n * A fetch that answers in the worker, for `createConnectTransport({ baseUrl, fetch: workerFetch(worker) })`.\n * Only the path and query reach the worker, so baseUrl can be anything absolute, such as\n * location.origin. It rejects if the worker reports an error (no handler, a failed build, a handler\n * panic) and resolves with any HTTP status the handler chose.\n *\n * A handler that flushes (http.Flusher) streams: the Response resolves at its first flush, and its\n * body delivers each flush as it happens, even from a Go loop that never yields, then the rest\n * when the handler returns. Aborting the request (init.signal) rejects it, or errors a body that's\n * already streaming, and cancels the handler's context; a handler sees that the next time it checks\n * ctx, which a loop that never yields to JS doesn't get to do (a lane ends such a worker instead).\n * Once the body is streaming, Chrome's text() and json() report the abort as \"TypeError: Failed to\n * fetch\" rather than an AbortError, so tell an abort from a failure by signal.aborted.\n */\nexport function workerFetch(worker: Worker): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n const c = channel(worker);\n return async (input, init) => {\n const req = new Request(input, init);\n const signal = req.signal;\n if (signal.aborted) throw abortReason(signal);\n const buf = new Uint8Array(await req.arrayBuffer());\n const body = buf.byteLength ? buf : null;\n const headers: Record<string, string> = {};\n req.headers.forEach((v, k) => (headers[k] = v));\n const u = new URL(req.url);\n\n return new Promise<Response>((resolve, reject) => {\n let stream: ReadableStreamDefaultController<Uint8Array> | undefined;\n let settled = false;\n const fail = (err: unknown) => {\n if (settled) return;\n settled = true;\n if (stream) stream.error(err);\n else reject(err);\n };\n const { id, done } = c.start(\n { kind: \"http\", method: req.method, url: u.pathname + u.search, headers, body },\n body ? [body.buffer] : [],\n (chunk) => {\n if (settled) return;\n if (!stream) {\n const status = chunk.status ?? 200;\n const rs = new ReadableStream<Uint8Array>({ start: (ctl) => void (stream = ctl) });\n resolve(new Response(NULL_BODY.has(status) ? null : rs, { status, headers: chunk.headers }));\n }\n if (chunk.body.byteLength) stream!.enqueue(chunk.body);\n },\n );\n const onAbort = () => {\n void c.call({ kind: \"cancel\", target: id }, []).catch(() => {});\n fail(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n done.then(\n (reply) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (!reply.ok) return fail(new Error(reply.error));\n if (settled) return;\n settled = true;\n if (stream) {\n if (reply.body?.byteLength) stream.enqueue(reply.body);\n stream.close();\n return;\n }\n const status = reply.status ?? 200;\n const resBody = NULL_BODY.has(status) ? null : ((reply.body ?? null) as BodyInit | null);\n resolve(new Response(resBody, { status, headers: reply.headers }));\n },\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n fail(err);\n },\n );\n });\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n\n/**\n * A fetch like workerFetch's, except that each call starts a fresh worker from `opts`, sends it that\n * one request, and terminates it once the response is in, whether the request succeeded or not.\n * Ending the worker is the only way to give its wasm memory back to the browser, since wasm memory\n * never shrinks, so route a request with a big transient peak (an ingest that parses a large input\n * on the way to a small result) through this, and have it leave its result in the shared Cache\n * (Go's wasmhost.BrowserCache) for the long-lived worker to load. Every worker for the same `ns`\n * sees the same cache.\n *\n * Each call pays for a worker start and a wasm instantiate, a few hundred ms, so it's for jobs\n * that take seconds, not for ordinary requests. The worker ends when the response's body has been\n * read to the end, fails, or is cancelled, so a streamed body isn't cut short; read or cancel the\n * body, or the worker stays up.\n */\nexport function oneShotFetch(opts: StartWorkerOptions): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n return async (input, init) => {\n const worker = await startWorker(opts);\n let res: Response;\n try {\n res = await workerFetch(worker)(input, init);\n } catch (err) {\n worker.terminate();\n throw err;\n }\n return untilBodyEnds(res, () => worker.terminate());\n };\n}\n\n/**\n * res with `end` called once its body has been read to the end, has failed, or has been\n * cancelled (or at once, for a response without a body). For oneShotFetch and lanes, which must\n * not let go of a worker while its streamed body is still arriving. Not exported from the package.\n */\nexport function untilBodyEnds(res: Response, end: () => void): Response {\n if (!res.body) {\n end();\n return res;\n }\n const reader = res.body.getReader();\n const body = new ReadableStream<Uint8Array>({\n async pull(ctl) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n ctl.close();\n end();\n } else {\n ctl.enqueue(value);\n }\n } catch (err) {\n end();\n ctl.error(err);\n }\n },\n cancel(reason) {\n end();\n return reader.cancel(reason);\n },\n });\n return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });\n}\n\n/**\n * Replaces the mount `name` with `files`. The buffers are transferred to the worker, not copied, so\n * each Uint8Array is empty here afterwards; copy first anything the page still needs. Resolves once\n * the worker has mounted them (and, for a rebuild-mode host, rebuilt its handler).\n */\nexport function mountFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"mount\", name, files);\n}\n\n/**\n * Adds `files` to the mount `name`, keeping the files it already holds; a file at a path the mount\n * already has is replaced, and a missing mount is created. This suits a page that brings files in a\n * piece at a time, since it only sends what's new. The worker checks the whole batch first, so a\n * rejection (a path that is already a directory, say) leaves the mount as it was. Buffers are\n * transferred as with mountFiles.\n */\nexport function addFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"add\", name, files);\n}\n\nasync function sendFiles(worker: Worker, kind: \"mount\" | \"add\", name: string, files: Files): Promise<void> {\n const transfer = new Set<ArrayBuffer>();\n for (const b of Object.values(files)) {\n // A tag check rather than instanceof, which fails for a buffer from another realm (an iframe),\n // and a SharedArrayBuffer can't be transferred.\n if (Object.prototype.toString.call(b.buffer) === \"[object ArrayBuffer]\") transfer.add(b.buffer as ArrayBuffer);\n }\n const reply = await channel(worker).call({ kind, name, files }, [...transfer]);\n if (!reply.ok) throw new Error(reply.error);\n}\n\n/**\n * The bytes of linear memory the worker's wasm holds. Wasm memory grows and never shrinks, so this\n * is the peak the engine has needed so far, which is what an app weighs before giving a browser a\n * bigger job.\n */\nexport async function workerMemory(worker: Worker): Promise<number> {\n const reply = await channel(worker).call({ kind: \"stats\" }, []);\n if (!reply.ok) throw new Error(reply.error);\n return reply.memoryBytes ?? 0;\n}\n\n/** What workerStats reports about a worker. */\nexport interface WorkerStats {\n /** The wasm linear memory's size, as workerMemory: the peak so far, since it never shrinks. */\n memoryBytes: number;\n /**\n * The Go heap inside it, absent when the wasm was built against goapplib before 0.7.4. Far below\n * memoryBytes means a fresh worker would come back smaller; near it means one would come back\n * just as large.\n */\n heap?: HeapStats;\n}\n\n/**\n * The worker's wasm memory and its Go heap. With `gc`, the worker collects garbage first, so\n * heap.heapAlloc is what it holds live rather than live plus garbage, at the cost of a pause; it\n * waits behind whatever the worker is running, like any request.\n */\nexport async function workerStats(worker: Worker, opts: { gc?: boolean } = {}): Promise<WorkerStats> {\n const reply = await channel(worker).call({ kind: \"stats\", gc: opts.gc === true }, []);\n if (!reply.ok) throw new Error(reply.error);\n return { memoryBytes: reply.memoryBytes ?? 0, heap: reply.heap };\n}\n\n/** Removes the mount `name`. Removing a name that isn't mounted succeeds. */\nexport async function unmountFiles(worker: Worker, name: string): Promise<void> {\n const reply = await channel(worker).call({ kind: \"unmount\", name }, []);\n if (!reply.ok) throw new Error(reply.error);\n}\n","// Turning what a user drops or picks into the {path: bytes} map mountFiles takes. The bytes are\n// read here, before any request, because the Go side can't wait on File.arrayBuffer() mid-request.\nimport type { Files } from \"./protocol\";\n\n// The parts of the File and Directory Entries API used here. Chromium, Firefox and Safari all ship\n// it under the webkit prefix.\ninterface Entry {\n isFile: boolean;\n isDirectory: boolean;\n fullPath: string;\n}\ninterface FileEntry extends Entry {\n file(ok: (f: File) => void, err: (e: unknown) => void): void;\n}\ninterface DirectoryEntry extends Entry {\n createReader(): { readEntries(ok: (es: Entry[]) => void, err: (e: unknown) => void): void };\n}\n\n/**\n * Reads a drop into files keyed by path. A dropped folder keeps its own name as the first path\n * element (\"design/board.edn\"), and dropped loose files sit at the top. Entries the browser can't\n * read as files or folders are skipped.\n */\nexport async function filesFromDrop(dt: DataTransfer): Promise<Files> {\n const entries: Entry[] = [];\n const loose: File[] = [];\n for (const item of Array.from(dt.items)) {\n if (item.kind !== \"file\") continue;\n const entry = (item as DataTransferItem & { webkitGetAsEntry?: () => Entry | null }).webkitGetAsEntry?.();\n if (entry) entries.push(entry);\n else {\n const f = item.getAsFile();\n if (f) loose.push(f);\n }\n }\n const out: Files = {};\n await Promise.all([\n ...entries.map((e) => readEntry(e, out)),\n ...loose.map(async (f) => {\n out[f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n ]);\n return out;\n}\n\n/**\n * Reads an `<input type=\"file\" webkitdirectory>` (or `multiple`) selection into files keyed by\n * path. Folder picks use each file's webkitRelativePath, which starts with the folder's name.\n */\nexport async function filesFromFileList(list: FileList | File[]): Promise<Files> {\n const out: Files = {};\n await Promise.all(\n Array.from(list).map(async (f) => {\n out[f.webkitRelativePath || f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n );\n return out;\n}\n\nasync function readEntry(entry: Entry, out: Files): Promise<void> {\n if (entry.isFile) {\n const f = await new Promise<File>((ok, err) => (entry as FileEntry).file(ok, err));\n out[entry.fullPath.replace(/^\\/+/, \"\")] = new Uint8Array(await f.arrayBuffer());\n return;\n }\n if (!entry.isDirectory) return;\n const reader = (entry as DirectoryEntry).createReader();\n // readEntries returns a batch at a time (100 in Chromium) and an empty batch at the end.\n for (;;) {\n const batch = await new Promise<Entry[]>((ok, err) => reader.readEntries(ok, err));\n if (batch.length === 0) return;\n await Promise.all(batch.map((e) => readEntry(e, out)));\n }\n}\n","// Lanes (goapplib issue 80): more than one worker for one wasm service, with the app routing\n// requests by kind, so a quick request never waits behind a long one. Go's wasm target runs one\n// thread per worker, and a job that never yields keeps that thread busy, so neither a second\n// request nor an abort can reach it. A lane holds one worker it can replace: aborting a request\n// on it terminates the worker, which is the only way to stop a job that never yields, and starts\n// a fresh one, warmed from the shared Cache by the app's warm function.\nimport { endWorker, startWorker, untilBodyEnds, workerFetch, workerStats, type StartWorkerOptions, type WorkerStats } from \"./client\";\n\ntype Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface LaneOptions {\n /**\n * Runs on each new worker before the lane hands it a request: typically a request that loads\n * the service's state from the cache (wasmhost.BrowserCache), so a replacement worker answers\n * like the one it replaced. A warm that throws ends that worker, and the error is what the next\n * request gets; the request after it starts another worker.\n */\n warm?: (fetch: Fetch) => Promise<unknown>;\n /**\n * A memory limit for the lane's worker, in bytes of wasm memory (workerMemory). Wasm memory never\n * shrinks, so a long-lived worker creeps up through requests that each allocate and drop some.\n * When a request finishes (its body read to the end, or failed) and the lane has nothing else\n * in flight, the lane asks the worker how much it holds, and past this limit replaces it with a\n * fresh one, warmed as on an abort. It never interrupts a request, so a lane that's never idle\n * never restarts, and a response whose body nobody reads keeps the lane busy. Size it above what\n * the warmed state needs, or the lane restarts after every request.\n */\n maxMemoryBytes?: number;\n /**\n * Decides from the worker's stats whether to replace it, checked at the same idle moments as\n * maxMemoryBytes. The stats are taken after a collection, so heap.heapAlloc is the live heap,\n * and a worker whose live heap is near its memory would come back just as large; replacing one\n * pays when memoryBytes is far above it. With maxMemoryBytes as well, the lane restarts only when\n * the worker is past that limit and this returns true. heap is absent for a wasm built against\n * goapplib before 0.7.4.\n */\n restartIf?: (stats: WorkerStats) => boolean;\n /** Called when the lane replaces its worker for maxMemoryBytes or restartIf, with its stats. */\n onRestart?: (why: WorkerStats) => void;\n}\n\n/** One replaceable worker. See startLane. */\nexport interface Lane {\n /**\n * A fetch for a Connect transport, like workerFetch, answered by the lane's current worker.\n * Aborting a request (init.signal) rejects it with the signal's reason at once (or errors its\n * body, if it's already streaming), terminates the worker, and starts and warms a new one; other\n * requests still waiting on the old worker are rejected too. A request made meanwhile waits for\n * the new worker.\n */\n fetch: Fetch;\n /** The lane's current worker, once it's started and warmed. */\n worker(): Promise<Worker>;\n /** Replaces the worker, as an abort does, and resolves once the new one is warm. */\n restart(): Promise<void>;\n /** Terminates the worker. Requests after this reject. */\n close(): void;\n}\n\n/**\n * Starts a lane: a worker from `opts`, warmed with `lane.warm`, that the lane replaces whenever a\n * request on it is aborted. Give each kind of request its own lane (a \"serve\" lane for quick\n * queries, a \"jobs\" lane for long jobs) by building each client's transport on that lane's fetch.\n * Every lane of one ns shares the same Cache, which is how a replacement or a second lane gets the\n * state without rebuilding it.\n */\nexport function startLane(opts: StartWorkerOptions, lane: LaneOptions = {}): Lane {\n let closed = false;\n let current!: Promise<Worker>;\n let failed = false;\n\n const boot = () => {\n failed = false;\n const p: Promise<Worker> = startWorker(opts).then(async (w) => {\n if (lane.warm) {\n try {\n await lane.warm(workerFetch(w));\n } catch (err) {\n endWorker(w, err instanceof Error ? err : new Error(String(err)));\n throw err;\n }\n }\n return w;\n });\n p.catch(() => {\n if (current === p) failed = true;\n });\n current = p;\n return p;\n };\n\n const replace = (old: Worker, why: Error) => {\n endWorker(old, why);\n return boot();\n };\n\n let inFlight = 0;\n const checksMemory = lane.maxMemoryBytes !== undefined || lane.restartIf !== undefined;\n // Runs when the lane goes idle. A request that starts while workerStats is out means the lane\n // isn't idle any more, so the restart waits for the next idle moment.\n const checkMemory = async (w: Worker, of: Promise<Worker>) => {\n let stats: WorkerStats;\n try {\n stats = await workerStats(w, { gc: lane.restartIf !== undefined });\n } catch {\n return;\n }\n if (lane.maxMemoryBytes !== undefined && stats.memoryBytes <= lane.maxMemoryBytes) return;\n if (inFlight !== 0 || current !== of || closed) return;\n if (lane.restartIf && !lane.restartIf(stats)) return;\n lane.onRestart?.(stats);\n void replace(w, new Error(\"wasm host lane: restarted past its memory limit\")).catch(() => {});\n };\n\n boot();\n\n return {\n async fetch(input, init) {\n if (closed) throw new Error(\"wasm host lane: closed\");\n const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);\n if (signal?.aborted) throw abortReason(signal);\n if (failed) boot();\n const booting = current;\n const w = await booting;\n if (signal?.aborted) throw abortReason(signal);\n inFlight++;\n let ended = false;\n const end = () => {\n if (ended) return;\n ended = true;\n inFlight--;\n if (inFlight === 0 && checksMemory && current === booting) void checkMemory(w, booting);\n };\n const run = workerFetch(w)(input, init);\n if (!signal) {\n return run.then(\n (res) => untilBodyEnds(res, end),\n (err) => {\n end();\n throw err;\n },\n );\n }\n return new Promise<Response>((resolve, reject) => {\n const onAbort = () => {\n end();\n reject(abortReason(signal));\n if (current === booting) void replace(w, new Error(\"wasm host lane: restarted after an abort\")).catch(() => {});\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n run.then(\n // A streamed body is still coming from the busy worker, so an abort until it ends must\n // still end the worker.\n (res) =>\n resolve(\n untilBodyEnds(res, () => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n }),\n ),\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n reject(err);\n },\n );\n });\n },\n worker: () => current,\n async restart() {\n const old = await current.catch(() => undefined);\n await (old ? replace(old, new Error(\"wasm host lane: restarted\")) : boot());\n },\n close() {\n closed = true;\n void current.then((w) => endWorker(w, new Error(\"wasm host lane: closed\")), () => {});\n },\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n"]}
1
+ {"version":3,"sources":["../../src/wasmhost/client.ts","../../src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AAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,SAAA,CAAU,CAAA,EAAG,IAAI,KAAA,CAAM,wBAAwB,CAAC,CAAA,EAAG,MAAM;AAAA,MAAC,CAAC,CAAA;AAAA,IACtF;AAAA,GACF;AACF;AAEA,SAASA,aAAY,MAAA,EAA8B;AACjD,EAAA,OAAO,MAAA,CAAO,MAAA,IAAU,IAAI,YAAA,CAAa,6BAA6B,YAAY,CAAA;AACpF","file":"index.js","sourcesContent":["// The page's side of a wasm host worker (goapplib issue 32). startWorker loads the app's Go wasm in\n// a Web Worker; workerFetch is a fetch to hand a Connect transport, so the app's generated clients\n// talk to the worker exactly as they would to a server; mountFiles pushes files in before the\n// requests that read them.\nimport type { Files, HeapStats, HostChunk, HostReply, HostRequest, HostStatus } from \"./protocol\";\n\nexport type { Files } from \"./protocol\";\n\n/** Where the worker's pieces are served, and the global name the Go side exports under. */\nexport interface StartWorkerOptions {\n /** The built worker script, @panyam/tsappkit/wasmhost/worker.js, as your bundler serves it. */\n worker: string | URL;\n /** The Go wasm build. */\n wasm: string | URL;\n /** Go's wasm_exec.js, from `$(go env GOROOT)/lib/wasm`, matching the Go that built the wasm. */\n exec: string | URL;\n /** The ns the Go program passed to wasmhost.Serve. */\n ns: string;\n}\n\ntype Unsent = HostRequest extends infer R ? (R extends HostRequest ? Omit<R, \"id\"> : never) : never;\n\nclass Channel {\n private next = 1;\n private pending = new Map<\n number,\n { resolve: (r: HostReply) => void; reject: (e: Error) => void; onChunk?: (c: HostChunk) => void }\n >();\n private dead: Error | null = null;\n\n constructor(private worker: Worker) {\n worker.addEventListener(\"message\", (ev: MessageEvent<HostReply | HostStatus | HostChunk>) => {\n const m = ev.data;\n if (\"exited\" in m) {\n this.fail(new Error(`wasm host: ${m.exited}`));\n } else if (\"chunk\" in m) {\n this.pending.get(m.id)?.onChunk?.(m);\n } else if (\"id\" in m) {\n this.pending.get(m.id)?.resolve(m);\n this.pending.delete(m.id);\n }\n });\n worker.addEventListener(\"error\", (ev: ErrorEvent) => this.fail(new Error(`wasm host worker: ${ev.message}`)));\n }\n\n /** Sends req and returns its id with the final reply; chunks before it go to onChunk. */\n start(req: Unsent, transfer: Transferable[], onChunk?: (c: HostChunk) => void): { id: number; done: Promise<HostReply> } {\n const id = this.next++;\n if (this.dead) return { id, done: Promise.reject(this.dead) };\n const done = new Promise<HostReply>((resolve, reject) => {\n this.pending.set(id, { resolve, reject, onChunk });\n this.worker.postMessage({ ...req, id }, transfer);\n });\n return { id, done };\n }\n\n call(req: Unsent, transfer: Transferable[]): Promise<HostReply> {\n return this.start(req, transfer).done;\n }\n\n fail(err: Error) {\n this.dead = err;\n for (const p of this.pending.values()) p.reject(err);\n this.pending.clear();\n }\n}\n\nconst channels = new WeakMap<Worker, Channel>();\n\n/**\n * Terminates worker and rejects every request still waiting on it with `err`, which terminate\n * alone wouldn't do: a terminated worker never replies, so its pending requests would wait forever.\n * For lane.ts; not exported from the package.\n */\nexport function endWorker(worker: Worker, err: Error): void {\n channels.get(worker)?.fail(err);\n worker.terminate();\n}\n\nfunction channel(worker: Worker): Channel {\n let c = channels.get(worker);\n if (!c) {\n c = new Channel(worker);\n channels.set(worker, c);\n }\n return c;\n}\n\n/**\n * Starts the worker and resolves with it once the Go program has installed its exports, or rejects\n * with why it couldn't load (and terminates it, since it can't answer anything). Relative URLs\n * resolve against the page, not the worker script.\n */\nexport function startWorker(opts: StartWorkerOptions): Promise<Worker> {\n const abs = (u: string | URL) => new URL(u, location.href).href;\n const url = new URL(abs(opts.worker));\n url.searchParams.set(\"wasm\", abs(opts.wasm));\n url.searchParams.set(\"exec\", abs(opts.exec));\n url.searchParams.set(\"ns\", opts.ns);\n const worker = new Worker(url);\n channel(worker);\n return new Promise((resolve, reject) => {\n const onMessage = (ev: MessageEvent<HostStatus | HostReply>) => {\n const m = ev.data;\n if (!(\"ready\" in m)) return;\n worker.removeEventListener(\"message\", onMessage);\n if (m.ready) {\n resolve(worker);\n return;\n }\n worker.terminate();\n reject(new Error(`wasm host failed to load: ${m.error}`));\n };\n worker.addEventListener(\"message\", onMessage);\n worker.addEventListener(\n \"error\",\n (ev: ErrorEvent) => {\n worker.terminate();\n reject(new Error(`wasm host worker: ${ev.message}`));\n },\n { once: true },\n );\n });\n}\n\n// Statuses whose Response must have no body.\nconst NULL_BODY = new Set([101, 103, 204, 205, 304]);\n\n/**\n * A fetch that answers in the worker, for `createConnectTransport({ baseUrl, fetch: workerFetch(worker) })`.\n * Only the path and query reach the worker, so baseUrl can be anything absolute, such as\n * location.origin. It rejects if the worker reports an error (no handler, a failed build, a handler\n * panic) and resolves with any HTTP status the handler chose.\n *\n * A handler that flushes (http.Flusher) streams: the Response resolves at its first flush, and its\n * body delivers each flush as it happens, even from a Go loop that never yields, then the rest\n * when the handler returns. Aborting the request (init.signal) rejects it, or errors a body that's\n * already streaming, and cancels the handler's context; a handler sees that the next time it checks\n * ctx, which a loop that never yields to JS doesn't get to do (a lane ends such a worker instead).\n * Once the body is streaming, Chrome's text() and json() report the abort as \"TypeError: Failed to\n * fetch\" rather than an AbortError, so tell an abort from a failure by signal.aborted.\n */\nexport function workerFetch(worker: Worker): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n const c = channel(worker);\n return async (input, init) => {\n const req = new Request(input, init);\n const signal = req.signal;\n if (signal.aborted) throw abortReason(signal);\n const buf = new Uint8Array(await req.arrayBuffer());\n const body = buf.byteLength ? buf : null;\n const headers: Record<string, string> = {};\n req.headers.forEach((v, k) => (headers[k] = v));\n const u = new URL(req.url);\n\n return new Promise<Response>((resolve, reject) => {\n let stream: ReadableStreamDefaultController<Uint8Array> | undefined;\n let settled = false;\n const fail = (err: unknown) => {\n if (settled) return;\n settled = true;\n if (stream) stream.error(err);\n else reject(err);\n };\n const { id, done } = c.start(\n { kind: \"http\", method: req.method, url: u.pathname + u.search, headers, body },\n body ? [body.buffer] : [],\n (chunk) => {\n if (settled) return;\n if (!stream) {\n const status = chunk.status ?? 200;\n const rs = new ReadableStream<Uint8Array>({ start: (ctl) => void (stream = ctl) });\n resolve(new Response(NULL_BODY.has(status) ? null : rs, { status, headers: chunk.headers }));\n }\n if (chunk.body.byteLength) stream!.enqueue(chunk.body);\n },\n );\n const onAbort = () => {\n void c.call({ kind: \"cancel\", target: id }, []).catch(() => {});\n fail(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n done.then(\n (reply) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (!reply.ok) return fail(new Error(reply.error));\n if (settled) return;\n settled = true;\n if (stream) {\n if (reply.body?.byteLength) stream.enqueue(reply.body);\n stream.close();\n return;\n }\n const status = reply.status ?? 200;\n const resBody = NULL_BODY.has(status) ? null : ((reply.body ?? null) as BodyInit | null);\n resolve(new Response(resBody, { status, headers: reply.headers }));\n },\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n fail(err);\n },\n );\n });\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n\n/**\n * A fetch like workerFetch's, except that each call starts a fresh worker from `opts`, sends it that\n * one request, and terminates it once the response is in, whether the request succeeded or not.\n * Ending the worker is the only way to give its wasm memory back to the browser, since wasm memory\n * never shrinks, so route a request with a big transient peak (an ingest that parses a large input\n * on the way to a small result) through this, and have it leave its result in the shared Cache\n * (Go's wasmhost.BrowserCache) for the long-lived worker to load. Every worker for the same `ns`\n * sees the same cache.\n *\n * Each call pays for a worker start and a wasm instantiate, a few hundred ms, so it's for jobs\n * that take seconds, not for ordinary requests. The worker ends when the response's body has been\n * read to the end, fails, or is cancelled, so a streamed body isn't cut short; read or cancel the\n * body, or the worker stays up.\n */\nexport function oneShotFetch(opts: StartWorkerOptions): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n return async (input, init) => {\n const worker = await startWorker(opts);\n let res: Response;\n try {\n res = await workerFetch(worker)(input, init);\n } catch (err) {\n worker.terminate();\n throw err;\n }\n return untilBodyEnds(res, () => worker.terminate());\n };\n}\n\n/**\n * res with `end` called once its body has been read to the end, has failed, or has been\n * cancelled (or at once, for a response without a body). For oneShotFetch and lanes, which must\n * not let go of a worker while its streamed body is still arriving. Not exported from the package.\n */\nexport function untilBodyEnds(res: Response, end: () => void): Response {\n if (!res.body) {\n end();\n return res;\n }\n const reader = res.body.getReader();\n const body = new ReadableStream<Uint8Array>({\n async pull(ctl) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n ctl.close();\n end();\n } else {\n ctl.enqueue(value);\n }\n } catch (err) {\n end();\n ctl.error(err);\n }\n },\n cancel(reason) {\n end();\n return reader.cancel(reason);\n },\n });\n return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });\n}\n\n/**\n * Replaces the mount `name` with `files`. The buffers are transferred to the worker, not copied, so\n * each Uint8Array is empty here afterwards; copy first anything the page still needs. Resolves once\n * the worker has mounted them (and, for a rebuild-mode host, rebuilt its handler).\n */\nexport function mountFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"mount\", name, files);\n}\n\n/**\n * Adds `files` to the mount `name`, keeping the files it already holds; a file at a path the mount\n * already has is replaced, and a missing mount is created. This suits a page that brings files in a\n * piece at a time, since it only sends what's new. The worker checks the whole batch first, so a\n * rejection (a path that is already a directory, say) leaves the mount as it was. Buffers are\n * transferred as with mountFiles.\n */\nexport function addFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"add\", name, files);\n}\n\nasync function sendFiles(worker: Worker, kind: \"mount\" | \"add\", name: string, files: Files): Promise<void> {\n const transfer = new Set<ArrayBuffer>();\n for (const b of Object.values(files)) {\n // A tag check rather than instanceof, which fails for a buffer from another realm (an iframe),\n // and a SharedArrayBuffer can't be transferred.\n if (Object.prototype.toString.call(b.buffer) === \"[object ArrayBuffer]\") transfer.add(b.buffer as ArrayBuffer);\n }\n const reply = await channel(worker).call({ kind, name, files }, [...transfer]);\n if (!reply.ok) throw new Error(reply.error);\n}\n\n/**\n * The bytes of linear memory the worker's wasm holds. Wasm memory grows and never shrinks, so this\n * is the peak the engine has needed so far, which is what an app weighs before giving a browser a\n * bigger job.\n */\nexport async function workerMemory(worker: Worker): Promise<number> {\n const reply = await channel(worker).call({ kind: \"stats\" }, []);\n if (!reply.ok) throw new Error(reply.error);\n return reply.memoryBytes ?? 0;\n}\n\n/** What workerStats reports about a worker. */\nexport interface WorkerStats {\n /** The wasm linear memory's size, as workerMemory: the peak so far, since it never shrinks. */\n memoryBytes: number;\n /**\n * The Go heap inside it, absent when the wasm was built against goapplib before 0.7.4. Far below\n * memoryBytes means a fresh worker would come back smaller; near it means one would come back\n * just as large.\n */\n heap?: HeapStats;\n}\n\n/**\n * The worker's wasm memory and its Go heap. With `gc`, the worker collects garbage first, so\n * heap.heapAlloc is what it holds live rather than live plus garbage, at the cost of a pause; it\n * waits behind whatever the worker is running, like any request.\n */\nexport async function workerStats(worker: Worker, opts: { gc?: boolean } = {}): Promise<WorkerStats> {\n const reply = await channel(worker).call({ kind: \"stats\", gc: opts.gc === true }, []);\n if (!reply.ok) throw new Error(reply.error);\n return { memoryBytes: reply.memoryBytes ?? 0, heap: reply.heap };\n}\n\n/** Removes the mount `name`. Removing a name that isn't mounted succeeds. */\nexport async function unmountFiles(worker: Worker, name: string): Promise<void> {\n const reply = await channel(worker).call({ kind: \"unmount\", name }, []);\n if (!reply.ok) throw new Error(reply.error);\n}\n","// Turning what a user drops or picks into the {path: bytes} map mountFiles takes. The bytes are\n// read here, before any request, because the Go side can't wait on File.arrayBuffer() mid-request.\nimport type { Files } from \"./protocol\";\n\n// The parts of the File and Directory Entries API used here. Chromium, Firefox and Safari all ship\n// it under the webkit prefix.\ninterface Entry {\n isFile: boolean;\n isDirectory: boolean;\n fullPath: string;\n}\ninterface FileEntry extends Entry {\n file(ok: (f: File) => void, err: (e: unknown) => void): void;\n}\ninterface DirectoryEntry extends Entry {\n createReader(): { readEntries(ok: (es: Entry[]) => void, err: (e: unknown) => void): void };\n}\n\n/**\n * Reads a drop into files keyed by path. A dropped folder keeps its own name as the first path\n * element (\"design/board.edn\"), and dropped loose files sit at the top. Entries the browser can't\n * read as files or folders are skipped.\n */\nexport async function filesFromDrop(dt: DataTransfer): Promise<Files> {\n const entries: Entry[] = [];\n const loose: File[] = [];\n for (const item of Array.from(dt.items)) {\n if (item.kind !== \"file\") continue;\n const entry = (item as DataTransferItem & { webkitGetAsEntry?: () => Entry | null }).webkitGetAsEntry?.();\n if (entry) entries.push(entry);\n else {\n const f = item.getAsFile();\n if (f) loose.push(f);\n }\n }\n const out: Files = {};\n await Promise.all([\n ...entries.map((e) => readEntry(e, out)),\n ...loose.map(async (f) => {\n out[f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n ]);\n return out;\n}\n\n/**\n * Reads an `<input type=\"file\" webkitdirectory>` (or `multiple`) selection into files keyed by\n * path. Folder picks use each file's webkitRelativePath, which starts with the folder's name.\n */\nexport async function filesFromFileList(list: FileList | File[]): Promise<Files> {\n const out: Files = {};\n await Promise.all(\n Array.from(list).map(async (f) => {\n out[f.webkitRelativePath || f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n );\n return out;\n}\n\nasync function readEntry(entry: Entry, out: Files): Promise<void> {\n if (entry.isFile) {\n const f = await new Promise<File>((ok, err) => (entry as FileEntry).file(ok, err));\n out[entry.fullPath.replace(/^\\/+/, \"\")] = new Uint8Array(await f.arrayBuffer());\n return;\n }\n if (!entry.isDirectory) return;\n const reader = (entry as DirectoryEntry).createReader();\n // readEntries returns a batch at a time (100 in Chromium) and an empty batch at the end.\n for (;;) {\n const batch = await new Promise<Entry[]>((ok, err) => reader.readEntries(ok, err));\n if (batch.length === 0) return;\n await Promise.all(batch.map((e) => readEntry(e, out)));\n }\n}\n","// Lanes (goapplib issue 80): more than one worker for one wasm service, with the app routing\n// requests by kind, so a quick request never waits behind a long one. Go's wasm target runs one\n// thread per worker, and a job that never yields keeps that thread busy, so neither a second\n// request nor an abort can reach it. A lane holds one worker it can replace: aborting a request\n// on it terminates the worker, which is the only way to stop a job that never yields, and starts\n// a fresh one, warmed from the shared Cache by the app's warm function.\nimport { endWorker, startWorker, untilBodyEnds, workerFetch, workerStats, type StartWorkerOptions, type WorkerStats } from \"./client\";\n\ntype Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface LaneOptions {\n /**\n * Runs on each new worker before the lane hands it a request: typically a request that loads\n * the service's state from the cache (wasmhost.BrowserCache), so a replacement worker answers\n * like the one it replaced. A warm that throws ends that worker, and the error is what the next\n * request gets; the request after it starts another worker.\n */\n warm?: (fetch: Fetch) => Promise<unknown>;\n /**\n * A memory limit for the lane's worker, in bytes of wasm memory (workerMemory). Wasm memory never\n * shrinks, so a long-lived worker creeps up through requests that each allocate and drop some.\n * When a request finishes (its body read to the end, or failed) and the lane has nothing else\n * in flight, the lane asks the worker how much it holds, and past this limit replaces it with a\n * fresh one, warmed as on an abort. It never interrupts a request, so a lane that's never idle\n * never restarts, and a response whose body nobody reads keeps the lane busy. Size it above what\n * the warmed state needs, or the lane restarts after every request.\n */\n maxMemoryBytes?: number;\n /**\n * Decides from the worker's stats whether to replace it, checked at the same idle moments as\n * maxMemoryBytes. The stats are taken after a collection, so heap.heapAlloc is the live heap,\n * and a worker whose live heap is near its memory would come back just as large; replacing one\n * pays when memoryBytes is far above it. With maxMemoryBytes as well, the lane restarts only when\n * the worker is past that limit and this returns true, and a worker under the limit isn't asked\n * to collect. Without maxMemoryBytes every idle moment pays a collection (187 ms on a 377 MB\n * live heap in agni), so set both. heap is absent for a wasm built against goapplib before 0.7.4.\n */\n restartIf?: (stats: WorkerStats) => boolean;\n /** Called when the lane replaces its worker for maxMemoryBytes or restartIf, with its stats. */\n onRestart?: (why: WorkerStats) => void;\n}\n\n/** One replaceable worker. See startLane. */\nexport interface Lane {\n /**\n * A fetch for a Connect transport, like workerFetch, answered by the lane's current worker.\n * Aborting a request (init.signal) rejects it with the signal's reason at once (or errors its\n * body, if it's already streaming), terminates the worker, and starts and warms a new one; other\n * requests still waiting on the old worker are rejected too. A request made meanwhile waits for\n * the new worker.\n */\n fetch: Fetch;\n /** The lane's current worker, once it's started and warmed. */\n worker(): Promise<Worker>;\n /** Replaces the worker, as an abort does, and resolves once the new one is warm. */\n restart(): Promise<void>;\n /** Terminates the worker. Requests after this reject. */\n close(): void;\n}\n\n/**\n * Starts a lane: a worker from `opts`, warmed with `lane.warm`, that the lane replaces whenever a\n * request on it is aborted. Give each kind of request its own lane (a \"serve\" lane for quick\n * queries, a \"jobs\" lane for long jobs) by building each client's transport on that lane's fetch.\n * Every lane of one ns shares the same Cache, which is how a replacement or a second lane gets the\n * state without rebuilding it.\n */\nexport function startLane(opts: StartWorkerOptions, lane: LaneOptions = {}): Lane {\n let closed = false;\n let current!: Promise<Worker>;\n let failed = false;\n\n const boot = () => {\n failed = false;\n const p: Promise<Worker> = startWorker(opts).then(async (w) => {\n if (lane.warm) {\n try {\n await lane.warm(workerFetch(w));\n } catch (err) {\n endWorker(w, err instanceof Error ? err : new Error(String(err)));\n throw err;\n }\n }\n return w;\n });\n p.catch(() => {\n if (current === p) failed = true;\n });\n current = p;\n return p;\n };\n\n const replace = (old: Worker, why: Error) => {\n endWorker(old, why);\n return boot();\n };\n\n let inFlight = 0;\n const checksMemory = lane.maxMemoryBytes !== undefined || lane.restartIf !== undefined;\n // Runs when the lane goes idle. A request that starts while workerStats is out means the lane\n // isn't idle any more, so the restart waits for the next idle moment. The limit is read first\n // without a collection, which can take a fifth of a second on a big heap (#121), so a worker\n // under it is never asked to collect.\n const checkMemory = async (w: Worker, of: Promise<Worker>) => {\n const idle = () => inFlight === 0 && current === of && !closed;\n let stats: WorkerStats | undefined;\n try {\n if (lane.maxMemoryBytes !== undefined) {\n stats = await workerStats(w);\n if (stats.memoryBytes <= lane.maxMemoryBytes || !idle()) return;\n }\n if (lane.restartIf) {\n stats = await workerStats(w, { gc: true });\n if (!idle() || !lane.restartIf(stats)) return;\n }\n } catch {\n return;\n }\n if (!stats) return;\n lane.onRestart?.(stats);\n void replace(w, new Error(\"wasm host lane: restarted past its memory limit\")).catch(() => {});\n };\n\n boot();\n\n return {\n async fetch(input, init) {\n if (closed) throw new Error(\"wasm host lane: closed\");\n const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);\n if (signal?.aborted) throw abortReason(signal);\n if (failed) boot();\n const booting = current;\n const w = await booting;\n if (signal?.aborted) throw abortReason(signal);\n inFlight++;\n let ended = false;\n const end = () => {\n if (ended) return;\n ended = true;\n inFlight--;\n if (inFlight === 0 && checksMemory && current === booting) void checkMemory(w, booting);\n };\n const run = workerFetch(w)(input, init);\n if (!signal) {\n return run.then(\n (res) => untilBodyEnds(res, end),\n (err) => {\n end();\n throw err;\n },\n );\n }\n return new Promise<Response>((resolve, reject) => {\n const onAbort = () => {\n end();\n reject(abortReason(signal));\n if (current === booting) void replace(w, new Error(\"wasm host lane: restarted after an abort\")).catch(() => {});\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n run.then(\n // A streamed body is still coming from the busy worker, so an abort until it ends must\n // still end the worker.\n (res) =>\n resolve(\n untilBodyEnds(res, () => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n }),\n ),\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n reject(err);\n },\n );\n });\n },\n worker: () => current,\n async restart() {\n const old = await current.catch(() => undefined);\n await (old ? replace(old, new Error(\"wasm host lane: restarted\")) : boot());\n },\n close() {\n closed = true;\n void current.then((w) => endWorker(w, new Error(\"wasm host lane: closed\")), () => {});\n },\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n"]}
@@ -294,15 +294,21 @@ function startLane(opts, lane = {}) {
294
294
  let inFlight = 0;
295
295
  const checksMemory = lane.maxMemoryBytes !== void 0 || lane.restartIf !== void 0;
296
296
  const checkMemory = async (w, of) => {
297
+ const idle = () => inFlight === 0 && current === of && !closed;
297
298
  let stats;
298
299
  try {
299
- stats = await workerStats(w, { gc: lane.restartIf !== void 0 });
300
+ if (lane.maxMemoryBytes !== void 0) {
301
+ stats = await workerStats(w);
302
+ if (stats.memoryBytes <= lane.maxMemoryBytes || !idle()) return;
303
+ }
304
+ if (lane.restartIf) {
305
+ stats = await workerStats(w, { gc: true });
306
+ if (!idle() || !lane.restartIf(stats)) return;
307
+ }
300
308
  } catch {
301
309
  return;
302
310
  }
303
- if (lane.maxMemoryBytes !== void 0 && stats.memoryBytes <= lane.maxMemoryBytes) return;
304
- if (inFlight !== 0 || current !== of || closed) return;
305
- if (lane.restartIf && !lane.restartIf(stats)) return;
311
+ if (!stats) return;
306
312
  lane.onRestart?.(stats);
307
313
  void replace(w, new Error("wasm host lane: restarted past its memory limit")).catch(() => {
308
314
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/wasmhost/client.ts","../../src/wasmhost/drop.ts","../../src/wasmhost/lane.ts"],"names":["abortReason"],"mappings":";AAsBA,IAAM,UAAN,MAAc;AAAA,EAQZ,YAAoB,MAAA,EAAgB;AAAhB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAPpB,IAAA,IAAA,CAAQ,IAAA,GAAO,CAAA;AACf,IAAA,IAAA,CAAQ,OAAA,uBAAc,GAAA,EAGpB;AACF,IAAA,IAAA,CAAQ,IAAA,GAAqB,IAAA;AAG3B,IAAA,MAAA,CAAO,gBAAA,CAAiB,SAAA,EAAW,CAAC,EAAA,KAAyD;AAC3F,MAAA,MAAM,IAAI,EAAA,CAAG,IAAA;AACb,MAAA,IAAI,YAAY,CAAA,EAAG;AACjB,QAAA,IAAA,CAAK,KAAK,IAAI,KAAA,CAAM,cAAc,CAAA,CAAE,MAAM,EAAE,CAAC,CAAA;AAAA,MAC/C,CAAA,MAAA,IAAW,WAAW,CAAA,EAAG;AACvB,QAAA,IAAA,CAAK,QAAQ,GAAA,CAAI,CAAA,CAAE,EAAE,CAAA,EAAG,UAAU,CAAC,CAAA;AAAA,MACrC,CAAA,MAAA,IAAW,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H,CAAA;AAAA,IACA,QAAQ,MAAM,OAAA;AAAA,IACd,MAAM,OAAA,GAAU;AACd,MAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,KAAA,CAAM,MAAM,MAAS,CAAA;AAC/C,MAAA,OAAO,GAAA,GAAM,QAAQ,GAAA,EAAK,IAAI,MAAM,2BAA2B,CAAC,IAAI,IAAA,EAAK,CAAA;AAAA,IAC3E,CAAA;AAAA,IACA,KAAA,GAAQ;AACN,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,KAAK,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,SAAA,CAAU,CAAA,EAAG,IAAI,KAAA,CAAM,wBAAwB,CAAC,CAAA,EAAG,MAAM;AAAA,MAAC,CAAC,CAAA;AAAA,IACtF;AAAA,GACF;AACF;AAEA,SAASA,aAAY,MAAA,EAA8B;AACjD,EAAA,OAAO,MAAA,CAAO,MAAA,IAAU,IAAI,YAAA,CAAa,6BAA6B,YAAY,CAAA;AACpF","file":"index.mjs","sourcesContent":["// The page's side of a wasm host worker (goapplib issue 32). startWorker loads the app's Go wasm in\n// a Web Worker; workerFetch is a fetch to hand a Connect transport, so the app's generated clients\n// talk to the worker exactly as they would to a server; mountFiles pushes files in before the\n// requests that read them.\nimport type { Files, HeapStats, HostChunk, HostReply, HostRequest, HostStatus } from \"./protocol\";\n\nexport type { Files } from \"./protocol\";\n\n/** Where the worker's pieces are served, and the global name the Go side exports under. */\nexport interface StartWorkerOptions {\n /** The built worker script, @panyam/tsappkit/wasmhost/worker.js, as your bundler serves it. */\n worker: string | URL;\n /** The Go wasm build. */\n wasm: string | URL;\n /** Go's wasm_exec.js, from `$(go env GOROOT)/lib/wasm`, matching the Go that built the wasm. */\n exec: string | URL;\n /** The ns the Go program passed to wasmhost.Serve. */\n ns: string;\n}\n\ntype Unsent = HostRequest extends infer R ? (R extends HostRequest ? Omit<R, \"id\"> : never) : never;\n\nclass Channel {\n private next = 1;\n private pending = new Map<\n number,\n { resolve: (r: HostReply) => void; reject: (e: Error) => void; onChunk?: (c: HostChunk) => void }\n >();\n private dead: Error | null = null;\n\n constructor(private worker: Worker) {\n worker.addEventListener(\"message\", (ev: MessageEvent<HostReply | HostStatus | HostChunk>) => {\n const m = ev.data;\n if (\"exited\" in m) {\n this.fail(new Error(`wasm host: ${m.exited}`));\n } else if (\"chunk\" in m) {\n this.pending.get(m.id)?.onChunk?.(m);\n } else if (\"id\" in m) {\n this.pending.get(m.id)?.resolve(m);\n this.pending.delete(m.id);\n }\n });\n worker.addEventListener(\"error\", (ev: ErrorEvent) => this.fail(new Error(`wasm host worker: ${ev.message}`)));\n }\n\n /** Sends req and returns its id with the final reply; chunks before it go to onChunk. */\n start(req: Unsent, transfer: Transferable[], onChunk?: (c: HostChunk) => void): { id: number; done: Promise<HostReply> } {\n const id = this.next++;\n if (this.dead) return { id, done: Promise.reject(this.dead) };\n const done = new Promise<HostReply>((resolve, reject) => {\n this.pending.set(id, { resolve, reject, onChunk });\n this.worker.postMessage({ ...req, id }, transfer);\n });\n return { id, done };\n }\n\n call(req: Unsent, transfer: Transferable[]): Promise<HostReply> {\n return this.start(req, transfer).done;\n }\n\n fail(err: Error) {\n this.dead = err;\n for (const p of this.pending.values()) p.reject(err);\n this.pending.clear();\n }\n}\n\nconst channels = new WeakMap<Worker, Channel>();\n\n/**\n * Terminates worker and rejects every request still waiting on it with `err`, which terminate\n * alone wouldn't do: a terminated worker never replies, so its pending requests would wait forever.\n * For lane.ts; not exported from the package.\n */\nexport function endWorker(worker: Worker, err: Error): void {\n channels.get(worker)?.fail(err);\n worker.terminate();\n}\n\nfunction channel(worker: Worker): Channel {\n let c = channels.get(worker);\n if (!c) {\n c = new Channel(worker);\n channels.set(worker, c);\n }\n return c;\n}\n\n/**\n * Starts the worker and resolves with it once the Go program has installed its exports, or rejects\n * with why it couldn't load (and terminates it, since it can't answer anything). Relative URLs\n * resolve against the page, not the worker script.\n */\nexport function startWorker(opts: StartWorkerOptions): Promise<Worker> {\n const abs = (u: string | URL) => new URL(u, location.href).href;\n const url = new URL(abs(opts.worker));\n url.searchParams.set(\"wasm\", abs(opts.wasm));\n url.searchParams.set(\"exec\", abs(opts.exec));\n url.searchParams.set(\"ns\", opts.ns);\n const worker = new Worker(url);\n channel(worker);\n return new Promise((resolve, reject) => {\n const onMessage = (ev: MessageEvent<HostStatus | HostReply>) => {\n const m = ev.data;\n if (!(\"ready\" in m)) return;\n worker.removeEventListener(\"message\", onMessage);\n if (m.ready) {\n resolve(worker);\n return;\n }\n worker.terminate();\n reject(new Error(`wasm host failed to load: ${m.error}`));\n };\n worker.addEventListener(\"message\", onMessage);\n worker.addEventListener(\n \"error\",\n (ev: ErrorEvent) => {\n worker.terminate();\n reject(new Error(`wasm host worker: ${ev.message}`));\n },\n { once: true },\n );\n });\n}\n\n// Statuses whose Response must have no body.\nconst NULL_BODY = new Set([101, 103, 204, 205, 304]);\n\n/**\n * A fetch that answers in the worker, for `createConnectTransport({ baseUrl, fetch: workerFetch(worker) })`.\n * Only the path and query reach the worker, so baseUrl can be anything absolute, such as\n * location.origin. It rejects if the worker reports an error (no handler, a failed build, a handler\n * panic) and resolves with any HTTP status the handler chose.\n *\n * A handler that flushes (http.Flusher) streams: the Response resolves at its first flush, and its\n * body delivers each flush as it happens, even from a Go loop that never yields, then the rest\n * when the handler returns. Aborting the request (init.signal) rejects it, or errors a body that's\n * already streaming, and cancels the handler's context; a handler sees that the next time it checks\n * ctx, which a loop that never yields to JS doesn't get to do (a lane ends such a worker instead).\n * Once the body is streaming, Chrome's text() and json() report the abort as \"TypeError: Failed to\n * fetch\" rather than an AbortError, so tell an abort from a failure by signal.aborted.\n */\nexport function workerFetch(worker: Worker): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n const c = channel(worker);\n return async (input, init) => {\n const req = new Request(input, init);\n const signal = req.signal;\n if (signal.aborted) throw abortReason(signal);\n const buf = new Uint8Array(await req.arrayBuffer());\n const body = buf.byteLength ? buf : null;\n const headers: Record<string, string> = {};\n req.headers.forEach((v, k) => (headers[k] = v));\n const u = new URL(req.url);\n\n return new Promise<Response>((resolve, reject) => {\n let stream: ReadableStreamDefaultController<Uint8Array> | undefined;\n let settled = false;\n const fail = (err: unknown) => {\n if (settled) return;\n settled = true;\n if (stream) stream.error(err);\n else reject(err);\n };\n const { id, done } = c.start(\n { kind: \"http\", method: req.method, url: u.pathname + u.search, headers, body },\n body ? [body.buffer] : [],\n (chunk) => {\n if (settled) return;\n if (!stream) {\n const status = chunk.status ?? 200;\n const rs = new ReadableStream<Uint8Array>({ start: (ctl) => void (stream = ctl) });\n resolve(new Response(NULL_BODY.has(status) ? null : rs, { status, headers: chunk.headers }));\n }\n if (chunk.body.byteLength) stream!.enqueue(chunk.body);\n },\n );\n const onAbort = () => {\n void c.call({ kind: \"cancel\", target: id }, []).catch(() => {});\n fail(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n done.then(\n (reply) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (!reply.ok) return fail(new Error(reply.error));\n if (settled) return;\n settled = true;\n if (stream) {\n if (reply.body?.byteLength) stream.enqueue(reply.body);\n stream.close();\n return;\n }\n const status = reply.status ?? 200;\n const resBody = NULL_BODY.has(status) ? null : ((reply.body ?? null) as BodyInit | null);\n resolve(new Response(resBody, { status, headers: reply.headers }));\n },\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n fail(err);\n },\n );\n });\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n\n/**\n * A fetch like workerFetch's, except that each call starts a fresh worker from `opts`, sends it that\n * one request, and terminates it once the response is in, whether the request succeeded or not.\n * Ending the worker is the only way to give its wasm memory back to the browser, since wasm memory\n * never shrinks, so route a request with a big transient peak (an ingest that parses a large input\n * on the way to a small result) through this, and have it leave its result in the shared Cache\n * (Go's wasmhost.BrowserCache) for the long-lived worker to load. Every worker for the same `ns`\n * sees the same cache.\n *\n * Each call pays for a worker start and a wasm instantiate, a few hundred ms, so it's for jobs\n * that take seconds, not for ordinary requests. The worker ends when the response's body has been\n * read to the end, fails, or is cancelled, so a streamed body isn't cut short; read or cancel the\n * body, or the worker stays up.\n */\nexport function oneShotFetch(opts: StartWorkerOptions): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n return async (input, init) => {\n const worker = await startWorker(opts);\n let res: Response;\n try {\n res = await workerFetch(worker)(input, init);\n } catch (err) {\n worker.terminate();\n throw err;\n }\n return untilBodyEnds(res, () => worker.terminate());\n };\n}\n\n/**\n * res with `end` called once its body has been read to the end, has failed, or has been\n * cancelled (or at once, for a response without a body). For oneShotFetch and lanes, which must\n * not let go of a worker while its streamed body is still arriving. Not exported from the package.\n */\nexport function untilBodyEnds(res: Response, end: () => void): Response {\n if (!res.body) {\n end();\n return res;\n }\n const reader = res.body.getReader();\n const body = new ReadableStream<Uint8Array>({\n async pull(ctl) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n ctl.close();\n end();\n } else {\n ctl.enqueue(value);\n }\n } catch (err) {\n end();\n ctl.error(err);\n }\n },\n cancel(reason) {\n end();\n return reader.cancel(reason);\n },\n });\n return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });\n}\n\n/**\n * Replaces the mount `name` with `files`. The buffers are transferred to the worker, not copied, so\n * each Uint8Array is empty here afterwards; copy first anything the page still needs. Resolves once\n * the worker has mounted them (and, for a rebuild-mode host, rebuilt its handler).\n */\nexport function mountFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"mount\", name, files);\n}\n\n/**\n * Adds `files` to the mount `name`, keeping the files it already holds; a file at a path the mount\n * already has is replaced, and a missing mount is created. This suits a page that brings files in a\n * piece at a time, since it only sends what's new. The worker checks the whole batch first, so a\n * rejection (a path that is already a directory, say) leaves the mount as it was. Buffers are\n * transferred as with mountFiles.\n */\nexport function addFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"add\", name, files);\n}\n\nasync function sendFiles(worker: Worker, kind: \"mount\" | \"add\", name: string, files: Files): Promise<void> {\n const transfer = new Set<ArrayBuffer>();\n for (const b of Object.values(files)) {\n // A tag check rather than instanceof, which fails for a buffer from another realm (an iframe),\n // and a SharedArrayBuffer can't be transferred.\n if (Object.prototype.toString.call(b.buffer) === \"[object ArrayBuffer]\") transfer.add(b.buffer as ArrayBuffer);\n }\n const reply = await channel(worker).call({ kind, name, files }, [...transfer]);\n if (!reply.ok) throw new Error(reply.error);\n}\n\n/**\n * The bytes of linear memory the worker's wasm holds. Wasm memory grows and never shrinks, so this\n * is the peak the engine has needed so far, which is what an app weighs before giving a browser a\n * bigger job.\n */\nexport async function workerMemory(worker: Worker): Promise<number> {\n const reply = await channel(worker).call({ kind: \"stats\" }, []);\n if (!reply.ok) throw new Error(reply.error);\n return reply.memoryBytes ?? 0;\n}\n\n/** What workerStats reports about a worker. */\nexport interface WorkerStats {\n /** The wasm linear memory's size, as workerMemory: the peak so far, since it never shrinks. */\n memoryBytes: number;\n /**\n * The Go heap inside it, absent when the wasm was built against goapplib before 0.7.4. Far below\n * memoryBytes means a fresh worker would come back smaller; near it means one would come back\n * just as large.\n */\n heap?: HeapStats;\n}\n\n/**\n * The worker's wasm memory and its Go heap. With `gc`, the worker collects garbage first, so\n * heap.heapAlloc is what it holds live rather than live plus garbage, at the cost of a pause; it\n * waits behind whatever the worker is running, like any request.\n */\nexport async function workerStats(worker: Worker, opts: { gc?: boolean } = {}): Promise<WorkerStats> {\n const reply = await channel(worker).call({ kind: \"stats\", gc: opts.gc === true }, []);\n if (!reply.ok) throw new Error(reply.error);\n return { memoryBytes: reply.memoryBytes ?? 0, heap: reply.heap };\n}\n\n/** Removes the mount `name`. Removing a name that isn't mounted succeeds. */\nexport async function unmountFiles(worker: Worker, name: string): Promise<void> {\n const reply = await channel(worker).call({ kind: \"unmount\", name }, []);\n if (!reply.ok) throw new Error(reply.error);\n}\n","// Turning what a user drops or picks into the {path: bytes} map mountFiles takes. The bytes are\n// read here, before any request, because the Go side can't wait on File.arrayBuffer() mid-request.\nimport type { Files } from \"./protocol\";\n\n// The parts of the File and Directory Entries API used here. Chromium, Firefox and Safari all ship\n// it under the webkit prefix.\ninterface Entry {\n isFile: boolean;\n isDirectory: boolean;\n fullPath: string;\n}\ninterface FileEntry extends Entry {\n file(ok: (f: File) => void, err: (e: unknown) => void): void;\n}\ninterface DirectoryEntry extends Entry {\n createReader(): { readEntries(ok: (es: Entry[]) => void, err: (e: unknown) => void): void };\n}\n\n/**\n * Reads a drop into files keyed by path. A dropped folder keeps its own name as the first path\n * element (\"design/board.edn\"), and dropped loose files sit at the top. Entries the browser can't\n * read as files or folders are skipped.\n */\nexport async function filesFromDrop(dt: DataTransfer): Promise<Files> {\n const entries: Entry[] = [];\n const loose: File[] = [];\n for (const item of Array.from(dt.items)) {\n if (item.kind !== \"file\") continue;\n const entry = (item as DataTransferItem & { webkitGetAsEntry?: () => Entry | null }).webkitGetAsEntry?.();\n if (entry) entries.push(entry);\n else {\n const f = item.getAsFile();\n if (f) loose.push(f);\n }\n }\n const out: Files = {};\n await Promise.all([\n ...entries.map((e) => readEntry(e, out)),\n ...loose.map(async (f) => {\n out[f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n ]);\n return out;\n}\n\n/**\n * Reads an `<input type=\"file\" webkitdirectory>` (or `multiple`) selection into files keyed by\n * path. Folder picks use each file's webkitRelativePath, which starts with the folder's name.\n */\nexport async function filesFromFileList(list: FileList | File[]): Promise<Files> {\n const out: Files = {};\n await Promise.all(\n Array.from(list).map(async (f) => {\n out[f.webkitRelativePath || f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n );\n return out;\n}\n\nasync function readEntry(entry: Entry, out: Files): Promise<void> {\n if (entry.isFile) {\n const f = await new Promise<File>((ok, err) => (entry as FileEntry).file(ok, err));\n out[entry.fullPath.replace(/^\\/+/, \"\")] = new Uint8Array(await f.arrayBuffer());\n return;\n }\n if (!entry.isDirectory) return;\n const reader = (entry as DirectoryEntry).createReader();\n // readEntries returns a batch at a time (100 in Chromium) and an empty batch at the end.\n for (;;) {\n const batch = await new Promise<Entry[]>((ok, err) => reader.readEntries(ok, err));\n if (batch.length === 0) return;\n await Promise.all(batch.map((e) => readEntry(e, out)));\n }\n}\n","// Lanes (goapplib issue 80): more than one worker for one wasm service, with the app routing\n// requests by kind, so a quick request never waits behind a long one. Go's wasm target runs one\n// thread per worker, and a job that never yields keeps that thread busy, so neither a second\n// request nor an abort can reach it. A lane holds one worker it can replace: aborting a request\n// on it terminates the worker, which is the only way to stop a job that never yields, and starts\n// a fresh one, warmed from the shared Cache by the app's warm function.\nimport { endWorker, startWorker, untilBodyEnds, workerFetch, workerStats, type StartWorkerOptions, type WorkerStats } from \"./client\";\n\ntype Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface LaneOptions {\n /**\n * Runs on each new worker before the lane hands it a request: typically a request that loads\n * the service's state from the cache (wasmhost.BrowserCache), so a replacement worker answers\n * like the one it replaced. A warm that throws ends that worker, and the error is what the next\n * request gets; the request after it starts another worker.\n */\n warm?: (fetch: Fetch) => Promise<unknown>;\n /**\n * A memory limit for the lane's worker, in bytes of wasm memory (workerMemory). Wasm memory never\n * shrinks, so a long-lived worker creeps up through requests that each allocate and drop some.\n * When a request finishes (its body read to the end, or failed) and the lane has nothing else\n * in flight, the lane asks the worker how much it holds, and past this limit replaces it with a\n * fresh one, warmed as on an abort. It never interrupts a request, so a lane that's never idle\n * never restarts, and a response whose body nobody reads keeps the lane busy. Size it above what\n * the warmed state needs, or the lane restarts after every request.\n */\n maxMemoryBytes?: number;\n /**\n * Decides from the worker's stats whether to replace it, checked at the same idle moments as\n * maxMemoryBytes. The stats are taken after a collection, so heap.heapAlloc is the live heap,\n * and a worker whose live heap is near its memory would come back just as large; replacing one\n * pays when memoryBytes is far above it. With maxMemoryBytes as well, the lane restarts only when\n * the worker is past that limit and this returns true. heap is absent for a wasm built against\n * goapplib before 0.7.4.\n */\n restartIf?: (stats: WorkerStats) => boolean;\n /** Called when the lane replaces its worker for maxMemoryBytes or restartIf, with its stats. */\n onRestart?: (why: WorkerStats) => void;\n}\n\n/** One replaceable worker. See startLane. */\nexport interface Lane {\n /**\n * A fetch for a Connect transport, like workerFetch, answered by the lane's current worker.\n * Aborting a request (init.signal) rejects it with the signal's reason at once (or errors its\n * body, if it's already streaming), terminates the worker, and starts and warms a new one; other\n * requests still waiting on the old worker are rejected too. A request made meanwhile waits for\n * the new worker.\n */\n fetch: Fetch;\n /** The lane's current worker, once it's started and warmed. */\n worker(): Promise<Worker>;\n /** Replaces the worker, as an abort does, and resolves once the new one is warm. */\n restart(): Promise<void>;\n /** Terminates the worker. Requests after this reject. */\n close(): void;\n}\n\n/**\n * Starts a lane: a worker from `opts`, warmed with `lane.warm`, that the lane replaces whenever a\n * request on it is aborted. Give each kind of request its own lane (a \"serve\" lane for quick\n * queries, a \"jobs\" lane for long jobs) by building each client's transport on that lane's fetch.\n * Every lane of one ns shares the same Cache, which is how a replacement or a second lane gets the\n * state without rebuilding it.\n */\nexport function startLane(opts: StartWorkerOptions, lane: LaneOptions = {}): Lane {\n let closed = false;\n let current!: Promise<Worker>;\n let failed = false;\n\n const boot = () => {\n failed = false;\n const p: Promise<Worker> = startWorker(opts).then(async (w) => {\n if (lane.warm) {\n try {\n await lane.warm(workerFetch(w));\n } catch (err) {\n endWorker(w, err instanceof Error ? err : new Error(String(err)));\n throw err;\n }\n }\n return w;\n });\n p.catch(() => {\n if (current === p) failed = true;\n });\n current = p;\n return p;\n };\n\n const replace = (old: Worker, why: Error) => {\n endWorker(old, why);\n return boot();\n };\n\n let inFlight = 0;\n const checksMemory = lane.maxMemoryBytes !== undefined || lane.restartIf !== undefined;\n // Runs when the lane goes idle. A request that starts while workerStats is out means the lane\n // isn't idle any more, so the restart waits for the next idle moment.\n const checkMemory = async (w: Worker, of: Promise<Worker>) => {\n let stats: WorkerStats;\n try {\n stats = await workerStats(w, { gc: lane.restartIf !== undefined });\n } catch {\n return;\n }\n if (lane.maxMemoryBytes !== undefined && stats.memoryBytes <= lane.maxMemoryBytes) return;\n if (inFlight !== 0 || current !== of || closed) return;\n if (lane.restartIf && !lane.restartIf(stats)) return;\n lane.onRestart?.(stats);\n void replace(w, new Error(\"wasm host lane: restarted past its memory limit\")).catch(() => {});\n };\n\n boot();\n\n return {\n async fetch(input, init) {\n if (closed) throw new Error(\"wasm host lane: closed\");\n const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);\n if (signal?.aborted) throw abortReason(signal);\n if (failed) boot();\n const booting = current;\n const w = await booting;\n if (signal?.aborted) throw abortReason(signal);\n inFlight++;\n let ended = false;\n const end = () => {\n if (ended) return;\n ended = true;\n inFlight--;\n if (inFlight === 0 && checksMemory && current === booting) void checkMemory(w, booting);\n };\n const run = workerFetch(w)(input, init);\n if (!signal) {\n return run.then(\n (res) => untilBodyEnds(res, end),\n (err) => {\n end();\n throw err;\n },\n );\n }\n return new Promise<Response>((resolve, reject) => {\n const onAbort = () => {\n end();\n reject(abortReason(signal));\n if (current === booting) void replace(w, new Error(\"wasm host lane: restarted after an abort\")).catch(() => {});\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n run.then(\n // A streamed body is still coming from the busy worker, so an abort until it ends must\n // still end the worker.\n (res) =>\n resolve(\n untilBodyEnds(res, () => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n }),\n ),\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n reject(err);\n },\n );\n });\n },\n worker: () => current,\n async restart() {\n const old = await current.catch(() => undefined);\n await (old ? replace(old, new Error(\"wasm host lane: restarted\")) : boot());\n },\n close() {\n closed = true;\n void current.then((w) => endWorker(w, new Error(\"wasm host lane: closed\")), () => {});\n },\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n"]}
1
+ {"version":3,"sources":["../../src/wasmhost/client.ts","../../src/wasmhost/dr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IAAA,CAAK,CAAC,CAAA,KAAM,SAAA,CAAU,CAAA,EAAG,IAAI,KAAA,CAAM,wBAAwB,CAAC,CAAA,EAAG,MAAM;AAAA,MAAC,CAAC,CAAA;AAAA,IACtF;AAAA,GACF;AACF;AAEA,SAASA,aAAY,MAAA,EAA8B;AACjD,EAAA,OAAO,MAAA,CAAO,MAAA,IAAU,IAAI,YAAA,CAAa,6BAA6B,YAAY,CAAA;AACpF","file":"index.mjs","sourcesContent":["// The page's side of a wasm host worker (goapplib issue 32). startWorker loads the app's Go wasm in\n// a Web Worker; workerFetch is a fetch to hand a Connect transport, so the app's generated clients\n// talk to the worker exactly as they would to a server; mountFiles pushes files in before the\n// requests that read them.\nimport type { Files, HeapStats, HostChunk, HostReply, HostRequest, HostStatus } from \"./protocol\";\n\nexport type { Files } from \"./protocol\";\n\n/** Where the worker's pieces are served, and the global name the Go side exports under. */\nexport interface StartWorkerOptions {\n /** The built worker script, @panyam/tsappkit/wasmhost/worker.js, as your bundler serves it. */\n worker: string | URL;\n /** The Go wasm build. */\n wasm: string | URL;\n /** Go's wasm_exec.js, from `$(go env GOROOT)/lib/wasm`, matching the Go that built the wasm. */\n exec: string | URL;\n /** The ns the Go program passed to wasmhost.Serve. */\n ns: string;\n}\n\ntype Unsent = HostRequest extends infer R ? (R extends HostRequest ? Omit<R, \"id\"> : never) : never;\n\nclass Channel {\n private next = 1;\n private pending = new Map<\n number,\n { resolve: (r: HostReply) => void; reject: (e: Error) => void; onChunk?: (c: HostChunk) => void }\n >();\n private dead: Error | null = null;\n\n constructor(private worker: Worker) {\n worker.addEventListener(\"message\", (ev: MessageEvent<HostReply | HostStatus | HostChunk>) => {\n const m = ev.data;\n if (\"exited\" in m) {\n this.fail(new Error(`wasm host: ${m.exited}`));\n } else if (\"chunk\" in m) {\n this.pending.get(m.id)?.onChunk?.(m);\n } else if (\"id\" in m) {\n this.pending.get(m.id)?.resolve(m);\n this.pending.delete(m.id);\n }\n });\n worker.addEventListener(\"error\", (ev: ErrorEvent) => this.fail(new Error(`wasm host worker: ${ev.message}`)));\n }\n\n /** Sends req and returns its id with the final reply; chunks before it go to onChunk. */\n start(req: Unsent, transfer: Transferable[], onChunk?: (c: HostChunk) => void): { id: number; done: Promise<HostReply> } {\n const id = this.next++;\n if (this.dead) return { id, done: Promise.reject(this.dead) };\n const done = new Promise<HostReply>((resolve, reject) => {\n this.pending.set(id, { resolve, reject, onChunk });\n this.worker.postMessage({ ...req, id }, transfer);\n });\n return { id, done };\n }\n\n call(req: Unsent, transfer: Transferable[]): Promise<HostReply> {\n return this.start(req, transfer).done;\n }\n\n fail(err: Error) {\n this.dead = err;\n for (const p of this.pending.values()) p.reject(err);\n this.pending.clear();\n }\n}\n\nconst channels = new WeakMap<Worker, Channel>();\n\n/**\n * Terminates worker and rejects every request still waiting on it with `err`, which terminate\n * alone wouldn't do: a terminated worker never replies, so its pending requests would wait forever.\n * For lane.ts; not exported from the package.\n */\nexport function endWorker(worker: Worker, err: Error): void {\n channels.get(worker)?.fail(err);\n worker.terminate();\n}\n\nfunction channel(worker: Worker): Channel {\n let c = channels.get(worker);\n if (!c) {\n c = new Channel(worker);\n channels.set(worker, c);\n }\n return c;\n}\n\n/**\n * Starts the worker and resolves with it once the Go program has installed its exports, or rejects\n * with why it couldn't load (and terminates it, since it can't answer anything). Relative URLs\n * resolve against the page, not the worker script.\n */\nexport function startWorker(opts: StartWorkerOptions): Promise<Worker> {\n const abs = (u: string | URL) => new URL(u, location.href).href;\n const url = new URL(abs(opts.worker));\n url.searchParams.set(\"wasm\", abs(opts.wasm));\n url.searchParams.set(\"exec\", abs(opts.exec));\n url.searchParams.set(\"ns\", opts.ns);\n const worker = new Worker(url);\n channel(worker);\n return new Promise((resolve, reject) => {\n const onMessage = (ev: MessageEvent<HostStatus | HostReply>) => {\n const m = ev.data;\n if (!(\"ready\" in m)) return;\n worker.removeEventListener(\"message\", onMessage);\n if (m.ready) {\n resolve(worker);\n return;\n }\n worker.terminate();\n reject(new Error(`wasm host failed to load: ${m.error}`));\n };\n worker.addEventListener(\"message\", onMessage);\n worker.addEventListener(\n \"error\",\n (ev: ErrorEvent) => {\n worker.terminate();\n reject(new Error(`wasm host worker: ${ev.message}`));\n },\n { once: true },\n );\n });\n}\n\n// Statuses whose Response must have no body.\nconst NULL_BODY = new Set([101, 103, 204, 205, 304]);\n\n/**\n * A fetch that answers in the worker, for `createConnectTransport({ baseUrl, fetch: workerFetch(worker) })`.\n * Only the path and query reach the worker, so baseUrl can be anything absolute, such as\n * location.origin. It rejects if the worker reports an error (no handler, a failed build, a handler\n * panic) and resolves with any HTTP status the handler chose.\n *\n * A handler that flushes (http.Flusher) streams: the Response resolves at its first flush, and its\n * body delivers each flush as it happens, even from a Go loop that never yields, then the rest\n * when the handler returns. Aborting the request (init.signal) rejects it, or errors a body that's\n * already streaming, and cancels the handler's context; a handler sees that the next time it checks\n * ctx, which a loop that never yields to JS doesn't get to do (a lane ends such a worker instead).\n * Once the body is streaming, Chrome's text() and json() report the abort as \"TypeError: Failed to\n * fetch\" rather than an AbortError, so tell an abort from a failure by signal.aborted.\n */\nexport function workerFetch(worker: Worker): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n const c = channel(worker);\n return async (input, init) => {\n const req = new Request(input, init);\n const signal = req.signal;\n if (signal.aborted) throw abortReason(signal);\n const buf = new Uint8Array(await req.arrayBuffer());\n const body = buf.byteLength ? buf : null;\n const headers: Record<string, string> = {};\n req.headers.forEach((v, k) => (headers[k] = v));\n const u = new URL(req.url);\n\n return new Promise<Response>((resolve, reject) => {\n let stream: ReadableStreamDefaultController<Uint8Array> | undefined;\n let settled = false;\n const fail = (err: unknown) => {\n if (settled) return;\n settled = true;\n if (stream) stream.error(err);\n else reject(err);\n };\n const { id, done } = c.start(\n { kind: \"http\", method: req.method, url: u.pathname + u.search, headers, body },\n body ? [body.buffer] : [],\n (chunk) => {\n if (settled) return;\n if (!stream) {\n const status = chunk.status ?? 200;\n const rs = new ReadableStream<Uint8Array>({ start: (ctl) => void (stream = ctl) });\n resolve(new Response(NULL_BODY.has(status) ? null : rs, { status, headers: chunk.headers }));\n }\n if (chunk.body.byteLength) stream!.enqueue(chunk.body);\n },\n );\n const onAbort = () => {\n void c.call({ kind: \"cancel\", target: id }, []).catch(() => {});\n fail(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n done.then(\n (reply) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (!reply.ok) return fail(new Error(reply.error));\n if (settled) return;\n settled = true;\n if (stream) {\n if (reply.body?.byteLength) stream.enqueue(reply.body);\n stream.close();\n return;\n }\n const status = reply.status ?? 200;\n const resBody = NULL_BODY.has(status) ? null : ((reply.body ?? null) as BodyInit | null);\n resolve(new Response(resBody, { status, headers: reply.headers }));\n },\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n fail(err);\n },\n );\n });\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n\n/**\n * A fetch like workerFetch's, except that each call starts a fresh worker from `opts`, sends it that\n * one request, and terminates it once the response is in, whether the request succeeded or not.\n * Ending the worker is the only way to give its wasm memory back to the browser, since wasm memory\n * never shrinks, so route a request with a big transient peak (an ingest that parses a large input\n * on the way to a small result) through this, and have it leave its result in the shared Cache\n * (Go's wasmhost.BrowserCache) for the long-lived worker to load. Every worker for the same `ns`\n * sees the same cache.\n *\n * Each call pays for a worker start and a wasm instantiate, a few hundred ms, so it's for jobs\n * that take seconds, not for ordinary requests. The worker ends when the response's body has been\n * read to the end, fails, or is cancelled, so a streamed body isn't cut short; read or cancel the\n * body, or the worker stays up.\n */\nexport function oneShotFetch(opts: StartWorkerOptions): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {\n return async (input, init) => {\n const worker = await startWorker(opts);\n let res: Response;\n try {\n res = await workerFetch(worker)(input, init);\n } catch (err) {\n worker.terminate();\n throw err;\n }\n return untilBodyEnds(res, () => worker.terminate());\n };\n}\n\n/**\n * res with `end` called once its body has been read to the end, has failed, or has been\n * cancelled (or at once, for a response without a body). For oneShotFetch and lanes, which must\n * not let go of a worker while its streamed body is still arriving. Not exported from the package.\n */\nexport function untilBodyEnds(res: Response, end: () => void): Response {\n if (!res.body) {\n end();\n return res;\n }\n const reader = res.body.getReader();\n const body = new ReadableStream<Uint8Array>({\n async pull(ctl) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n ctl.close();\n end();\n } else {\n ctl.enqueue(value);\n }\n } catch (err) {\n end();\n ctl.error(err);\n }\n },\n cancel(reason) {\n end();\n return reader.cancel(reason);\n },\n });\n return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });\n}\n\n/**\n * Replaces the mount `name` with `files`. The buffers are transferred to the worker, not copied, so\n * each Uint8Array is empty here afterwards; copy first anything the page still needs. Resolves once\n * the worker has mounted them (and, for a rebuild-mode host, rebuilt its handler).\n */\nexport function mountFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"mount\", name, files);\n}\n\n/**\n * Adds `files` to the mount `name`, keeping the files it already holds; a file at a path the mount\n * already has is replaced, and a missing mount is created. This suits a page that brings files in a\n * piece at a time, since it only sends what's new. The worker checks the whole batch first, so a\n * rejection (a path that is already a directory, say) leaves the mount as it was. Buffers are\n * transferred as with mountFiles.\n */\nexport function addFiles(worker: Worker, name: string, files: Files): Promise<void> {\n return sendFiles(worker, \"add\", name, files);\n}\n\nasync function sendFiles(worker: Worker, kind: \"mount\" | \"add\", name: string, files: Files): Promise<void> {\n const transfer = new Set<ArrayBuffer>();\n for (const b of Object.values(files)) {\n // A tag check rather than instanceof, which fails for a buffer from another realm (an iframe),\n // and a SharedArrayBuffer can't be transferred.\n if (Object.prototype.toString.call(b.buffer) === \"[object ArrayBuffer]\") transfer.add(b.buffer as ArrayBuffer);\n }\n const reply = await channel(worker).call({ kind, name, files }, [...transfer]);\n if (!reply.ok) throw new Error(reply.error);\n}\n\n/**\n * The bytes of linear memory the worker's wasm holds. Wasm memory grows and never shrinks, so this\n * is the peak the engine has needed so far, which is what an app weighs before giving a browser a\n * bigger job.\n */\nexport async function workerMemory(worker: Worker): Promise<number> {\n const reply = await channel(worker).call({ kind: \"stats\" }, []);\n if (!reply.ok) throw new Error(reply.error);\n return reply.memoryBytes ?? 0;\n}\n\n/** What workerStats reports about a worker. */\nexport interface WorkerStats {\n /** The wasm linear memory's size, as workerMemory: the peak so far, since it never shrinks. */\n memoryBytes: number;\n /**\n * The Go heap inside it, absent when the wasm was built against goapplib before 0.7.4. Far below\n * memoryBytes means a fresh worker would come back smaller; near it means one would come back\n * just as large.\n */\n heap?: HeapStats;\n}\n\n/**\n * The worker's wasm memory and its Go heap. With `gc`, the worker collects garbage first, so\n * heap.heapAlloc is what it holds live rather than live plus garbage, at the cost of a pause; it\n * waits behind whatever the worker is running, like any request.\n */\nexport async function workerStats(worker: Worker, opts: { gc?: boolean } = {}): Promise<WorkerStats> {\n const reply = await channel(worker).call({ kind: \"stats\", gc: opts.gc === true }, []);\n if (!reply.ok) throw new Error(reply.error);\n return { memoryBytes: reply.memoryBytes ?? 0, heap: reply.heap };\n}\n\n/** Removes the mount `name`. Removing a name that isn't mounted succeeds. */\nexport async function unmountFiles(worker: Worker, name: string): Promise<void> {\n const reply = await channel(worker).call({ kind: \"unmount\", name }, []);\n if (!reply.ok) throw new Error(reply.error);\n}\n","// Turning what a user drops or picks into the {path: bytes} map mountFiles takes. The bytes are\n// read here, before any request, because the Go side can't wait on File.arrayBuffer() mid-request.\nimport type { Files } from \"./protocol\";\n\n// The parts of the File and Directory Entries API used here. Chromium, Firefox and Safari all ship\n// it under the webkit prefix.\ninterface Entry {\n isFile: boolean;\n isDirectory: boolean;\n fullPath: string;\n}\ninterface FileEntry extends Entry {\n file(ok: (f: File) => void, err: (e: unknown) => void): void;\n}\ninterface DirectoryEntry extends Entry {\n createReader(): { readEntries(ok: (es: Entry[]) => void, err: (e: unknown) => void): void };\n}\n\n/**\n * Reads a drop into files keyed by path. A dropped folder keeps its own name as the first path\n * element (\"design/board.edn\"), and dropped loose files sit at the top. Entries the browser can't\n * read as files or folders are skipped.\n */\nexport async function filesFromDrop(dt: DataTransfer): Promise<Files> {\n const entries: Entry[] = [];\n const loose: File[] = [];\n for (const item of Array.from(dt.items)) {\n if (item.kind !== \"file\") continue;\n const entry = (item as DataTransferItem & { webkitGetAsEntry?: () => Entry | null }).webkitGetAsEntry?.();\n if (entry) entries.push(entry);\n else {\n const f = item.getAsFile();\n if (f) loose.push(f);\n }\n }\n const out: Files = {};\n await Promise.all([\n ...entries.map((e) => readEntry(e, out)),\n ...loose.map(async (f) => {\n out[f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n ]);\n return out;\n}\n\n/**\n * Reads an `<input type=\"file\" webkitdirectory>` (or `multiple`) selection into files keyed by\n * path. Folder picks use each file's webkitRelativePath, which starts with the folder's name.\n */\nexport async function filesFromFileList(list: FileList | File[]): Promise<Files> {\n const out: Files = {};\n await Promise.all(\n Array.from(list).map(async (f) => {\n out[f.webkitRelativePath || f.name] = new Uint8Array(await f.arrayBuffer());\n }),\n );\n return out;\n}\n\nasync function readEntry(entry: Entry, out: Files): Promise<void> {\n if (entry.isFile) {\n const f = await new Promise<File>((ok, err) => (entry as FileEntry).file(ok, err));\n out[entry.fullPath.replace(/^\\/+/, \"\")] = new Uint8Array(await f.arrayBuffer());\n return;\n }\n if (!entry.isDirectory) return;\n const reader = (entry as DirectoryEntry).createReader();\n // readEntries returns a batch at a time (100 in Chromium) and an empty batch at the end.\n for (;;) {\n const batch = await new Promise<Entry[]>((ok, err) => reader.readEntries(ok, err));\n if (batch.length === 0) return;\n await Promise.all(batch.map((e) => readEntry(e, out)));\n }\n}\n","// Lanes (goapplib issue 80): more than one worker for one wasm service, with the app routing\n// requests by kind, so a quick request never waits behind a long one. Go's wasm target runs one\n// thread per worker, and a job that never yields keeps that thread busy, so neither a second\n// request nor an abort can reach it. A lane holds one worker it can replace: aborting a request\n// on it terminates the worker, which is the only way to stop a job that never yields, and starts\n// a fresh one, warmed from the shared Cache by the app's warm function.\nimport { endWorker, startWorker, untilBodyEnds, workerFetch, workerStats, type StartWorkerOptions, type WorkerStats } from \"./client\";\n\ntype Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface LaneOptions {\n /**\n * Runs on each new worker before the lane hands it a request: typically a request that loads\n * the service's state from the cache (wasmhost.BrowserCache), so a replacement worker answers\n * like the one it replaced. A warm that throws ends that worker, and the error is what the next\n * request gets; the request after it starts another worker.\n */\n warm?: (fetch: Fetch) => Promise<unknown>;\n /**\n * A memory limit for the lane's worker, in bytes of wasm memory (workerMemory). Wasm memory never\n * shrinks, so a long-lived worker creeps up through requests that each allocate and drop some.\n * When a request finishes (its body read to the end, or failed) and the lane has nothing else\n * in flight, the lane asks the worker how much it holds, and past this limit replaces it with a\n * fresh one, warmed as on an abort. It never interrupts a request, so a lane that's never idle\n * never restarts, and a response whose body nobody reads keeps the lane busy. Size it above what\n * the warmed state needs, or the lane restarts after every request.\n */\n maxMemoryBytes?: number;\n /**\n * Decides from the worker's stats whether to replace it, checked at the same idle moments as\n * maxMemoryBytes. The stats are taken after a collection, so heap.heapAlloc is the live heap,\n * and a worker whose live heap is near its memory would come back just as large; replacing one\n * pays when memoryBytes is far above it. With maxMemoryBytes as well, the lane restarts only when\n * the worker is past that limit and this returns true, and a worker under the limit isn't asked\n * to collect. Without maxMemoryBytes every idle moment pays a collection (187 ms on a 377 MB\n * live heap in agni), so set both. heap is absent for a wasm built against goapplib before 0.7.4.\n */\n restartIf?: (stats: WorkerStats) => boolean;\n /** Called when the lane replaces its worker for maxMemoryBytes or restartIf, with its stats. */\n onRestart?: (why: WorkerStats) => void;\n}\n\n/** One replaceable worker. See startLane. */\nexport interface Lane {\n /**\n * A fetch for a Connect transport, like workerFetch, answered by the lane's current worker.\n * Aborting a request (init.signal) rejects it with the signal's reason at once (or errors its\n * body, if it's already streaming), terminates the worker, and starts and warms a new one; other\n * requests still waiting on the old worker are rejected too. A request made meanwhile waits for\n * the new worker.\n */\n fetch: Fetch;\n /** The lane's current worker, once it's started and warmed. */\n worker(): Promise<Worker>;\n /** Replaces the worker, as an abort does, and resolves once the new one is warm. */\n restart(): Promise<void>;\n /** Terminates the worker. Requests after this reject. */\n close(): void;\n}\n\n/**\n * Starts a lane: a worker from `opts`, warmed with `lane.warm`, that the lane replaces whenever a\n * request on it is aborted. Give each kind of request its own lane (a \"serve\" lane for quick\n * queries, a \"jobs\" lane for long jobs) by building each client's transport on that lane's fetch.\n * Every lane of one ns shares the same Cache, which is how a replacement or a second lane gets the\n * state without rebuilding it.\n */\nexport function startLane(opts: StartWorkerOptions, lane: LaneOptions = {}): Lane {\n let closed = false;\n let current!: Promise<Worker>;\n let failed = false;\n\n const boot = () => {\n failed = false;\n const p: Promise<Worker> = startWorker(opts).then(async (w) => {\n if (lane.warm) {\n try {\n await lane.warm(workerFetch(w));\n } catch (err) {\n endWorker(w, err instanceof Error ? err : new Error(String(err)));\n throw err;\n }\n }\n return w;\n });\n p.catch(() => {\n if (current === p) failed = true;\n });\n current = p;\n return p;\n };\n\n const replace = (old: Worker, why: Error) => {\n endWorker(old, why);\n return boot();\n };\n\n let inFlight = 0;\n const checksMemory = lane.maxMemoryBytes !== undefined || lane.restartIf !== undefined;\n // Runs when the lane goes idle. A request that starts while workerStats is out means the lane\n // isn't idle any more, so the restart waits for the next idle moment. The limit is read first\n // without a collection, which can take a fifth of a second on a big heap (#121), so a worker\n // under it is never asked to collect.\n const checkMemory = async (w: Worker, of: Promise<Worker>) => {\n const idle = () => inFlight === 0 && current === of && !closed;\n let stats: WorkerStats | undefined;\n try {\n if (lane.maxMemoryBytes !== undefined) {\n stats = await workerStats(w);\n if (stats.memoryBytes <= lane.maxMemoryBytes || !idle()) return;\n }\n if (lane.restartIf) {\n stats = await workerStats(w, { gc: true });\n if (!idle() || !lane.restartIf(stats)) return;\n }\n } catch {\n return;\n }\n if (!stats) return;\n lane.onRestart?.(stats);\n void replace(w, new Error(\"wasm host lane: restarted past its memory limit\")).catch(() => {});\n };\n\n boot();\n\n return {\n async fetch(input, init) {\n if (closed) throw new Error(\"wasm host lane: closed\");\n const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);\n if (signal?.aborted) throw abortReason(signal);\n if (failed) boot();\n const booting = current;\n const w = await booting;\n if (signal?.aborted) throw abortReason(signal);\n inFlight++;\n let ended = false;\n const end = () => {\n if (ended) return;\n ended = true;\n inFlight--;\n if (inFlight === 0 && checksMemory && current === booting) void checkMemory(w, booting);\n };\n const run = workerFetch(w)(input, init);\n if (!signal) {\n return run.then(\n (res) => untilBodyEnds(res, end),\n (err) => {\n end();\n throw err;\n },\n );\n }\n return new Promise<Response>((resolve, reject) => {\n const onAbort = () => {\n end();\n reject(abortReason(signal));\n if (current === booting) void replace(w, new Error(\"wasm host lane: restarted after an abort\")).catch(() => {});\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n run.then(\n // A streamed body is still coming from the busy worker, so an abort until it ends must\n // still end the worker.\n (res) =>\n resolve(\n untilBodyEnds(res, () => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n }),\n ),\n (err) => {\n signal.removeEventListener(\"abort\", onAbort);\n end();\n reject(err);\n },\n );\n });\n },\n worker: () => current,\n async restart() {\n const old = await current.catch(() => undefined);\n await (old ? replace(old, new Error(\"wasm host lane: restarted\")) : boot());\n },\n close() {\n closed = true;\n void current.then((w) => endWorker(w, new Error(\"wasm host lane: closed\")), () => {});\n },\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"This request was aborted.\", \"AbortError\");\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panyam/tsappkit",
3
- "version": "0.7.4",
3
+ "version": "0.7.6",
4
4
  "description": "TypeScript application toolkit with component lifecycle management, event system, UI utilities, and documentation site components",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
package/src/Port.ts ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The views a presenter drives through one typed view interface, its "port"
3
+ * (docs/PRESENTER_CONTRACT_THESIS.md, Principle 3). A presenter keeps one Port
4
+ * per interface it talks to, so one presenter can drive several islands on a
5
+ * page without an EventBus or a store between them:
6
+ *
7
+ * readonly tools = new Port<ToolsView>((v) => v.setToolState(this.state));
8
+ * select(t: Tool) { this.state = ...; this.tools.each((v) => v.setToolState(this.state)); }
9
+ *
10
+ * Islands mount at different times (a `visible` one may mount long after the
11
+ * page started), so a view attached late has missed every command sent so far.
12
+ * The replay passed to the constructor runs on each view as it attaches and
13
+ * should send the presenter's current state, which is how a late view catches
14
+ * up. A port takes any number of views, including none: commands to an empty
15
+ * port go nowhere.
16
+ */
17
+ export class Port<V> {
18
+ private readonly views = new Set<V>();
19
+
20
+ /** @param replay runs on each view as it attaches, to bring it up to date. */
21
+ constructor(private readonly replay?: (view: V) => void) {}
22
+
23
+ /**
24
+ * Adds a view, runs the replay on it, and returns the function that removes
25
+ * it again. An island attaches when it activates and detaches when it
26
+ * deactivates (tsappkit-solid's useView does both). Attaching the same view
27
+ * twice keeps one copy, and calling the returned function more than once is
28
+ * harmless.
29
+ */
30
+ attach(view: V): () => void {
31
+ this.views.add(view);
32
+ this.replay?.(view);
33
+ return () => {
34
+ this.views.delete(view);
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Sends a command to every view attached when it's called, in the order they
40
+ * attached. A view may detach (or attach another) from inside the command.
41
+ * A view that throws stops the command reaching the views after it.
42
+ */
43
+ each(send: (view: V) => void): void {
44
+ for (const view of [...this.views]) send(view);
45
+ }
46
+
47
+ /** How many views are attached. */
48
+ get size(): number {
49
+ return this.views.size;
50
+ }
51
+ }
package/src/index.ts CHANGED
@@ -27,6 +27,9 @@ export { TemplateLoader } from './TemplateLoader';
27
27
  export { SplashScreen } from './SplashScreen';
28
28
  export { MobileBottomDrawer } from './MobileBottomDrawer';
29
29
 
30
+ // Presenter ports (one presenter driving several views)
31
+ export { Port } from './Port';
32
+
30
33
  // Island pages (islands mounted from a server-written page spec)
31
34
  export { IslandPage } from './page/IslandPage';
32
35
  export { readSpec, SPEC_ELEMENT_ID } from './page/spec';
@@ -31,8 +31,9 @@ export interface LaneOptions {
31
31
  * maxMemoryBytes. The stats are taken after a collection, so heap.heapAlloc is the live heap,
32
32
  * and a worker whose live heap is near its memory would come back just as large; replacing one
33
33
  * pays when memoryBytes is far above it. With maxMemoryBytes as well, the lane restarts only when
34
- * the worker is past that limit and this returns true. heap is absent for a wasm built against
35
- * goapplib before 0.7.4.
34
+ * the worker is past that limit and this returns true, and a worker under the limit isn't asked
35
+ * to collect. Without maxMemoryBytes every idle moment pays a collection (187 ms on a 377 MB
36
+ * live heap in agni), so set both. heap is absent for a wasm built against goapplib before 0.7.4.
36
37
  */
37
38
  restartIf?: (stats: WorkerStats) => boolean;
38
39
  /** Called when the lane replaces its worker for maxMemoryBytes or restartIf, with its stats. */
@@ -97,17 +98,25 @@ export function startLane(opts: StartWorkerOptions, lane: LaneOptions = {}): Lan
97
98
  let inFlight = 0;
98
99
  const checksMemory = lane.maxMemoryBytes !== undefined || lane.restartIf !== undefined;
99
100
  // Runs when the lane goes idle. A request that starts while workerStats is out means the lane
100
- // isn't idle any more, so the restart waits for the next idle moment.
101
+ // isn't idle any more, so the restart waits for the next idle moment. The limit is read first
102
+ // without a collection, which can take a fifth of a second on a big heap (#121), so a worker
103
+ // under it is never asked to collect.
101
104
  const checkMemory = async (w: Worker, of: Promise<Worker>) => {
102
- let stats: WorkerStats;
105
+ const idle = () => inFlight === 0 && current === of && !closed;
106
+ let stats: WorkerStats | undefined;
103
107
  try {
104
- stats = await workerStats(w, { gc: lane.restartIf !== undefined });
108
+ if (lane.maxMemoryBytes !== undefined) {
109
+ stats = await workerStats(w);
110
+ if (stats.memoryBytes <= lane.maxMemoryBytes || !idle()) return;
111
+ }
112
+ if (lane.restartIf) {
113
+ stats = await workerStats(w, { gc: true });
114
+ if (!idle() || !lane.restartIf(stats)) return;
115
+ }
105
116
  } catch {
106
117
  return;
107
118
  }
108
- if (lane.maxMemoryBytes !== undefined && stats.memoryBytes <= lane.maxMemoryBytes) return;
109
- if (inFlight !== 0 || current !== of || closed) return;
110
- if (lane.restartIf && !lane.restartIf(stats)) return;
119
+ if (!stats) return;
111
120
  lane.onRestart?.(stats);
112
121
  void replace(w, new Error("wasm host lane: restarted past its memory limit")).catch(() => {});
113
122
  };