okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
1.3 KiB34 linesraw
1/** One active inference request; queued work is cancellable and never survives host exit. */
2export class RequestQueue {
3  #pending = [];
4  #active = false;
5  constructor(onChange = () => {}) { this.onChange = onChange; }
6  get waiting() { return this.#pending.length; }
7  run(signal, task) {
8    return new Promise((resolve, reject) => {
9      const entry = { signal, task, resolve, reject, abort: null };
10      entry.abort = () => {
11        const index = this.#pending.indexOf(entry);
12        if (index < 0) return;
13        this.#pending.splice(index, 1);
14        reject(signal.reason ?? new DOMException('Request cancelled', 'AbortError'));
15        this.onChange(this.waiting);
16      };
17      if (signal.aborted) { reject(signal.reason); return; }
18      signal.addEventListener('abort', entry.abort, { once: true });
19      this.#pending.push(entry);
20      this.#drain();
21    });
22  }
23  async #drain() {
24    if (this.#active) { this.onChange(this.waiting); return; }
25    const entry = this.#pending.shift();
26    if (!entry) { this.onChange(0); return; }
27    this.#active = true;
28    entry.signal.removeEventListener('abort', entry.abort);
29    this.onChange(this.waiting);
30    try { entry.signal.throwIfAborted(); entry.resolve(await entry.task()); }
31    catch (error) { entry.reject(error); }
32    finally { this.#active = false; this.#drain(); }
33  }
34}