@mark1russell7/service 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -400,6 +400,7 @@ const response = await retry(
400
400
  | `timeout(ms, clock)` | It makes a channel that gets one value after `ms`, on the clock. |
401
401
  | `ticker(ms, clock)` | It makes a channel of ticks. Tick k comes due at the start plus (k + 1) periods, so the ticks do not drift. |
402
402
  | `pipeline`, `fanOut`, `fanIn`, `merge`, `workerPool` | They start work between channels. Each failure goes to `onError`, and the output closes. |
403
+ | `preemptivePool(max)` | It operates at most `max` tasks at a time. A new task stops the oldest task with a `PreemptedError`, and `stop` stops each task. |
403
404
 
404
405
  - **The clock.** `timeout` and `ticker` take a clock. The default is `realClock`. A test gives `fakeClock()` of `./testing`, and the time of each channel is then exact.
405
406
  - **The timer of a timeout.** `timeout` gives no cancel, as `time.After` of Go. Its timer stays until it comes due, also after `select` takes another case.
@@ -133,5 +133,33 @@ export interface WorkerPoolOptions<T> {
133
133
  * worker is done. A failed job goes to `onError`, and its worker takes the next job.
134
134
  */
135
135
  export declare const workerPool: <T, R>(jobs: Channel<T>, worker: (job: T) => Promise<R>, options?: WorkerPoolOptions<T>) => Channel<R>;
136
+ /**
137
+ * This error is the reason of a task that a `preemptivePool` stopped: a newer task took its place,
138
+ * or `stop` stopped it. A caller tells it from a failure of the task with `instanceof`.
139
+ */
140
+ export declare class PreemptedError extends Error {
141
+ override readonly name = "PreemptedError";
142
+ }
143
+ /** A pool that runs at most `max` tasks at a time, and stops the oldest task for a new task. */
144
+ export interface PreemptivePool {
145
+ /**
146
+ * This method starts `task` with a signal. When the pool is full, it first stops the oldest task.
147
+ * The promise of a stopped task rejects at once with the reason of its signal, and the signal
148
+ * tells the task to stop its work.
149
+ */
150
+ run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R>;
151
+ /** This method stops each task that runs. The reason is `reason`, or a `PreemptedError`. */
152
+ stop(reason?: unknown): void;
153
+ /** This count is the number of tasks that run. */
154
+ readonly size: number;
155
+ }
156
+ /**
157
+ * This function makes a pool of at most `max` tasks. The newest task always operates: a new task in a
158
+ * full pool stops the oldest task. This is the policy for work whose old results nobody reads, for
159
+ * example the load of a page that the user left. `workerPool` keeps each job in a queue instead.
160
+ *
161
+ * @throws RangeError when `max` is not an integer of 1 or more.
162
+ */
163
+ export declare const preemptivePool: (max: number) => PreemptivePool;
136
164
  //#endregion
137
165
  //# sourceMappingURL=channel.d.ts.map
package/build/channel.js CHANGED
@@ -259,7 +259,50 @@ const workerPool = (jobs, worker, options = {}) => {
259
259
  Promise.all(workers).then(() => results.close());
260
260
  return results;
261
261
  };
262
+ /**
263
+ * This error is the reason of a task that a `preemptivePool` stopped: a newer task took its place,
264
+ * or `stop` stopped it. A caller tells it from a failure of the task with `instanceof`.
265
+ */
266
+ var PreemptedError = class extends Error {
267
+ name = "PreemptedError";
268
+ };
269
+ /**
270
+ * This function makes a pool of at most `max` tasks. The newest task always operates: a new task in a
271
+ * full pool stops the oldest task. This is the policy for work whose old results nobody reads, for
272
+ * example the load of a page that the user left. `workerPool` keeps each job in a queue instead.
273
+ *
274
+ * @throws RangeError when `max` is not an integer of 1 or more.
275
+ */
276
+ const preemptivePool = (max) => {
277
+ if (!(Number.isInteger(max) && max >= 1)) throw new RangeError(`preemptivePool: max is an integer of 1 or more, not ${max}.`);
278
+ const running = /* @__PURE__ */ new Set();
279
+ const preempt = (controller, reason) => {
280
+ running.delete(controller);
281
+ controller.abort(reason);
282
+ };
283
+ return {
284
+ run(task) {
285
+ for (const oldest of running) {
286
+ if (running.size < max) break;
287
+ preempt(oldest, new PreemptedError("A newer task took the place of this task."));
288
+ }
289
+ const controller = new AbortController();
290
+ running.add(controller);
291
+ const stopped = new Promise((_resolve, reject) => {
292
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
293
+ });
294
+ const done = Promise.resolve().then(() => task(controller.signal));
295
+ return Promise.race([done, stopped]).finally(() => running.delete(controller));
296
+ },
297
+ stop(reason) {
298
+ for (const controller of [...running]) preempt(controller, reason ?? new PreemptedError("The pool stopped this task."));
299
+ },
300
+ get size() {
301
+ return running.size;
302
+ }
303
+ };
304
+ };
262
305
  //#endregion
263
- export { Channel, buffered, channel, fanIn, fanOut, merge, pipeline, select, ticker, timeout, unbuffered, workerPool };
306
+ export { Channel, PreemptedError, buffered, channel, fanIn, fanOut, merge, pipeline, preemptivePool, select, ticker, timeout, unbuffered, workerPool };
264
307
 
265
308
  //# sourceMappingURL=channel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"channel.js","names":[],"sources":["../src/channel.ts"],"sourcesContent":["// @mark1russell7/service/channel: channels in the style of Go, on the clock of the service. It\n// imports only ./clock.ts and @mark1russell7/collections: no `node:` module and no zod. Thus a\n// client in a browser can use it, as it uses ./clock.\n//\n// The code came from @mark1russell7/collections 0.7 (the review of its API, C12, S2). The changes:\n// `timeout` and `ticker` take a clock, `ticker` does not drift, the functions that start work give\n// each failure to `onError` and write nothing to the console, and `fanIn` and `merge` take an array.\n\nimport { asyncQueue, type AsyncQueue } from \"@mark1russell7/collections\";\nimport { realClock, type Cancel, type Clock } from \"./clock.ts\";\n\n/** This function gets a failure of the work that a function of this entry started. */\nexport type ErrorHandler = (error: unknown) => void;\n\n/** These options are for a function that starts work and gives an output channel. */\nexport interface FlowOptions {\n /** The size of the buffer of each output channel. The default is 0: a send waits for a receiver. */\n readonly bufferSize?: number | undefined;\n /**\n * This function gets each failure of the work. The output closes after a failure. Without it,\n * the failure is lost, but the output also closes.\n */\n readonly onError?: ErrorHandler | undefined;\n}\n\n/**\n * A channel carries values from senders to receivers, as a channel of Go does. A channel with a\n * buffer of 0 is a rendezvous: each send waits for a receiver.\n */\nexport class Channel<T> {\n private readonly queue: AsyncQueue<T>;\n private closed = false;\n\n /** This constructor makes a channel with a buffer of `bufferSize` values. The default is 0. */\n constructor(bufferSize = 0) {\n // A buffer of 0 makes a send wait for a receiver (before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17)\n this.queue = asyncQueue<T>({ capacity: bufferSize });\n }\n\n /**\n * This method sends a value. It waits while the buffer is full and no receiver waits.\n *\n * @throws Error when the channel is closed.\n */\n async send(value: T): Promise<void> {\n if (this.closed) throw new Error(\"Cannot send on closed channel\");\n await this.queue.put(value);\n }\n\n /**\n * This method receives a value. It waits while the channel has no value.\n *\n * @throws Error when the channel is closed and empty.\n */\n async receive(): Promise<T> {\n return await this.queue.take();\n }\n\n /**\n * This method waits for one value, as `receive` does, and gives it to `onValue`. When the\n * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in\n * the call that sends the value or closes the channel.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no value yet.\n */\n waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {\n return this.queue.waitTake(onValue, onClosed);\n }\n\n /** This method sends a value if a receiver or the buffer takes it at once. It gives false when not. */\n trySend(value: T): boolean {\n if (this.closed) return false;\n return this.queue.tryPut(value);\n }\n\n /** This method receives a value if the channel has one at once. It gives undefined when not. */\n tryReceive(): T | undefined {\n return this.queue.tryTake();\n }\n\n /** This method closes the channel. A send then fails, but a receiver can take the values that stay. */\n close(): void {\n this.closed = true;\n this.queue.close();\n }\n\n /** This value is true after `close`. */\n get isClosed(): boolean {\n return this.closed;\n }\n\n /** This value is the count of values in the buffer. */\n get size(): number {\n return this.queue.size;\n }\n\n /** This method makes a case of `select` for this channel. `handler` gets the value of the case. */\n case<R>(handler: (value: T) => R): SelectCase<R> {\n return {\n // The value of each call comes from this channel, so it has the type T\n handler: (value) => handler(value as T),\n wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),\n };\n }\n\n /** This iteration receives each value. It stops when the channel is closed and empty. */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n let value: T;\n try {\n value = await this.receive();\n } catch {\n // The channel is closed and empty\n return;\n }\n yield value;\n }\n }\n}\n\n/** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */\nexport type Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;\n\n/** A case of `select`: a wait for one value, and the function that gets the value. `Channel.case` makes one. */\nexport interface SelectCase<R> {\n /** This function gets the value of the case, when the case wins. */\n readonly handler: (value: unknown) => R;\n /** This function waits for one value of the case. `select` withdraws it when another case wins. */\n readonly wait: Wait;\n}\n\n/**\n * This function gives the first value of the waits, with the index of its wait. It rejects with\n * the error of the first wait whose channel is closed and empty. It withdraws each other wait in\n * the same call, so a later value stays in its channel (before, the receives of the cases that\n * lost stayed in their channels and dropped the next value of each: audit O56).\n */\nconst firstOf = (waits: readonly Wait[]): Promise<{ index: number; value: unknown }> =>\n new Promise((resolve, reject) => {\n const withdraws: Array<() => boolean> = [];\n let settled = false;\n const end = (): void => {\n settled = true;\n for (const withdraw of withdraws) withdraw();\n };\n // A wait can call back at once, in its own call, when its channel has a value or is closed\n try {\n for (let index = 0; index < waits.length && !settled; index++) {\n withdraws.push(\n waits[index]!(\n (value) => {\n if (settled) return;\n end();\n resolve({ index, value });\n },\n (error) => {\n if (settled) return;\n end();\n reject(error);\n },\n ),\n );\n }\n } catch (error) {\n // A wait that throws: the waits before it are withdrawn\n if (!settled) end();\n reject(error);\n }\n });\n\n/**\n * This function waits for the first case with a value, as the `select` of Go does, and gives the\n * result of its handler. A case that loses keeps no receive: a later value stays in its channel.\n * When the channel of a case is closed and empty, the promise rejects.\n *\n * @example\n * const result = await select(data.case((v) => `data ${v}`), timeout(1000).case(() => \"late\"));\n */\nexport const select = async <R>(...cases: readonly SelectCase<R>[]): Promise<R> => {\n const { index, value } = await firstOf(cases.map((c) => c.wait));\n // The handler runs after the race, not in the call of the sender\n return cases[index]!.handler(value);\n};\n\n/**\n * This function makes a channel that gets one value after `ms` milliseconds of `clock`, and then\n * closes. A case of it in `select` is a time limit.\n */\nexport const timeout = (ms: number, clock: Clock = realClock): Channel<void> => {\n const ch = new Channel<void>();\n clock.after(ms, () => {\n // The value waits for a receiver. The close lets the receivers after it fail at once.\n ch.send(undefined).catch(() => undefined);\n ch.close();\n });\n return ch;\n};\n\n/** A ticker is a channel of the numbers of its ticks. `stop` stops its timer and closes it. */\nexport type Ticker = Channel<number> & { readonly stop: () => void };\n\n/**\n * This function makes a channel that gets a tick each `ms` milliseconds of `clock`. Tick k (from 0)\n * comes due at start + (k + 1) * ms, so the ticks do not drift. A late timer gives the number of\n * the last tick that came due, and skips the ticks that it missed. The buffer has 1 value: a slow\n * receiver loses ticks, as with the ticker of Go.\n */\nexport const ticker = (ms: number, clock: Clock = realClock): Ticker => {\n if (!(Number.isFinite(ms) && ms > 0)) throw new RangeError(`The period of a ticker is a finite number above 0, not ${ms}`);\n const ch = new Channel<number>(1);\n const start = clock.now();\n let cancel: Cancel | undefined;\n const arm = (tick: number): void => {\n cancel = clock.after(Math.max(0, start + (tick + 1) * ms - clock.now()), () => {\n const due = Math.max(tick, Math.floor((clock.now() - start) / ms) - 1);\n ch.trySend(due);\n arm(due + 1);\n });\n };\n arm(0);\n return Object.assign(ch, {\n stop: () => {\n cancel?.();\n ch.close();\n },\n });\n};\n\n/** This function starts `work`. It gives a failure to `onError`, and it calls `end` after the work in each case. */\nconst run = (work: () => Promise<void>, end: () => void, onError: ErrorHandler | undefined): void => {\n void work()\n .catch((error: unknown) => onError?.(error))\n .finally(end);\n};\n\n/**\n * This function gives a channel of `transform` of each value of `input`. The output closes when\n * `input` is closed and empty, or after a failure of `transform`.\n */\nexport const pipeline = <T, U>(input: Channel<T>, transform: (value: T) => U | Promise<U>, options: FlowOptions = {}): Channel<U> => {\n const output = new Channel<U>(options.bufferSize);\n run(\n async () => {\n for await (const value of input) await output.send(await transform(value));\n },\n () => output.close(),\n options.onError,\n );\n return output;\n};\n\n/**\n * This function gives `count` channels. Each one gets each value of `input`. The outputs close when\n * `input` is closed and empty, or after a failed send.\n */\nexport const fanOut = <T>(input: Channel<T>, count: number, options: FlowOptions = {}): Channel<T>[] => {\n const outputs = Array.from({ length: count }, () => new Channel<T>(options.bufferSize));\n run(\n async () => {\n for await (const value of input) await Promise.all(outputs.map((ch) => ch.send(value)));\n },\n () => {\n for (const ch of outputs) ch.close();\n },\n options.onError,\n );\n return outputs;\n};\n\n/**\n * This function gives one channel with the values of all `inputs`. The output closes when each\n * input is closed and empty. A failed send of one input goes to `onError`.\n */\nexport const fanIn = <T>(inputs: readonly Channel<T>[], options: FlowOptions = {}): Channel<T> => {\n const output = new Channel<T>(options.bufferSize);\n const workers = inputs.map(async (input) => {\n for await (const value of input) await output.send(value);\n });\n // All the workers settle, then the output closes, also after a failed send\n void Promise.allSettled(workers).then((results) => {\n output.close();\n for (const result of results) if (result.status === \"rejected\") options.onError?.(result.reason);\n });\n return output;\n};\n\n/**\n * This function gives one channel with the values of `inputs`, as `fanIn` does, but it closes when\n * the first input is closed and empty. It takes one value at a time, from the inputs in turn, and\n * keeps no receive on an input while it waits for the reader. Thus each value reaches the output\n * one time, in the order of its input, or stays in its input. With no input, the output is closed.\n */\nexport const merge = <T>(inputs: readonly Channel<T>[]): Channel<T> => {\n const output = new Channel<T>();\n // With no input, no input can give a value, so the output is closed at once, as with fanIn\n if (inputs.length === 0) {\n output.close();\n return output;\n }\n void (async () => {\n // The input after the input of the last value comes first, so a busy input starves no other\n let start = 0;\n while (true) {\n const order = inputs.map((_, offset) => (start + offset) % inputs.length);\n let next: { index: number; value: unknown };\n try {\n next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));\n } catch {\n // An input is closed and empty\n break;\n }\n const index = order[next.index]!;\n start = (index + 1) % inputs.length;\n try {\n // The value came from inputs[index], so it has the type T\n await output.send(next.value as T);\n } catch {\n // The reader closed the output\n break;\n }\n }\n output.close();\n })();\n return output;\n};\n\n/** This function makes a channel with a buffer of `capacity` values. */\nexport const buffered = <T>(capacity: number): Channel<T> => new Channel<T>(capacity);\n\n/** This function makes a channel with no buffer: each send waits for a receiver. */\nexport const unbuffered = <T>(): Channel<T> => new Channel<T>(0);\n\n/** This function makes a channel with a buffer of `bufferSize` values. The default is 0. */\nexport const channel = <T>(bufferSize = 0): Channel<T> => new Channel<T>(bufferSize);\n\n/** These options are for `workerPool`. */\nexport interface WorkerPoolOptions<T> {\n /** The count of workers. The default is 1. */\n readonly workers?: number | undefined;\n /** The size of the buffer of the results. The default is 0. */\n readonly bufferSize?: number | undefined;\n /** This function gets each failure of a job, with the job. The other jobs continue. */\n readonly onError?: ((error: unknown, job: T) => void) | undefined;\n}\n\n/**\n * This function starts `workers` workers. Each one takes a job from `jobs`, gives the job to\n * `worker`, and sends the result. The results close when `jobs` is closed and empty and each\n * worker is done. A failed job goes to `onError`, and its worker takes the next job.\n */\nexport const workerPool = <T, R>(jobs: Channel<T>, worker: (job: T) => Promise<R>, options: WorkerPoolOptions<T> = {}): Channel<R> => {\n const results = new Channel<R>(options.bufferSize);\n const workers = Array.from({ length: options.workers ?? 1 }, async () => {\n for await (const job of jobs) {\n try {\n await results.send(await worker(job));\n } catch (error) {\n options.onError?.(error, job);\n }\n }\n });\n void Promise.all(workers).then(() => results.close());\n return results;\n};\n"],"mappings":";;;;;;;AA6BA,IAAa,UAAb,MAAwB;CACtB;CACA,SAAiB;;CAGjB,YAAY,aAAa,GAAG;EAE1B,KAAK,QAAQ,WAAc,EAAE,UAAU,WAAW,CAAC;CACrD;;;;;;CAOA,MAAM,KAAK,OAAyB;EAClC,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,+BAA+B;EAChE,MAAM,KAAK,MAAM,IAAI,KAAK;CAC5B;;;;;;CAOA,MAAM,UAAsB;EAC1B,OAAO,MAAM,KAAK,MAAM,KAAK;CAC/B;;;;;;;;CASA,YAAY,SAA6B,UAAiD;EACxF,OAAO,KAAK,MAAM,SAAS,SAAS,QAAQ;CAC9C;;CAGA,QAAQ,OAAmB;EACzB,IAAI,KAAK,QAAQ,OAAO;EACxB,OAAO,KAAK,MAAM,OAAO,KAAK;CAChC;;CAGA,aAA4B;EAC1B,O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AC;;AAG/D,MAAa,WAAc,aAAa,MAAkB,IAAI,QAAW,UAAU;;;;;;AAiBnF,MAAa,cAAoB,MAAkB,QAAgC,UAAgC,CAAC,MAAkB;CACpI,MAAM,UAAU,IAAI,QAAW,QAAQ,UAAU;CACjD,MAAM,UAAU,MAAM,KAAK,EAAE,QAAQ,QAAQ,WAAW,EAAE,GAAG,YAAY;EACvE,WAAW,MAAM,OAAO,MACtB,IAAI;GACF,MAAM,QAAQ,KAAK,MAAM,OAAO,GAAG,CAAC;EACtC,SAAS,OAAO;GACd,QAAQ,UAAU,OAAO,GAAG;EAC9B;CAEJ,CAAC;CACD,QAAa,IAAI,OAAO,CAAC,CAAC,WAAW,QAAQ,MAAM,CAAC;CACpD,OAAO;AACT"}
1
+ {"version":3,"file":"channel.js","names":[],"sources":["../src/channel.ts"],"sourcesContent":["// @mark1russell7/service/channel: channels in the style of Go, on the clock of the service. It\n// imports only ./clock.ts and @mark1russell7/collections: no `node:` module and no zod. Thus a\n// client in a browser can use it, as it uses ./clock.\n//\n// The code came from @mark1russell7/collections 0.7 (the review of its API, C12, S2). The changes:\n// `timeout` and `ticker` take a clock, `ticker` does not drift, the functions that start work give\n// each failure to `onError` and write nothing to the console, and `fanIn` and `merge` take an array.\n\nimport { asyncQueue, type AsyncQueue } from \"@mark1russell7/collections\";\nimport { realClock, type Cancel, type Clock } from \"./clock.ts\";\n\n/** This function gets a failure of the work that a function of this entry started. */\nexport type ErrorHandler = (error: unknown) => void;\n\n/** These options are for a function that starts work and gives an output channel. */\nexport interface FlowOptions {\n /** The size of the buffer of each output channel. The default is 0: a send waits for a receiver. */\n readonly bufferSize?: number | undefined;\n /**\n * This function gets each failure of the work. The output closes after a failure. Without it,\n * the failure is lost, but the output also closes.\n */\n readonly onError?: ErrorHandler | undefined;\n}\n\n/**\n * A channel carries values from senders to receivers, as a channel of Go does. A channel with a\n * buffer of 0 is a rendezvous: each send waits for a receiver.\n */\nexport class Channel<T> {\n private readonly queue: AsyncQueue<T>;\n private closed = false;\n\n /** This constructor makes a channel with a buffer of `bufferSize` values. The default is 0. */\n constructor(bufferSize = 0) {\n // A buffer of 0 makes a send wait for a receiver (before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17)\n this.queue = asyncQueue<T>({ capacity: bufferSize });\n }\n\n /**\n * This method sends a value. It waits while the buffer is full and no receiver waits.\n *\n * @throws Error when the channel is closed.\n */\n async send(value: T): Promise<void> {\n if (this.closed) throw new Error(\"Cannot send on closed channel\");\n await this.queue.put(value);\n }\n\n /**\n * This method receives a value. It waits while the channel has no value.\n *\n * @throws Error when the channel is closed and empty.\n */\n async receive(): Promise<T> {\n return await this.queue.take();\n }\n\n /**\n * This method waits for one value, as `receive` does, and gives it to `onValue`. When the\n * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in\n * the call that sends the value or closes the channel.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no value yet.\n */\n waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {\n return this.queue.waitTake(onValue, onClosed);\n }\n\n /** This method sends a value if a receiver or the buffer takes it at once. It gives false when not. */\n trySend(value: T): boolean {\n if (this.closed) return false;\n return this.queue.tryPut(value);\n }\n\n /** This method receives a value if the channel has one at once. It gives undefined when not. */\n tryReceive(): T | undefined {\n return this.queue.tryTake();\n }\n\n /** This method closes the channel. A send then fails, but a receiver can take the values that stay. */\n close(): void {\n this.closed = true;\n this.queue.close();\n }\n\n /** This value is true after `close`. */\n get isClosed(): boolean {\n return this.closed;\n }\n\n /** This value is the count of values in the buffer. */\n get size(): number {\n return this.queue.size;\n }\n\n /** This method makes a case of `select` for this channel. `handler` gets the value of the case. */\n case<R>(handler: (value: T) => R): SelectCase<R> {\n return {\n // The value of each call comes from this channel, so it has the type T\n handler: (value) => handler(value as T),\n wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),\n };\n }\n\n /** This iteration receives each value. It stops when the channel is closed and empty. */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n let value: T;\n try {\n value = await this.receive();\n } catch {\n // The channel is closed and empty\n return;\n }\n yield value;\n }\n }\n}\n\n/** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */\nexport type Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;\n\n/** A case of `select`: a wait for one value, and the function that gets the value. `Channel.case` makes one. */\nexport interface SelectCase<R> {\n /** This function gets the value of the case, when the case wins. */\n readonly handler: (value: unknown) => R;\n /** This function waits for one value of the case. `select` withdraws it when another case wins. */\n readonly wait: Wait;\n}\n\n/**\n * This function gives the first value of the waits, with the index of its wait. It rejects with\n * the error of the first wait whose channel is closed and empty. It withdraws each other wait in\n * the same call, so a later value stays in its channel (before, the receives of the cases that\n * lost stayed in their channels and dropped the next value of each: audit O56).\n */\nconst firstOf = (waits: readonly Wait[]): Promise<{ index: number; value: unknown }> =>\n new Promise((resolve, reject) => {\n const withdraws: Array<() => boolean> = [];\n let settled = false;\n const end = (): void => {\n settled = true;\n for (const withdraw of withdraws) withdraw();\n };\n // A wait can call back at once, in its own call, when its channel has a value or is closed\n try {\n for (let index = 0; index < waits.length && !settled; index++) {\n withdraws.push(\n waits[index]!(\n (value) => {\n if (settled) return;\n end();\n resolve({ index, value });\n },\n (error) => {\n if (settled) return;\n end();\n reject(error);\n },\n ),\n );\n }\n } catch (error) {\n // A wait that throws: the waits before it are withdrawn\n if (!settled) end();\n reject(error);\n }\n });\n\n/**\n * This function waits for the first case with a value, as the `select` of Go does, and gives the\n * result of its handler. A case that loses keeps no receive: a later value stays in its channel.\n * When the channel of a case is closed and empty, the promise rejects.\n *\n * @example\n * const result = await select(data.case((v) => `data ${v}`), timeout(1000).case(() => \"late\"));\n */\nexport const select = async <R>(...cases: readonly SelectCase<R>[]): Promise<R> => {\n const { index, value } = await firstOf(cases.map((c) => c.wait));\n // The handler runs after the race, not in the call of the sender\n return cases[index]!.handler(value);\n};\n\n/**\n * This function makes a channel that gets one value after `ms` milliseconds of `clock`, and then\n * closes. A case of it in `select` is a time limit.\n */\nexport const timeout = (ms: number, clock: Clock = realClock): Channel<void> => {\n const ch = new Channel<void>();\n clock.after(ms, () => {\n // The value waits for a receiver. The close lets the receivers after it fail at once.\n ch.send(undefined).catch(() => undefined);\n ch.close();\n });\n return ch;\n};\n\n/** A ticker is a channel of the numbers of its ticks. `stop` stops its timer and closes it. */\nexport type Ticker = Channel<number> & { readonly stop: () => void };\n\n/**\n * This function makes a channel that gets a tick each `ms` milliseconds of `clock`. Tick k (from 0)\n * comes due at start + (k + 1) * ms, so the ticks do not drift. A late timer gives the number of\n * the last tick that came due, and skips the ticks that it missed. The buffer has 1 value: a slow\n * receiver loses ticks, as with the ticker of Go.\n */\nexport const ticker = (ms: number, clock: Clock = realClock): Ticker => {\n if (!(Number.isFinite(ms) && ms > 0)) throw new RangeError(`The period of a ticker is a finite number above 0, not ${ms}`);\n const ch = new Channel<number>(1);\n const start = clock.now();\n let cancel: Cancel | undefined;\n const arm = (tick: number): void => {\n cancel = clock.after(Math.max(0, start + (tick + 1) * ms - clock.now()), () => {\n const due = Math.max(tick, Math.floor((clock.now() - start) / ms) - 1);\n ch.trySend(due);\n arm(due + 1);\n });\n };\n arm(0);\n return Object.assign(ch, {\n stop: () => {\n cancel?.();\n ch.close();\n },\n });\n};\n\n/** This function starts `work`. It gives a failure to `onError`, and it calls `end` after the work in each case. */\nconst run = (work: () => Promise<void>, end: () => void, onError: ErrorHandler | undefined): void => {\n void work()\n .catch((error: unknown) => onError?.(error))\n .finally(end);\n};\n\n/**\n * This function gives a channel of `transform` of each value of `input`. The output closes when\n * `input` is closed and empty, or after a failure of `transform`.\n */\nexport const pipeline = <T, U>(input: Channel<T>, transform: (value: T) => U | Promise<U>, options: FlowOptions = {}): Channel<U> => {\n const output = new Channel<U>(options.bufferSize);\n run(\n async () => {\n for await (const value of input) await output.send(await transform(value));\n },\n () => output.close(),\n options.onError,\n );\n return output;\n};\n\n/**\n * This function gives `count` channels. Each one gets each value of `input`. The outputs close when\n * `input` is closed and empty, or after a failed send.\n */\nexport const fanOut = <T>(input: Channel<T>, count: number, options: FlowOptions = {}): Channel<T>[] => {\n const outputs = Array.from({ length: count }, () => new Channel<T>(options.bufferSize));\n run(\n async () => {\n for await (const value of input) await Promise.all(outputs.map((ch) => ch.send(value)));\n },\n () => {\n for (const ch of outputs) ch.close();\n },\n options.onError,\n );\n return outputs;\n};\n\n/**\n * This function gives one channel with the values of all `inputs`. The output closes when each\n * input is closed and empty. A failed send of one input goes to `onError`.\n */\nexport const fanIn = <T>(inputs: readonly Channel<T>[], options: FlowOptions = {}): Channel<T> => {\n const output = new Channel<T>(options.bufferSize);\n const workers = inputs.map(async (input) => {\n for await (const value of input) await output.send(value);\n });\n // All the workers settle, then the output closes, also after a failed send\n void Promise.allSettled(workers).then((results) => {\n output.close();\n for (const result of results) if (result.status === \"rejected\") options.onError?.(result.reason);\n });\n return output;\n};\n\n/**\n * This function gives one channel with the values of `inputs`, as `fanIn` does, but it closes when\n * the first input is closed and empty. It takes one value at a time, from the inputs in turn, and\n * keeps no receive on an input while it waits for the reader. Thus each value reaches the output\n * one time, in the order of its input, or stays in its input. With no input, the output is closed.\n */\nexport const merge = <T>(inputs: readonly Channel<T>[]): Channel<T> => {\n const output = new Channel<T>();\n // With no input, no input can give a value, so the output is closed at once, as with fanIn\n if (inputs.length === 0) {\n output.close();\n return output;\n }\n void (async () => {\n // The input after the input of the last value comes first, so a busy input starves no other\n let start = 0;\n while (true) {\n const order = inputs.map((_, offset) => (start + offset) % inputs.length);\n let next: { index: number; value: unknown };\n try {\n next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));\n } catch {\n // An input is closed and empty\n break;\n }\n const index = order[next.index]!;\n start = (index + 1) % inputs.length;\n try {\n // The value came from inputs[index], so it has the type T\n await output.send(next.value as T);\n } catch {\n // The reader closed the output\n break;\n }\n }\n output.close();\n })();\n return output;\n};\n\n/** This function makes a channel with a buffer of `capacity` values. */\nexport const buffered = <T>(capacity: number): Channel<T> => new Channel<T>(capacity);\n\n/** This function makes a channel with no buffer: each send waits for a receiver. */\nexport const unbuffered = <T>(): Channel<T> => new Channel<T>(0);\n\n/** This function makes a channel with a buffer of `bufferSize` values. The default is 0. */\nexport const channel = <T>(bufferSize = 0): Channel<T> => new Channel<T>(bufferSize);\n\n/** These options are for `workerPool`. */\nexport interface WorkerPoolOptions<T> {\n /** The count of workers. The default is 1. */\n readonly workers?: number | undefined;\n /** The size of the buffer of the results. The default is 0. */\n readonly bufferSize?: number | undefined;\n /** This function gets each failure of a job, with the job. The other jobs continue. */\n readonly onError?: ((error: unknown, job: T) => void) | undefined;\n}\n\n/**\n * This function starts `workers` workers. Each one takes a job from `jobs`, gives the job to\n * `worker`, and sends the result. The results close when `jobs` is closed and empty and each\n * worker is done. A failed job goes to `onError`, and its worker takes the next job.\n */\nexport const workerPool = <T, R>(jobs: Channel<T>, worker: (job: T) => Promise<R>, options: WorkerPoolOptions<T> = {}): Channel<R> => {\n const results = new Channel<R>(options.bufferSize);\n const workers = Array.from({ length: options.workers ?? 1 }, async () => {\n for await (const job of jobs) {\n try {\n await results.send(await worker(job));\n } catch (error) {\n options.onError?.(error, job);\n }\n }\n });\n void Promise.all(workers).then(() => results.close());\n return results;\n};\n\n/**\n * This error is the reason of a task that a `preemptivePool` stopped: a newer task took its place,\n * or `stop` stopped it. A caller tells it from a failure of the task with `instanceof`.\n */\nexport class PreemptedError extends Error {\n override readonly name = \"PreemptedError\";\n}\n\n/** A pool that runs at most `max` tasks at a time, and stops the oldest task for a new task. */\nexport interface PreemptivePool {\n /**\n * This method starts `task` with a signal. When the pool is full, it first stops the oldest task.\n * The promise of a stopped task rejects at once with the reason of its signal, and the signal\n * tells the task to stop its work.\n */\n run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R>;\n /** This method stops each task that runs. The reason is `reason`, or a `PreemptedError`. */\n stop(reason?: unknown): void;\n /** This count is the number of tasks that run. */\n readonly size: number;\n}\n\n/**\n * This function makes a pool of at most `max` tasks. The newest task always operates: a new task in a\n * full pool stops the oldest task. This is the policy for work whose old results nobody reads, for\n * example the load of a page that the user left. `workerPool` keeps each job in a queue instead.\n *\n * @throws RangeError when `max` is not an integer of 1 or more.\n */\nexport const preemptivePool = (max: number): PreemptivePool => {\n if (!(Number.isInteger(max) && max >= 1)) throw new RangeError(`preemptivePool: max is an integer of 1 or more, not ${max}.`);\n // The controller of each task that runs, from the oldest. A Set keeps the order of the adds.\n const running = new Set<AbortController>();\n const preempt = (controller: AbortController, reason: unknown): void => {\n running.delete(controller);\n controller.abort(reason);\n };\n return {\n run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R> {\n for (const oldest of running) {\n if (running.size < max) break;\n preempt(oldest, new PreemptedError(\"A newer task took the place of this task.\"));\n }\n const controller = new AbortController();\n running.add(controller);\n const stopped = new Promise<never>((_resolve, reject) => {\n controller.signal.addEventListener(\"abort\", () => reject(controller.signal.reason), { once: true });\n });\n // A task that throws at once rejects as a task that fails later does\n const done = Promise.resolve().then(() => task(controller.signal));\n return Promise.race([done, stopped]).finally(() => running.delete(controller));\n },\n stop(reason?: unknown): void {\n for (const controller of [...running]) preempt(controller, reason ?? new PreemptedError(\"The pool stopped this task.\"));\n },\n get size(): number {\n return running.size;\n },\n };\n};\n"],"mappings":";;;;;;;AA6BA,IAAa,UAAb,MAAwB;CACtB;CACA,SAAiB;;CAGjB,YAAY,aAAa,GAAG;EAE1B,KAAK,QAAQ,WAAc,EAAE,UAAU,WAAW,CAAC;CACrD;;;;;;CAOA,MAAM,KAAK,OAAyB;EAClC,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,+BAA+B;EAChE,MAAM,KAAK,MAAM,IAAI,KAAK;CAC5B;;;;;;CAOA,MAAM,UAAsB;EAC1B,OAAO,MAAM,KAAK,MAAM,KAAK;CAC/B;;;;;;;;CASA,YAAY,SAA6B,UAAiD;EACxF,OAAO,KAAK,MAAM,SAAS,SAAS,QAAQ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C;GACpG,CAAC;GAED,MAAM,OAAO,QAAQ,QAAQ,CAAC,CAAC,WAAW,KAAK,WAAW,MAAM,CAAC;GACjE,OAAO,QAAQ,KAAK,CAAC,MAAM,OAAO,CAAC,CAAC,CAAC,cAAc,QAAQ,OAAO,UAAU,CAAC;EAC/E;EACA,KAAK,QAAwB;GAC3B,KAAK,MAAM,cAAc,CAAC,GAAG,OAAO,GAAG,QAAQ,YAAY,UAAU,IAAI,eAAe,6BAA6B,CAAC;EACxH;EACA,IAAI,OAAe;GACjB,OAAO,QAAQ;EACjB;CACF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/service",
4
- "version": "0.8.2",
4
+ "version": "0.8.4",
5
5
  "description": "A service declared as data before it starts, and its runtime: checks on jittered loops, a latch for each policy, probes from the cache, the startup in its sequence, and a staged, capped drain. The timer-ordering law checks the declaration. Its clock, heartbeat and backoff also work alone, in a browser too.",
6
6
  "keywords": [
7
7
  "service",
@@ -114,7 +114,7 @@
114
114
  },
115
115
  "dependencies": {
116
116
  "@mark1russell7/algebra": "^0.8.3",
117
- "@mark1russell7/collections": "^0.9.8",
117
+ "@mark1russell7/collections": "^0.10.0",
118
118
  "@mark1russell7/quantity": "^0.3.3",
119
119
  "@mark1russell7/rigor-generators": "^0.1.0"
120
120
  },
@@ -157,7 +157,7 @@
157
157
  "devDependencies": {
158
158
  "@grpc/grpc-js": "1.14.6",
159
159
  "@mark1russell7/cue": "github:mark1russell7/cue#da04dd56699a2ae806ab64da5b1d677476afe69e",
160
- "@mark1russell7/harness": "^0.15.4",
160
+ "@mark1russell7/harness": "^0.15.5",
161
161
  "@mark1russell7/otel-ts": "^0.4.0",
162
162
  "@mark1russell7/rigor-testkit": "^0.1.1",
163
163
  "@opentelemetry/api": "^1.10.0",
@@ -169,6 +169,7 @@
169
169
  "@opentelemetry/sdk-node": "~0.223.0",
170
170
  "@opentelemetry/sdk-trace-base": "^2.12.0",
171
171
  "@types/node": "^26.6.4",
172
+ "@vitest/coverage-v8": "^5.0.3",
172
173
  "ioredis": "6.0.0",
173
174
  "testcontainers": "12.2.0",
174
175
  "tsdown": "^0.23.1",