@mark1russell7/service 0.8.3 → 0.8.5
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 +1 -0
- package/build/{backoff-B-jGWVDm.d.ts → backoff-QTRGfkEK.d.ts} +1 -3
- package/build/backoff.d.ts +1 -1
- package/build/backoff.js +1 -2
- package/build/{builder-DQj3NNNc.d.ts → builder-zO48Vgoj.d.ts} +4 -10
- package/build/{call-context-gR8FhbF_.d.ts → call-context-DDhcVvn5.d.ts} +1 -3
- package/build/channel.d.ts +28 -2
- package/build/channel.js +45 -3
- package/build/channel.js.map +1 -1
- package/build/{core-Dt0HEVMq.d.ts → core-BSzt4RI2.d.ts} +5 -9
- package/build/{dial-CSQOl-yj.d.ts → dial-ChwIcvd4.d.ts} +2 -4
- package/build/grpc.d.ts +4 -14
- package/build/grpc.js +7 -12
- package/build/grpc.js.map +1 -1
- package/build/heartbeat.d.ts +0 -2
- package/build/heartbeat.js +1 -2
- package/build/host.d.ts +3 -23
- package/build/host.js +21 -33
- package/build/host.js.map +1 -1
- package/build/http-client.d.ts +4 -16
- package/build/http-client.js +7 -13
- package/build/http-client.js.map +1 -1
- package/build/http.d.ts +3 -9
- package/build/http.js +6 -10
- package/build/http.js.map +1 -1
- package/build/index.d.ts +10 -22
- package/build/index.js +26 -43
- package/build/index.js.map +1 -1
- package/build/{knobs-D2ClI68I.js → knobs-BJcz6m01.js} +3 -5
- package/build/{knobs-D2ClI68I.js.map → knobs-BJcz6m01.js.map} +1 -1
- package/build/{lifecycle-Br0jAjTk.d.ts → lifecycle-D0J-zwZF.d.ts} +2 -14
- package/build/{limiter-BTgM4aXZ.js → limiter-BwGxEWpP.js} +4 -6
- package/build/{limiter-BTgM4aXZ.js.map → limiter-BwGxEWpP.js.map} +1 -1
- package/build/{limiter-D1aluA0V.d.ts → limiter-Djw39d_S.d.ts} +3 -5
- package/build/limiter.d.ts +3 -3
- package/build/limiter.js +2 -2
- package/build/{logger-BN2BfPgU.d.ts → logger-B6drv9w0.d.ts} +2 -16
- package/build/{machine-p4lENJ86.js → machine-mIW1qgEE.js} +7 -11
- package/build/{machine-p4lENJ86.js.map → machine-mIW1qgEE.js.map} +1 -1
- package/build/mongodb.d.ts +3 -13
- package/build/mongodb.js +6 -11
- package/build/mongodb.js.map +1 -1
- package/build/{operation-DL5RxFds.js → operation-DF73RZOI.js} +2 -3
- package/build/{operation-DL5RxFds.js.map → operation-DF73RZOI.js.map} +1 -1
- package/build/otel.d.ts +2 -4
- package/build/otel.js +1 -2
- package/build/pg.d.ts +2 -12
- package/build/pg.js +6 -11
- package/build/pg.js.map +1 -1
- package/build/{policy-G-Y3Meku.js → policy-B23MY52l.js} +2 -3
- package/build/{policy-G-Y3Meku.js.map → policy-B23MY52l.js.map} +1 -1
- package/build/{policy-CwYR95Sz.d.ts → policy-CBcK2XGg.d.ts} +1 -3
- package/build/{ports-CSr7qWrA.d.ts → ports-DZoipkSD.d.ts} +2 -4
- package/build/{process-DG_im2zc.js → process-Oe0Abbsm.js} +2 -3
- package/build/{process-DG_im2zc.js.map → process-Oe0Abbsm.js.map} +1 -1
- package/build/{queue-fIkOXKVG.d.ts → queue-DXdw1vLO.d.ts} +3 -7
- package/build/rabbitmq.d.ts +4 -14
- package/build/rabbitmq.js +6 -11
- package/build/rabbitmq.js.map +1 -1
- package/build/redis.d.ts +3 -15
- package/build/redis.js +10 -16
- package/build/redis.js.map +1 -1
- package/build/{requests-BIq9Tr4P.js → requests-DD2ALv0_.js} +6 -9
- package/build/{requests-BIq9Tr4P.js.map → requests-DD2ALv0_.js.map} +1 -1
- package/build/{retrier-Nt6r4r6R.js → retrier-BObZq10-.js} +3 -4
- package/build/{retrier-Nt6r4r6R.js.map → retrier-BObZq10-.js.map} +1 -1
- package/build/{rules-BBRopO1e.d.ts → rules-HyFCBStQ.d.ts} +1 -5
- package/build/rules.d.ts +1 -1
- package/build/rules.js +1 -2
- package/build/{store-1CsNoJ8O.d.ts → store-DFwFKrsB.d.ts} +2 -4
- package/build/testing.d.ts +4 -14
- package/build/testing.js +9 -15
- package/build/testing.js.map +1 -1
- package/build/{timing-DGRi3XCI.js → timing-DZl36uXs.js} +2 -3
- package/build/{timing-DGRi3XCI.js.map → timing-DZl36uXs.js.map} +1 -1
- package/build/websocket.d.ts +3 -13
- package/build/websocket.js +7 -12
- package/build/websocket.js.map +1 -1
- package/package.json +6 -4
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.
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/backoff.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* A jitter is the random part of each delay. The random number `r` is from 0 up to 1.
|
|
4
3
|
* - `none`: the delay is the backoff.
|
|
@@ -43,6 +42,5 @@ declare const backoffDelay: (policy: Backoff, attempt: number, random?: () => nu
|
|
|
43
42
|
declare const backoffBand: (policy: Backoff, attempt?: number) => DelayBand;
|
|
44
43
|
/** This function gives the problems of a policy: each value that the delays cannot use. */
|
|
45
44
|
declare const backoffProblems: (policy: Backoff) => string[];
|
|
46
|
-
//#endregion
|
|
47
45
|
export { backoffDelay as a, backoffBand as i, DelayBand as n, backoffProblems as o, Jitter as r, Backoff as t };
|
|
48
|
-
//# sourceMappingURL=backoff-
|
|
46
|
+
//# sourceMappingURL=backoff-QTRGfkEK.d.ts.map
|
package/build/backoff.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as backoffDelay, i as backoffBand, n as DelayBand, o as backoffProblems, r as Jitter, t as Backoff } from "./backoff-
|
|
1
|
+
import { a as backoffDelay, i as backoffBand, n as DelayBand, o as backoffProblems, r as Jitter, t as Backoff } from "./backoff-QTRGfkEK.js";
|
|
2
2
|
export { Backoff, DelayBand, Jitter, backoffBand, backoffDelay, backoffProblems };
|
package/build/backoff.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/backoff.ts
|
|
2
2
|
const NONE = { kind: "none" };
|
|
3
3
|
/** This function gives the backoff of a try, before its jitter: `base × factor^(attempt − 1)`, at most the cap. */
|
|
4
4
|
const backoffOf = (policy, attempt) => {
|
|
@@ -64,7 +64,6 @@ const backoffProblems = (policy) => {
|
|
|
64
64
|
if (jitter.kind === "add" && !(Number.isFinite(jitter.amount) && jitter.amount >= 0)) problems.push(`the amount ${jitter.amount} of the jitter is not a time of zero or more`);
|
|
65
65
|
return problems;
|
|
66
66
|
};
|
|
67
|
-
//#endregion
|
|
68
67
|
export { backoffBand, backoffDelay, backoffProblems };
|
|
69
68
|
|
|
70
69
|
//# sourceMappingURL=backoff.js.map
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
+
import { $ as ProcessTrigger, E as Phase, F as Timing, N as Poll, O as RepeatSignal, S as ExitCodes, T as MessageTrigger, V as OperationOf, _ as Check, b as Coupling, k as ServiceDescription, q as ExitTrigger, ut as Operation, w as Gate, x as Dependency, y as CooperativeFloor } from "./logger-B6drv9w0.js";
|
|
2
|
+
import { D as CheckFn, E as StartOptions, F as Outcome, L as Trace, S as Health, d as TransportImpl, n as HealthServer, o as PhaseWork, r as Lifecycle, s as RunOptions, t as DependencyHandle } from "./lifecycle-D0J-zwZF.js";
|
|
3
|
+
import { l as LimiterSpec } from "./policy-CBcK2XGg.js";
|
|
1
4
|
import { n as Clock } from "./clock-DpVgpY4h.js";
|
|
2
|
-
import { l as LimiterSpec } from "./policy-CwYR95Sz.js";
|
|
3
|
-
import { $ as ProcessTrigger, E as Phase, F as Timing, N as Poll, O as RepeatSignal, S as ExitCodes, T as MessageTrigger, V as OperationOf, _ as Check, b as Coupling, k as ServiceDescription, q as ExitTrigger, ut as Operation, w as Gate, x as Dependency, y as CooperativeFloor } from "./logger-BN2BfPgU.js";
|
|
4
|
-
import { D as CheckFn, E as StartOptions, F as Outcome, L as Trace, S as Health, d as TransportImpl, n as HealthServer, o as PhaseWork, r as Lifecycle, s as RunOptions, t as DependencyHandle } from "./lifecycle-Br0jAjTk.js";
|
|
5
5
|
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
6
|
-
//#region src/profiles.d.ts
|
|
7
6
|
/**
|
|
8
7
|
* A profile is a part of a declaration as data: policies, phases and the rules of the shutdown.
|
|
9
8
|
* `svc.profile(profile)` declares each field, as its method does. The runtime has no defaults, and
|
|
@@ -68,8 +67,6 @@ interface PodTiming {
|
|
|
68
67
|
* shorter than the drain, which is shorter than the budget (O16).
|
|
69
68
|
*/
|
|
70
69
|
declare const kubernetes: (pod: PodTiming) => Profile;
|
|
71
|
-
//#endregion
|
|
72
|
-
//#region src/watchdog.d.ts
|
|
73
70
|
/**
|
|
74
71
|
* A watchdog spec declares a watchdog of the event loop. The service declares it as a check whose
|
|
75
72
|
* function the watchdog gives: the process's own wedge, which a liveness window reads.
|
|
@@ -99,8 +96,6 @@ interface Watchdog {
|
|
|
99
96
|
}
|
|
100
97
|
/** This function starts a watchdog on a clock. */
|
|
101
98
|
declare const watchdog: (clock: Clock, spec: WatchdogSpec, trace?: Trace) => Watchdog;
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/builder.d.ts
|
|
104
99
|
/**
|
|
105
100
|
* The caller composes a service with plain method uses before it starts. The builder is imperative, and
|
|
106
101
|
* it holds static knowledge. The service does not use an `init` function that gives registrations.
|
|
@@ -207,6 +202,5 @@ interface ServiceBuilder {
|
|
|
207
202
|
}
|
|
208
203
|
/** This function starts the composition of a service. */
|
|
209
204
|
declare const service: (name: string) => ServiceBuilder;
|
|
210
|
-
//#endregion
|
|
211
205
|
export { WatchdogSpec as a, Profile as c, kubernetes as d, localDev as f, Watchdog as i, daemon as l, ServiceBuilder as n, watchdog as o, service as r, PodTiming as s, ControllerBuilder as t, ephemeral as u };
|
|
212
|
-
//# sourceMappingURL=builder-
|
|
206
|
+
//# sourceMappingURL=builder-zO48Vgoj.d.ts.map
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/call-context.d.ts
|
|
2
1
|
/** These are the headers of an incoming call, as `node:http` gives them: the names are in lower case. */
|
|
3
2
|
type IncomingHeaders = Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
4
3
|
/** A call context reads the context of an incoming call, and writes the context of an outgoing call. */
|
|
@@ -12,6 +11,5 @@ interface CallContext {
|
|
|
12
11
|
/** This function gives the headers of the active context for an outgoing call, for example `traceparent`. */
|
|
13
12
|
headers(): Record<string, string>;
|
|
14
13
|
}
|
|
15
|
-
//#endregion
|
|
16
14
|
export { IncomingHeaders as n, CallContext as t };
|
|
17
|
-
//# sourceMappingURL=call-context-
|
|
15
|
+
//# sourceMappingURL=call-context-DDhcVvn5.d.ts.map
|
package/build/channel.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { n as Clock } from "./clock-DpVgpY4h.js";
|
|
2
|
-
//#region src/channel.d.ts
|
|
3
2
|
/** This function gets a failure of the work that a function of this entry started. */
|
|
4
3
|
export type ErrorHandler = (error: unknown) => void;
|
|
5
4
|
/** These options are for a function that starts work and gives an output channel. */
|
|
@@ -133,5 +132,32 @@ export interface WorkerPoolOptions<T> {
|
|
|
133
132
|
* worker is done. A failed job goes to `onError`, and its worker takes the next job.
|
|
134
133
|
*/
|
|
135
134
|
export declare const workerPool: <T, R>(jobs: Channel<T>, worker: (job: T) => Promise<R>, options?: WorkerPoolOptions<T>) => Channel<R>;
|
|
136
|
-
|
|
135
|
+
/**
|
|
136
|
+
* This error is the reason of a task that a `preemptivePool` stopped: a newer task took its place,
|
|
137
|
+
* or `stop` stopped it. A caller tells it from a failure of the task with `instanceof`.
|
|
138
|
+
*/
|
|
139
|
+
export declare class PreemptedError extends Error {
|
|
140
|
+
override readonly name = "PreemptedError";
|
|
141
|
+
}
|
|
142
|
+
/** A pool that runs at most `max` tasks at a time, and stops the oldest task for a new task. */
|
|
143
|
+
export interface PreemptivePool {
|
|
144
|
+
/**
|
|
145
|
+
* This method starts `task` with a signal. When the pool is full, it first stops the oldest task.
|
|
146
|
+
* The promise of a stopped task rejects at once with the reason of its signal, and the signal
|
|
147
|
+
* tells the task to stop its work.
|
|
148
|
+
*/
|
|
149
|
+
run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R>;
|
|
150
|
+
/** This method stops each task that runs. The reason is `reason`, or a `PreemptedError`. */
|
|
151
|
+
stop(reason?: unknown): void;
|
|
152
|
+
/** This count is the number of tasks that run. */
|
|
153
|
+
readonly size: number;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* This function makes a pool of at most `max` tasks. The newest task always operates: a new task in a
|
|
157
|
+
* full pool stops the oldest task. This is the policy for work whose old results nobody reads, for
|
|
158
|
+
* example the load of a page that the user left. `workerPool` keeps each job in a queue instead.
|
|
159
|
+
*
|
|
160
|
+
* @throws RangeError when `max` is not an integer of 1 or more.
|
|
161
|
+
*/
|
|
162
|
+
export declare const preemptivePool: (max: number) => PreemptivePool;
|
|
137
163
|
//# sourceMappingURL=channel.d.ts.map
|
package/build/channel.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { realClock } from "./clock.js";
|
|
2
2
|
import { asyncQueue } from "@mark1russell7/collections";
|
|
3
|
-
|
|
3
|
+
// src/channel.ts
|
|
4
4
|
/**
|
|
5
5
|
* A channel carries values from senders to receivers, as a channel of Go does. A channel with a
|
|
6
6
|
* buffer of 0 is a rendezvous: each send waits for a receiver.
|
|
@@ -259,7 +259,49 @@ const workerPool = (jobs, worker, options = {}) => {
|
|
|
259
259
|
Promise.all(workers).then(() => results.close());
|
|
260
260
|
return results;
|
|
261
261
|
};
|
|
262
|
-
|
|
263
|
-
|
|
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
|
+
};
|
|
305
|
+
export { Channel, PreemptedError, buffered, channel, fanIn, fanOut, merge, pipeline, preemptivePool, select, ticker, timeout, unbuffered, workerPool };
|
|
264
306
|
|
|
265
307
|
//# sourceMappingURL=channel.js.map
|
package/build/channel.js.map
CHANGED
|
@@ -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,IA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AACT;;AAGA,MAAa,YAAe,aAAiC,IAAI,QAAW,QAAQ;;AAGpF,MAAa,mBAAkC,IAAI,QAAW,CAAC;;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,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AAU,WAAW;IACvD,WAAW,OAAO,iBAAiB,eAAe,OAAO,WAAW,OAAO,MAAM,GAAG,EAAE,MAAM,KAAK,CAAC;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"}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { t as Backoff } from "./backoff-
|
|
1
|
+
import { t as Backoff } from "./backoff-QTRGfkEK.js";
|
|
2
|
+
import { n as ServiceBuilder } from "./builder-zO48Vgoj.js";
|
|
2
3
|
import { n as Clock } from "./clock-DpVgpY4h.js";
|
|
3
|
-
import { A as Step, N as Poll, _ as Check, g as Recorder, k as ServiceDescription, ut as Operation, w as Gate, x as Dependency } from "./logger-
|
|
4
|
-
import { D as CheckFn, t as DependencyHandle } from "./lifecycle-
|
|
5
|
-
import { n as ServiceBuilder } from "./builder-DQj3NNNc.js";
|
|
4
|
+
import { A as Step, N as Poll, _ as Check, g as Recorder, k as ServiceDescription, ut as Operation, w as Gate, x as Dependency } from "./logger-B6drv9w0.js";
|
|
5
|
+
import { D as CheckFn, t as DependencyHandle } from "./lifecycle-D0J-zwZF.js";
|
|
6
6
|
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
7
|
-
//#region src/client/meets.d.ts
|
|
8
7
|
/** A situation is what the connection did when the failure started: a command in flight, or idle. */
|
|
9
8
|
type Situation = "in flight" | "idle";
|
|
10
9
|
/** A detector is a mechanism that finds a failure, and the most time that it takes. */
|
|
@@ -39,8 +38,6 @@ declare const unwatched: (meets: readonly Meeting[]) => Array<{
|
|
|
39
38
|
readonly manifestation: string;
|
|
40
39
|
readonly situation: Situation;
|
|
41
40
|
}>;
|
|
42
|
-
//#endregion
|
|
43
|
-
//#region src/client/core.d.ts
|
|
44
41
|
/**
|
|
45
42
|
* A sent result is the outcome of a call, in three values (C8):
|
|
46
43
|
* - `ok`: the server answered.
|
|
@@ -229,6 +226,5 @@ declare const retryProblems: (name: string, knobs: RetryKnobs) => string[];
|
|
|
229
226
|
* It does not depend on a driver. The starting knobs of each driver fit it.
|
|
230
227
|
*/
|
|
231
228
|
declare const STARTING_POLL: Poll;
|
|
232
|
-
//#endregion
|
|
233
229
|
export { MANIFESTATIONS as C, firstDetector as D, Situation as E, unwatched as O, Detector as S, Meeting as T, Sent as _, ClientKnobs as a, retryProblems as b, ClientSpec as c, Factory as d, ReadyWait as f, SendOptions as g, STARTING_POLL as h, ClientJoin as i, ClientStep as l, RetrySchedule as m, CheckOptions as n, ClientOptions as o, RetryKnobs as p, Client as r, ClientSocket as s, Attempt as t, DialFn as u, readyWait as v, Manifestation as w, retrySchedule as x, retryBackoff as y };
|
|
234
|
-
//# sourceMappingURL=core-
|
|
230
|
+
//# sourceMappingURL=core-BSzt4RI2.d.ts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import "./core-
|
|
2
|
-
//#region src/client/dial.d.ts
|
|
1
|
+
import "./core-BSzt4RI2.js";
|
|
3
2
|
/**
|
|
4
3
|
* A judge reads the bytes that the server sent so far. It gives null for a good answer, an error for
|
|
5
4
|
* a bad answer, or "more" when it must wait for more bytes.
|
|
@@ -11,6 +10,5 @@ type Judge = (received: Buffer) => Error | null | "more";
|
|
|
11
10
|
* The HTTP client accepts each status. The WebSocket client accepts only 101.
|
|
12
11
|
*/
|
|
13
12
|
declare const statusLineJudge: (accept: (status: number, line: string) => Error | null) => Judge;
|
|
14
|
-
//#endregion
|
|
15
13
|
export { statusLineJudge as n, Judge as t };
|
|
16
|
-
//# sourceMappingURL=dial-
|
|
14
|
+
//# sourceMappingURL=dial-ChwIcvd4.d.ts.map
|
package/build/grpc.d.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { t as
|
|
4
|
-
import {
|
|
1
|
+
import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation } from "./core-BSzt4RI2.js";
|
|
2
|
+
import { t as Judge } from "./dial-ChwIcvd4.js";
|
|
3
|
+
import { t as CallContext } from "./call-context-DDhcVvn5.js";
|
|
4
|
+
import { N as Poll, ut as Operation } from "./logger-B6drv9w0.js";
|
|
5
5
|
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
6
6
|
import { Machine } from "@mark1russell7/algebra";
|
|
7
|
-
//#region src/grpc/connection.d.ts
|
|
8
7
|
/** A state is the connectivity state of a channel of grpc-js, by the names of its enum `connectivityState`. */
|
|
9
8
|
type GrpcState = "IDLE" | "CONNECTING" | "READY" | "TRANSIENT_FAILURE" | "SHUTDOWN";
|
|
10
9
|
/** These states are in the sequence of the enum of grpc-js: the index of a state is its value. */
|
|
@@ -100,8 +99,6 @@ export declare const adaptGrpc: (grpc: GrpcDriver, client: GrpcDriverClient) =>
|
|
|
100
99
|
* service that does not use gRPC does not need it. The specifier is a value, thus the package needs no types of grpc-js.
|
|
101
100
|
*/
|
|
102
101
|
export declare const nodeGrpc: GrpcFactory;
|
|
103
|
-
//#endregion
|
|
104
|
-
//#region src/grpc/client.d.ts
|
|
105
102
|
/**
|
|
106
103
|
* These are the knobs of the client, each a time, by the names of the ordering law and of the gRPC
|
|
107
104
|
* cells. The runtime has no defaults, thus each knob is necessary. The constant
|
|
@@ -249,8 +246,6 @@ export declare const grpcDial: DialFn;
|
|
|
249
246
|
* The calls in flight, the bounded close and the checks come from the core too. This entry gives what grpc-js does in its own way.
|
|
250
247
|
*/
|
|
251
248
|
export declare const grpcClient: (name: string, spec: GrpcClientSpec, options?: GrpcClientOptions) => GrpcClient;
|
|
252
|
-
//#endregion
|
|
253
|
-
//#region src/grpc/machine.d.ts
|
|
254
249
|
/**
|
|
255
250
|
* The gRPC client of the service as a `mark1russell7.machine/1` document. It is one channel of
|
|
256
251
|
* grpc-js 1.14 for the life of the client. Each READY of the channel is one generation. The states:
|
|
@@ -262,8 +257,6 @@ export declare const grpcClient: (name: string, spec: GrpcClientSpec, options?:
|
|
|
262
257
|
* A test records the transitions of the client and replays them against this document.
|
|
263
258
|
*/
|
|
264
259
|
export declare const GRPC_CLIENT_MACHINE: Machine;
|
|
265
|
-
//#endregion
|
|
266
|
-
//#region src/grpc/meets.d.ts
|
|
267
260
|
/**
|
|
268
261
|
* This function gives the manifestations that a gRPC client can meet, and the detectors of each,
|
|
269
262
|
* from its knobs. The gRPC cells measured them on grpc-js 1.14.6:
|
|
@@ -276,8 +269,6 @@ export declare const GRPC_CLIENT_MACHINE: Machine;
|
|
|
276
269
|
* not answer then keeps the channel out of READY.
|
|
277
270
|
*/
|
|
278
271
|
export declare const grpcMeetings: (name: string, knobs: GrpcKnobs, withoutCalls: boolean) => Meeting[];
|
|
279
|
-
//#endregion
|
|
280
|
-
//#region src/grpc/starting.d.ts
|
|
281
272
|
/**
|
|
282
273
|
* This poll is the poll of the checks that `GRPC_CLIENT_STARTING_KNOBS` fits. It is `STARTING_POLL` of
|
|
283
274
|
* the core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.
|
|
@@ -309,6 +300,5 @@ export declare const GRPC_CLIENT_STARTING_WITHOUT_CALLS: boolean;
|
|
|
309
300
|
* - `retrans_giveup_time` 924.6 s: the give-up of Linux at `tcp_retries2 = 15`.
|
|
310
301
|
*/
|
|
311
302
|
export declare const GRPC_CLIENT_STARTING_KNOBS: GrpcKnobs;
|
|
312
|
-
//#endregion
|
|
313
303
|
export { type Attempt, type CheckOptions, type Client, type ClientJoin, type ClientKnobs, type ClientOptions, type ClientSocket, type ClientSpec, type ClientStep, type Detector, type DialFn, type Factory, type GrpcCallHandle, type GrpcCallOptions, type GrpcChannel, type GrpcChannelOptions, type GrpcClient, type GrpcClientOptions, type GrpcClientSpec, type GrpcConnectOptions, type GrpcFactory, type GrpcIdempotencyLevel, type GrpcJoin, type GrpcKnobs, type GrpcServingStatus, type GrpcState, type GrpcStatus, type Judge, MANIFESTATIONS, type Manifestation, type Meeting, type ReadyWait, type RetryKnobs, STARTING_POLL, type SendOptions, type Sent, type Situation, firstDetector, readyWait, retryProblems, unwatched };
|
|
314
304
|
//# sourceMappingURL=grpc.d.ts.map
|
package/build/grpc.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { B as zeroProblems, C as notSent, D as readyWait, F as timeProblems, G as immediate, H as NEVER, L as wholeProblems, M as sendWithReissue, N as socketEnds, P as stepChecks, R as withinBound, S as ms, U as WHAT, V as MANIFESTATIONS, W as firstDetector, X as unwatched, Y as kernelGiveUp, _ as inFlight, a as helloDial, b as message, c as ageProblems, d as clientProblems, f as clientRecorder, g as idleCloseProblem, h as finiteMs, i as authority, j as roundTripCheck, k as retryProblems, l as attachClient, m as dialCheck, n as closeTimer, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, w as operationTable, y as localStateCheck, z as wrapperTimerProblems } from "./machine-mIW1qgEE.js";
|
|
1
2
|
import { realClock } from "./clock.js";
|
|
2
|
-
import { i as heartbeatDetection } from "./timing-
|
|
3
|
-
|
|
4
|
-
//#region src/grpc/connection.ts
|
|
3
|
+
import { i as heartbeatDetection } from "./timing-DZl36uXs.js";
|
|
4
|
+
// src/grpc/connection.ts
|
|
5
5
|
/** These states are in the sequence of the enum of grpc-js: the index of a state is its value. */
|
|
6
6
|
const GRPC_STATES = [
|
|
7
7
|
"IDLE",
|
|
@@ -57,8 +57,7 @@ const nodeGrpc = async ({ target, options }) => {
|
|
|
57
57
|
if (grpc?.Client === void 0) throw new Error("@grpc/grpc-js gives no Client class");
|
|
58
58
|
return adaptGrpc(grpc, new grpc.Client(target, grpc.credentials.createInsecure(), options));
|
|
59
59
|
};
|
|
60
|
-
|
|
61
|
-
//#region src/grpc/meets.ts
|
|
60
|
+
// src/grpc/meets.ts
|
|
62
61
|
/**
|
|
63
62
|
* This function gives the manifestations that a gRPC client can meet, and the detectors of each,
|
|
64
63
|
* from its knobs. The gRPC cells measured them on grpc-js 1.14.6:
|
|
@@ -157,8 +156,7 @@ const grpcMeetings = (name, knobs, withoutCalls) => {
|
|
|
157
156
|
}
|
|
158
157
|
];
|
|
159
158
|
};
|
|
160
|
-
|
|
161
|
-
//#region src/grpc/client.ts
|
|
159
|
+
// src/grpc/client.ts
|
|
162
160
|
/** The names of the status codes of gRPC, by their value. */
|
|
163
161
|
const GRPC_CODES = [
|
|
164
162
|
"OK",
|
|
@@ -622,8 +620,7 @@ const grpcClient = (name, spec, options = {}) => {
|
|
|
622
620
|
}
|
|
623
621
|
};
|
|
624
622
|
};
|
|
625
|
-
|
|
626
|
-
//#region src/grpc/machine.ts
|
|
623
|
+
// src/grpc/machine.ts
|
|
627
624
|
/** The states where the client can close, and the states where a call can start its second try. */
|
|
628
625
|
const SERVING = [
|
|
629
626
|
"connecting",
|
|
@@ -768,8 +765,7 @@ const GRPC_CLIENT_MACHINE = {
|
|
|
768
765
|
transition("end", "closing", "status.end", "end")
|
|
769
766
|
]
|
|
770
767
|
};
|
|
771
|
-
|
|
772
|
-
//#region src/grpc/starting.ts
|
|
768
|
+
// src/grpc/starting.ts
|
|
773
769
|
/**
|
|
774
770
|
* This poll is the poll of the checks that `GRPC_CLIENT_STARTING_KNOBS` fits. It is `STARTING_POLL` of
|
|
775
771
|
* the core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.
|
|
@@ -854,7 +850,6 @@ const GRPC_CLIENT_STARTING_KNOBS = {
|
|
|
854
850
|
unit: "s"
|
|
855
851
|
}
|
|
856
852
|
};
|
|
857
|
-
//#endregion
|
|
858
853
|
export { GRPC_CLIENT_MACHINE, GRPC_CLIENT_STARTING_KNOBS, GRPC_CLIENT_STARTING_POLL, GRPC_CLIENT_STARTING_WITHOUT_CALLS, GRPC_CODES, GRPC_OPERATIONS, GRPC_STATES, HEALTH_CHECK, HTTP2_PREFACE, MANIFESTATIONS, STARTING_POLL, adaptGrpc, codeName, firstDetector, grpcClient, grpcDial, grpcMeetings, grpcOperations, grpcOptions, grpcOutcome, grpcTarget, healthRequest, healthStatus, nodeGrpc, readyWait, retryProblems, settingsJudge, specProblems, unwatched };
|
|
859
854
|
|
|
860
855
|
//# sourceMappingURL=grpc.js.map
|