/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/native/job-poller * * Generic completion poller for native job handles. * * Native libraries expose non-blocking work as job ids: * * ```text * id = submit(...) // returns immediately * completedSeq() // monotonic counter, bumped when any job resolves * take(id) -> ptr | NULL // NULL while pending; owned string once done * cancel(id) // abort and discard * ``` * * One poller per library multiplexes every pending job on a single timer: a * tick costs one FFI call unless `completedSeq` changed, and the delay backs * off exponentially while nothing completes, so an idle process does not spin * and the JavaScript event loop is never blocked. */ /** Pointer-like value returned by `take` (Bun FFI pointers are numbers). */ export type NativeOwnedPointer = number | bigint | null | undefined; export interface JobPollerSpec { /** Monotonic completion counter of the library. */ completedSeq(): number | bigint; /** Owned result pointer for a finished job, `null`/`0` while pending. */ take(id: number): NativeOwnedPointer; /** Cancels a job and discards its result. */ cancel(id: number): unknown; /** Copies and frees an owned string pointer. */ readString(pointer: NonNullable): string; /** Initial polling delay (default 1 ms). */ minDelayMs?: number; /** Upper bound of the back-off (default 25 ms). */ maxDelayMs?: number; } export interface JobPoller { /** Resolves with the job's raw result string; rejects with `AbortError`. */ awaitJob(id: number, signal?: AbortSignal): Promise; /** Jobs awaited by this poller that have not resolved yet. */ pendingCount(): number; } interface Pending { resolve: (value: string) => void; reject: (error: Error) => void; signal?: AbortSignal; onAbort?: () => void; } function abortError(signal?: AbortSignal): Error { const reason = signal?.reason; if (reason instanceof Error && reason.name === "AbortError") return reason; return new DOMException("The native job was aborted", "AbortError"); } /** Creates a poller bound to one native library's job functions. */ export function createJobPoller(spec: JobPollerSpec): JobPoller { const minDelay = Math.max(0, spec.minDelayMs ?? 1); const maxDelay = Math.max(minDelay, spec.maxDelayMs ?? 25); const pending = new Map(); let lastSeq: number | bigint = -1; let timer: ReturnType | null = null; let delay = minDelay; const schedule = () => { if (timer !== null || pending.size === 0) return; timer = setTimeout(tick, delay); }; const settle = (id: number, entry: Pending) => { pending.delete(id); if (entry.onAbort) entry.signal?.removeEventListener("abort", entry.onAbort); }; function tick(): void { timer = null; let seq: number | bigint; try { seq = spec.completedSeq(); } catch (err) { const error = err instanceof Error ? err : new Error(String(err)); for (const [id, entry] of pending) { settle(id, entry); entry.reject(error); } return; } if (seq !== lastSeq) { lastSeq = seq; for (const [id, entry] of pending) { const pointer = spec.take(id); if (!pointer) continue; settle(id, entry); try { entry.resolve(spec.readString(pointer)); } catch (err) { entry.reject(err instanceof Error ? err : new Error(String(err))); } } delay = minDelay; } else { delay = Math.min(Math.max(delay * 2, 1), maxDelay); } schedule(); } return { awaitJob(id, signal) { return new Promise((resolve, reject) => { if (signal?.aborted) { spec.cancel(id); reject(abortError(signal)); return; } const entry: Pending = { resolve, reject, signal }; if (signal) { entry.onAbort = () => { if (!pending.has(id)) return; settle(id, entry); spec.cancel(id); reject(abortError(signal)); }; signal.addEventListener("abort", entry.onAbort, { once: true }); } pending.set(id, entry); delay = minDelay; if (timer !== null) { clearTimeout(timer); timer = null; } schedule(); }); }, pendingCount: () => pending.size, }; }