@mark1russell7/service 0.6.5 → 0.6.7

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
@@ -249,7 +249,7 @@ A profile is a part of a declaration as data: the phases, the cooperative window
249
249
  | `ephemeral` | A command that runs one time, or a stdio child | No gating checks, an abort at the start of the drain, a flush of the output, and the exit codes 130, 143 and 131 |
250
250
 
251
251
  - **Kubernetes.** The budget is the grace less the preStop sleep: the time from SIGTERM to SIGKILL. The stages get 2, 5, 15, 2, 1, 2 and 1 thirtieths of the budget, rounded down to the millisecond. The cooperative window is 5 thirtieths. Thus 2 thirtieths stay as a margin, and O10 and O16 hold.
252
- - **The defaults of Kubernetes.** At a grace of 30 s and no preStop hook, the caps are 2, 5, 15, 2, 1, 2 and 1 s, with a window of 5 s. These are the caps of jarvis and of the kind lab.
252
+ - **The defaults of Kubernetes.** At a grace of 30 s and no preStop hook, the caps are 2, 5, 15, 2, 1, 2 and 1 s, with a window of 5 s. These are the caps of the kind lab.
253
253
  - **Local development.** No load balancer routes to a computer of a developer, thus the profile has no readiness hold. A second Ctrl-C exits at once.
254
254
  - **A background host.** A supervisor or a command stops the host with a signal. A repeat signal has no effect, thus the host ends its drain. The host has no parent on stdin, thus the profile declares no process trigger.
255
255
  - **The repeat signal.** Each profile declares `onRepeatSignal`: `"exit"` for `localDev` and `ephemeral`, and `"ignore"` for `daemon` and `kubernetes`.
@@ -384,6 +384,22 @@ const response = await retry(
384
384
  );
385
385
  ```
386
386
 
387
+ ## The channels
388
+
389
+ `@mark1russell7/service/channel` has channels in the style of Go. The entry imports only the clock and `@mark1russell7/collections`: no `node:` module and no zod. Thus a client in a browser can use it. The root of the package does not give its functions.
390
+
391
+ | Function | What it does |
392
+ | --- | --- |
393
+ | `channel(bufferSize)`, `buffered`, `unbuffered` | It makes a channel. With a buffer of 0, each send waits for a receiver. |
394
+ | `select(...cases)` | It waits for the first case with a value. A case that loses keeps no receive. |
395
+ | `timeout(ms, clock)` | It makes a channel that gets one value after `ms`, on the clock. |
396
+ | `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. |
397
+ | `pipeline`, `fanOut`, `fanIn`, `merge`, `workerPool` | They start work between channels. Each failure goes to `onError`, and the output closes. |
398
+
399
+ - **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.
400
+ - **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.
401
+ - **A late timer.** A ticker gives the number of the last tick that came due, and skips the ticks that it missed. A slow receiver loses ticks, because the buffer has one tick.
402
+
387
403
  ## The keyed limiter
388
404
 
389
405
  A keyed limiter gives each key its own limit, for example each tenant or each principal. `@mark1russell7/service/limiter` has it. The entry loads only the quantity package: no `node:` module and no zod. Thus a client in a browser can use it. The root of the package also gives each function.
@@ -403,7 +419,7 @@ A keyed limiter gives each key its own limit, for example each tenant or each pr
403
419
  - **No defaults.** A spec has a key, a policy, a store and a bound on its keys. `describe()` refuses a spec without its rate, its burst, its limit, its window, its store, the failure policy of a shared store or its bound. The error names the part.
404
420
  - **The key.** `key` tells what the key of each take is, for example `tenant`. The caller gives each key to `take(key)`.
405
421
  - **A token bucket.** `{ type: "token-bucket", rate, burst }` gives a key `burst` takes at once, and then `rate` takes in each unit of time. The rate is a count for each unit of time, for example `count/s` or `count/min`.
406
- - **A sliding window.** `{ type: "sliding-window", limit, window }` gives a key at most `limit` takes in each window. Each take counts for one window from its time. Graph limits its writes with this policy.
422
+ - **A sliding window.** `{ type: "sliding-window", limit, window }` gives a key at most `limit` takes in each window. Each take counts for one window from its time.
407
423
  - **The decision.** `take(key)` gives `{ allowed: true, remaining }` or `{ allowed: false, retryAfter, cause }`. `retryAfter` is a `Quantity` above zero: the time until the limiter lets the same take in. The cause is `limit`, `cap` or `store`.
408
424
  - **A take with no promise.** `tryTakeSync(key)` gives the same `Decision` at once. `keyedLimiter` on a `memoryStore` gives a `LocalLimiter`, whose type has it. On `KeyedLimiter`, it is optional.
409
425
  - **Only a local store.** `tryTakeSync` throws for a shared store, before the take. It also throws for a local store whose take gives a promise. That take still counts, thus use `take()` with such a store.
@@ -515,7 +531,7 @@ if (!decision.allowed) return limitedResponse(decision); // 429, with Retry-Afte
515
531
  - **Each 503 gets `Retry-After`.** Each 503 gets the `Retry-After` of `server_retry_after` (RFC 9110), and a 500 gets none. The transport applies the rule when the headers of each response go, whatever wrote them. Thus the rule applies to a probe, to a refusal of the transport and to a handler that writes its own status.
516
532
  - **The rule for a handler.** A 503 without `Retry-After` gets it, and a 503 with its own `Retry-After` keeps it. A 500 loses each `Retry-After`, from `setHeader` and from `writeHead`. The other statuses keep their headers.
517
533
  - **Another framework.** `writeOutcome(res, stream, options)` writes the stream of any `life.request` to a response of `node:http`. `outcomeResponse(items, end, options)` gives a unary response as data.
518
- - **Tracing in an ESM service.** An ESM service that uses OpenTelemetry starts with a preload, for example `node --import ./instrumentation.js app.js`. The preload must register `@opentelemetry/instrumentation/hook.mjs` before the application loads. Without that hook, the instrumentation does not see the ESM imports, and the spans of express are lost. The telemetry check of Graph found this when its server moved to ESM.
534
+ - **Tracing in an ESM service.** An ESM service that uses OpenTelemetry starts with a preload, for example `node --import ./instrumentation.js app.js`. The preload must register `@opentelemetry/instrumentation/hook.mjs` before the application loads. Without that hook, the instrumentation does not see the ESM imports, and the spans of express are lost.
519
535
 
520
536
  ```js
521
537
  // instrumentation.js, the preload: node --import ./instrumentation.js app.js
@@ -795,6 +811,10 @@ For the Redis client, the application also installs `ioredis@6`. For the Postgre
795
811
 
796
812
  For the gRPC client, it installs `@grpc/grpc-js@1`. The HTTP client needs no other package.
797
813
 
814
+ ### One copy of service
815
+
816
+ Service keeps state for some objects by identity, for example the late holds of each lifecycle and the mark of each HTTP answer. Each copy of the package has its own state. Thus a lifecycle of one copy and a transport of another copy lose that state with no error. `IDENTITY_TYPES` names each exported type that holds or reaches such a value. A package whose public API takes or gives one of these types declares service as a peer dependency. A test calculates the list from the sources, thus the list stays current.
817
+
798
818
  The package uses [`@mark1russell7/quantity`](https://www.npmjs.com/package/@mark1russell7/quantity) for each amount. No entry of the service loads `zod` at run time, thus `zod` is an optional peer dependency. An application that validates amounts with the schemas of `quantity` installs `zod`.
799
819
 
800
820
  ## Example
@@ -893,7 +913,7 @@ for await (const event of stream) {
893
913
 
894
914
  `pnpm --filter @mark1russell7/service test` starts the tests:
895
915
 
896
- - **The algebra and the builder.** The timing algebra, the refusals of the builder, its partial export, and the four verdicts of the law. A test in jarvis compares this evaluator with the evaluator of the research, on 185 bindings. All decisions agree.
916
+ - **The algebra and the builder.** The timing algebra, the refusals of the builder, its partial export, and the four verdicts of the law. A test in a private repository compares this evaluator with the evaluator of the research, on 185 bindings. All decisions agree.
897
917
  - **The permutations.** The permutations cross the policy, the timing, the poll interval, the jitter and the way that the step fails. For each one, a latch on a fake clock must trip inside `failSpan` and recover inside `recoverSpan`. Each permutation has eight seeds for the jitter and the phase of the fault. A failure names its permutation and its seed. Two more tests show that the bounds are reached.
898
918
  - **The edges.** These tests cover a flapping signal, a check that does not answer at any time, and late parts. They also cover couplings, controllers, the force-fail list, the drain, the stop, and the loop of a slow check.
899
919
  - **Real time.** The runtime on the real clock, and a check against a quiet server over TCP.
@@ -0,0 +1,137 @@
1
+ import { n as Clock } from "./clock-mVqhXD0b.js";
2
+ //#region src/channel.d.ts
3
+ /** This function gets a failure of the work that a function of this entry started. */
4
+ export type ErrorHandler = (error: unknown) => void;
5
+ /** These options are for a function that starts work and gives an output channel. */
6
+ export interface FlowOptions {
7
+ /** The size of the buffer of each output channel. The default is 0: a send waits for a receiver. */
8
+ readonly bufferSize?: number | undefined;
9
+ /**
10
+ * This function gets each failure of the work. The output closes after a failure. Without it,
11
+ * the failure is lost, but the output also closes.
12
+ */
13
+ readonly onError?: ErrorHandler | undefined;
14
+ }
15
+ /**
16
+ * A channel carries values from senders to receivers, as a channel of Go does. A channel with a
17
+ * buffer of 0 is a rendezvous: each send waits for a receiver.
18
+ */
19
+ export declare class Channel<T> {
20
+ private readonly queue;
21
+ private closed;
22
+ /** This constructor makes a channel with a buffer of `bufferSize` values. The default is 0. */
23
+ constructor(bufferSize?: number);
24
+ /**
25
+ * This method sends a value. It waits while the buffer is full and no receiver waits.
26
+ *
27
+ * @throws Error when the channel is closed.
28
+ */
29
+ send(value: T): Promise<void>;
30
+ /**
31
+ * This method receives a value. It waits while the channel has no value.
32
+ *
33
+ * @throws Error when the channel is closed and empty.
34
+ */
35
+ receive(): Promise<T>;
36
+ /**
37
+ * This method waits for one value, as `receive` does, and gives it to `onValue`. When the
38
+ * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in
39
+ * the call that sends the value or closes the channel.
40
+ *
41
+ * @returns A function that withdraws the wait. It gives true when the wait had no value yet.
42
+ */
43
+ waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean;
44
+ /** This method sends a value if a receiver or the buffer takes it at once. It gives false when not. */
45
+ trySend(value: T): boolean;
46
+ /** This method receives a value if the channel has one at once. It gives undefined when not. */
47
+ tryReceive(): T | undefined;
48
+ /** This method closes the channel. A send then fails, but a receiver can take the values that stay. */
49
+ close(): void;
50
+ /** This value is true after `close`. */
51
+ get isClosed(): boolean;
52
+ /** This value is the count of values in the buffer. */
53
+ get size(): number;
54
+ /** This method makes a case of `select` for this channel. `handler` gets the value of the case. */
55
+ case<R>(handler: (value: T) => R): SelectCase<R>;
56
+ /** This iteration receives each value. It stops when the channel is closed and empty. */
57
+ [Symbol.asyncIterator](): AsyncIterator<T>;
58
+ }
59
+ /** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */
60
+ export type Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;
61
+ /** A case of `select`: a wait for one value, and the function that gets the value. `Channel.case` makes one. */
62
+ export interface SelectCase<R> {
63
+ /** This function gets the value of the case, when the case wins. */
64
+ readonly handler: (value: unknown) => R;
65
+ /** This function waits for one value of the case. `select` withdraws it when another case wins. */
66
+ readonly wait: Wait;
67
+ }
68
+ /**
69
+ * This function waits for the first case with a value, as the `select` of Go does, and gives the
70
+ * result of its handler. A case that loses keeps no receive: a later value stays in its channel.
71
+ * When the channel of a case is closed and empty, the promise rejects.
72
+ *
73
+ * @example
74
+ * const result = await select(data.case((v) => `data ${v}`), timeout(1000).case(() => "late"));
75
+ */
76
+ export declare const select: <R>(...cases: readonly SelectCase<R>[]) => Promise<R>;
77
+ /**
78
+ * This function makes a channel that gets one value after `ms` milliseconds of `clock`, and then
79
+ * closes. A case of it in `select` is a time limit.
80
+ */
81
+ export declare const timeout: (ms: number, clock?: Clock) => Channel<void>;
82
+ /** A ticker is a channel of the numbers of its ticks. `stop` stops its timer and closes it. */
83
+ export type Ticker = Channel<number> & {
84
+ readonly stop: () => void;
85
+ };
86
+ /**
87
+ * This function makes a channel that gets a tick each `ms` milliseconds of `clock`. Tick k (from 0)
88
+ * comes due at start + (k + 1) * ms, so the ticks do not drift. A late timer gives the number of
89
+ * the last tick that came due, and skips the ticks that it missed. The buffer has 1 value: a slow
90
+ * receiver loses ticks, as with the ticker of Go.
91
+ */
92
+ export declare const ticker: (ms: number, clock?: Clock) => Ticker;
93
+ /**
94
+ * This function gives a channel of `transform` of each value of `input`. The output closes when
95
+ * `input` is closed and empty, or after a failure of `transform`.
96
+ */
97
+ export declare const pipeline: <T, U>(input: Channel<T>, transform: (value: T) => U | Promise<U>, options?: FlowOptions) => Channel<U>;
98
+ /**
99
+ * This function gives `count` channels. Each one gets each value of `input`. The outputs close when
100
+ * `input` is closed and empty, or after a failed send.
101
+ */
102
+ export declare const fanOut: <T>(input: Channel<T>, count: number, options?: FlowOptions) => Channel<T>[];
103
+ /**
104
+ * This function gives one channel with the values of all `inputs`. The output closes when each
105
+ * input is closed and empty. A failed send of one input goes to `onError`.
106
+ */
107
+ export declare const fanIn: <T>(inputs: readonly Channel<T>[], options?: FlowOptions) => Channel<T>;
108
+ /**
109
+ * This function gives one channel with the values of `inputs`, as `fanIn` does, but it closes when
110
+ * the first input is closed and empty. It takes one value at a time, from the inputs in turn, and
111
+ * keeps no receive on an input while it waits for the reader. Thus each value reaches the output
112
+ * one time, in the order of its input, or stays in its input. With no input, the output is closed.
113
+ */
114
+ export declare const merge: <T>(inputs: readonly Channel<T>[]) => Channel<T>;
115
+ /** This function makes a channel with a buffer of `capacity` values. */
116
+ export declare const buffered: <T>(capacity: number) => Channel<T>;
117
+ /** This function makes a channel with no buffer: each send waits for a receiver. */
118
+ export declare const unbuffered: <T>() => Channel<T>;
119
+ /** This function makes a channel with a buffer of `bufferSize` values. The default is 0. */
120
+ export declare const channel: <T>(bufferSize?: number) => Channel<T>;
121
+ /** These options are for `workerPool`. */
122
+ export interface WorkerPoolOptions<T> {
123
+ /** The count of workers. The default is 1. */
124
+ readonly workers?: number | undefined;
125
+ /** The size of the buffer of the results. The default is 0. */
126
+ readonly bufferSize?: number | undefined;
127
+ /** This function gets each failure of a job, with the job. The other jobs continue. */
128
+ readonly onError?: ((error: unknown, job: T) => void) | undefined;
129
+ }
130
+ /**
131
+ * This function starts `workers` workers. Each one takes a job from `jobs`, gives the job to
132
+ * `worker`, and sends the result. The results close when `jobs` is closed and empty and each
133
+ * worker is done. A failed job goes to `onError`, and its worker takes the next job.
134
+ */
135
+ export declare const workerPool: <T, R>(jobs: Channel<T>, worker: (job: T) => Promise<R>, options?: WorkerPoolOptions<T>) => Channel<R>;
136
+ //#endregion
137
+ //# sourceMappingURL=channel.d.ts.map
@@ -0,0 +1,265 @@
1
+ import { realClock } from "./clock.js";
2
+ import { asyncQueue } from "@mark1russell7/collections";
3
+ //#region src/channel.ts
4
+ /**
5
+ * A channel carries values from senders to receivers, as a channel of Go does. A channel with a
6
+ * buffer of 0 is a rendezvous: each send waits for a receiver.
7
+ */
8
+ var Channel = class {
9
+ queue;
10
+ closed = false;
11
+ /** This constructor makes a channel with a buffer of `bufferSize` values. The default is 0. */
12
+ constructor(bufferSize = 0) {
13
+ this.queue = asyncQueue({ capacity: bufferSize });
14
+ }
15
+ /**
16
+ * This method sends a value. It waits while the buffer is full and no receiver waits.
17
+ *
18
+ * @throws Error when the channel is closed.
19
+ */
20
+ async send(value) {
21
+ if (this.closed) throw new Error("Cannot send on closed channel");
22
+ await this.queue.put(value);
23
+ }
24
+ /**
25
+ * This method receives a value. It waits while the channel has no value.
26
+ *
27
+ * @throws Error when the channel is closed and empty.
28
+ */
29
+ async receive() {
30
+ return await this.queue.take();
31
+ }
32
+ /**
33
+ * This method waits for one value, as `receive` does, and gives it to `onValue`. When the
34
+ * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in
35
+ * the call that sends the value or closes the channel.
36
+ *
37
+ * @returns A function that withdraws the wait. It gives true when the wait had no value yet.
38
+ */
39
+ waitReceive(onValue, onClosed) {
40
+ return this.queue.waitTake(onValue, onClosed);
41
+ }
42
+ /** This method sends a value if a receiver or the buffer takes it at once. It gives false when not. */
43
+ trySend(value) {
44
+ if (this.closed) return false;
45
+ return this.queue.tryPut(value);
46
+ }
47
+ /** This method receives a value if the channel has one at once. It gives undefined when not. */
48
+ tryReceive() {
49
+ return this.queue.tryTake();
50
+ }
51
+ /** This method closes the channel. A send then fails, but a receiver can take the values that stay. */
52
+ close() {
53
+ this.closed = true;
54
+ this.queue.close();
55
+ }
56
+ /** This value is true after `close`. */
57
+ get isClosed() {
58
+ return this.closed;
59
+ }
60
+ /** This value is the count of values in the buffer. */
61
+ get size() {
62
+ return this.queue.size;
63
+ }
64
+ /** This method makes a case of `select` for this channel. `handler` gets the value of the case. */
65
+ case(handler) {
66
+ return {
67
+ handler: (value) => handler(value),
68
+ wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed)
69
+ };
70
+ }
71
+ /** This iteration receives each value. It stops when the channel is closed and empty. */
72
+ async *[Symbol.asyncIterator]() {
73
+ while (true) {
74
+ let value;
75
+ try {
76
+ value = await this.receive();
77
+ } catch {
78
+ return;
79
+ }
80
+ yield value;
81
+ }
82
+ }
83
+ };
84
+ /**
85
+ * This function gives the first value of the waits, with the index of its wait. It rejects with
86
+ * the error of the first wait whose channel is closed and empty. It withdraws each other wait in
87
+ * the same call, so a later value stays in its channel (before, the receives of the cases that
88
+ * lost stayed in their channels and dropped the next value of each: audit O56).
89
+ */
90
+ const firstOf = (waits) => new Promise((resolve, reject) => {
91
+ const withdraws = [];
92
+ let settled = false;
93
+ const end = () => {
94
+ settled = true;
95
+ for (const withdraw of withdraws) withdraw();
96
+ };
97
+ try {
98
+ for (let index = 0; index < waits.length && !settled; index++) withdraws.push(waits[index]((value) => {
99
+ if (settled) return;
100
+ end();
101
+ resolve({
102
+ index,
103
+ value
104
+ });
105
+ }, (error) => {
106
+ if (settled) return;
107
+ end();
108
+ reject(error);
109
+ }));
110
+ } catch (error) {
111
+ if (!settled) end();
112
+ reject(error);
113
+ }
114
+ });
115
+ /**
116
+ * This function waits for the first case with a value, as the `select` of Go does, and gives the
117
+ * result of its handler. A case that loses keeps no receive: a later value stays in its channel.
118
+ * When the channel of a case is closed and empty, the promise rejects.
119
+ *
120
+ * @example
121
+ * const result = await select(data.case((v) => `data ${v}`), timeout(1000).case(() => "late"));
122
+ */
123
+ const select = async (...cases) => {
124
+ const { index, value } = await firstOf(cases.map((c) => c.wait));
125
+ return cases[index].handler(value);
126
+ };
127
+ /**
128
+ * This function makes a channel that gets one value after `ms` milliseconds of `clock`, and then
129
+ * closes. A case of it in `select` is a time limit.
130
+ */
131
+ const timeout = (ms, clock = realClock) => {
132
+ const ch = new Channel();
133
+ clock.after(ms, () => {
134
+ ch.send(void 0).catch(() => void 0);
135
+ ch.close();
136
+ });
137
+ return ch;
138
+ };
139
+ /**
140
+ * This function makes a channel that gets a tick each `ms` milliseconds of `clock`. Tick k (from 0)
141
+ * comes due at start + (k + 1) * ms, so the ticks do not drift. A late timer gives the number of
142
+ * the last tick that came due, and skips the ticks that it missed. The buffer has 1 value: a slow
143
+ * receiver loses ticks, as with the ticker of Go.
144
+ */
145
+ const ticker = (ms, clock = realClock) => {
146
+ if (!(Number.isFinite(ms) && ms > 0)) throw new RangeError(`The period of a ticker is a finite number above 0, not ${ms}`);
147
+ const ch = new Channel(1);
148
+ const start = clock.now();
149
+ let cancel;
150
+ const arm = (tick) => {
151
+ cancel = clock.after(Math.max(0, start + (tick + 1) * ms - clock.now()), () => {
152
+ const due = Math.max(tick, Math.floor((clock.now() - start) / ms) - 1);
153
+ ch.trySend(due);
154
+ arm(due + 1);
155
+ });
156
+ };
157
+ arm(0);
158
+ return Object.assign(ch, { stop: () => {
159
+ cancel?.();
160
+ ch.close();
161
+ } });
162
+ };
163
+ /** This function starts `work`. It gives a failure to `onError`, and it calls `end` after the work in each case. */
164
+ const run = (work, end, onError) => {
165
+ work().catch((error) => onError?.(error)).finally(end);
166
+ };
167
+ /**
168
+ * This function gives a channel of `transform` of each value of `input`. The output closes when
169
+ * `input` is closed and empty, or after a failure of `transform`.
170
+ */
171
+ const pipeline = (input, transform, options = {}) => {
172
+ const output = new Channel(options.bufferSize);
173
+ run(async () => {
174
+ for await (const value of input) await output.send(await transform(value));
175
+ }, () => output.close(), options.onError);
176
+ return output;
177
+ };
178
+ /**
179
+ * This function gives `count` channels. Each one gets each value of `input`. The outputs close when
180
+ * `input` is closed and empty, or after a failed send.
181
+ */
182
+ const fanOut = (input, count, options = {}) => {
183
+ const outputs = Array.from({ length: count }, () => new Channel(options.bufferSize));
184
+ run(async () => {
185
+ for await (const value of input) await Promise.all(outputs.map((ch) => ch.send(value)));
186
+ }, () => {
187
+ for (const ch of outputs) ch.close();
188
+ }, options.onError);
189
+ return outputs;
190
+ };
191
+ /**
192
+ * This function gives one channel with the values of all `inputs`. The output closes when each
193
+ * input is closed and empty. A failed send of one input goes to `onError`.
194
+ */
195
+ const fanIn = (inputs, options = {}) => {
196
+ const output = new Channel(options.bufferSize);
197
+ const workers = inputs.map(async (input) => {
198
+ for await (const value of input) await output.send(value);
199
+ });
200
+ Promise.allSettled(workers).then((results) => {
201
+ output.close();
202
+ for (const result of results) if (result.status === "rejected") options.onError?.(result.reason);
203
+ });
204
+ return output;
205
+ };
206
+ /**
207
+ * This function gives one channel with the values of `inputs`, as `fanIn` does, but it closes when
208
+ * the first input is closed and empty. It takes one value at a time, from the inputs in turn, and
209
+ * keeps no receive on an input while it waits for the reader. Thus each value reaches the output
210
+ * one time, in the order of its input, or stays in its input. With no input, the output is closed.
211
+ */
212
+ const merge = (inputs) => {
213
+ const output = new Channel();
214
+ if (inputs.length === 0) {
215
+ output.close();
216
+ return output;
217
+ }
218
+ (async () => {
219
+ let start = 0;
220
+ while (true) {
221
+ const order = inputs.map((_, offset) => (start + offset) % inputs.length);
222
+ let next;
223
+ try {
224
+ next = await firstOf(order.map((index) => (onValue, onClosed) => inputs[index].waitReceive(onValue, onClosed)));
225
+ } catch {
226
+ break;
227
+ }
228
+ start = (order[next.index] + 1) % inputs.length;
229
+ try {
230
+ await output.send(next.value);
231
+ } catch {
232
+ break;
233
+ }
234
+ }
235
+ output.close();
236
+ })();
237
+ return output;
238
+ };
239
+ /** This function makes a channel with a buffer of `capacity` values. */
240
+ const buffered = (capacity) => new Channel(capacity);
241
+ /** This function makes a channel with no buffer: each send waits for a receiver. */
242
+ const unbuffered = () => new Channel(0);
243
+ /** This function makes a channel with a buffer of `bufferSize` values. The default is 0. */
244
+ const channel = (bufferSize = 0) => new Channel(bufferSize);
245
+ /**
246
+ * This function starts `workers` workers. Each one takes a job from `jobs`, gives the job to
247
+ * `worker`, and sends the result. The results close when `jobs` is closed and empty and each
248
+ * worker is done. A failed job goes to `onError`, and its worker takes the next job.
249
+ */
250
+ const workerPool = (jobs, worker, options = {}) => {
251
+ const results = new Channel(options.bufferSize);
252
+ const workers = Array.from({ length: options.workers ?? 1 }, async () => {
253
+ for await (const job of jobs) try {
254
+ await results.send(await worker(job));
255
+ } catch (error) {
256
+ options.onError?.(error, job);
257
+ }
258
+ });
259
+ Promise.all(workers).then(() => results.close());
260
+ return results;
261
+ };
262
+ //#endregion
263
+ export { Channel, buffered, channel, fanIn, fanOut, merge, pipeline, select, ticker, timeout, unbuffered, workerPool };
264
+
265
+ //# sourceMappingURL=channel.js.map
@@ -0,0 +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,OAAO,KAAK,MAAM,QAAQ;CAC5B;;CAGA,QAAc;EACZ,KAAK,SAAS;EACd,KAAK,MAAM,MAAM;CACnB;;CAGA,IAAI,WAAoB;EACtB,OAAO,KAAK;CACd;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK,MAAM;CACpB;;CAGA,KAAQ,SAAyC;EAC/C,OA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W,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"}
package/build/index.d.ts CHANGED
@@ -99,7 +99,7 @@ export declare const SERVICE_RULES: readonly string[];
99
99
  * `Retry-After` of the policy. Otherwise a caller that does not read the header sends again too
100
100
  * early, and the limiter refuses each early call again.
101
101
  *
102
- * The identifiers O29 and O30 are provisional. The corpus of the law in jarvis (R3, track B) has 28
102
+ * The identifiers O29 and O30 are provisional. The private corpus of the law (R3, track B) has 28
103
103
  * rules, O01 to O28. It does not have these two rules yet, thus they take the next two identifiers.
104
104
  */
105
105
  export declare const LIMITER_RULES: readonly Rule[];
@@ -213,6 +213,24 @@ export declare const STOP_RULE = "stop";
213
213
  */
214
214
  export declare const lintStop: (svc: ServiceDescription, scenario: Scenario, rules: readonly Rule[], way: StopWay) => Finding[];
215
215
  //#endregion
216
+ //#region src/identity.d.ts
217
+ /**
218
+ * The exported type names that hold or reach a value that service knows by identity. A package
219
+ * whose public API takes or gives a value of one of these types has service as a peer dependency.
220
+ * A plain dependency is not sufficient. Then the package and its caller use one copy of service.
221
+ *
222
+ * The roots are `Lifecycle` and `RequestStream`, the keys of the maps, and `TransportImpl` and
223
+ * `RequestHandler`, whose values write to the maps of their own copy. The list is each exported type
224
+ * that names a root, or names a type of the list, in its declaration. A type can be on the list
225
+ * although its own use crosses copies safely: for that type, a peer is the safe choice.
226
+ *
227
+ * `identity.test.ts` calculates this list from the sources and from the maps, thus the list stays
228
+ * current.
229
+ */
230
+ export declare const IDENTITY_TYPES: readonly ["Client", "GrpcClient", "HttpClient", "HttpTransport", "IterationContext", "JobContext", "Lifecycle", "MongoClient", "MountContext", "PgClient", "QueueDrain", "QueueDrainOptions", "RabbitClient", "RedisClient", "RedisSender", "RequestHandler", "RequestStream", "ServiceBuilder", "SubjectFactory", "TransportImpl", "TransportSubject", "UpgradeHandler", "WorkerLoop", "WorkerLoopOptions", "WsClient"];
231
+ /** A name of `IDENTITY_TYPES`. */
232
+ type IdentityType = (typeof IDENTITY_TYPES)[number];
233
+ //#endregion
216
234
  //#region src/retrier.d.ts
217
235
  /** These options make a retrier: a backoff policy, the clock of its timers, and the signal that cancels it. */
218
236
  interface RetrierOptions extends Backoff {
@@ -404,5 +422,5 @@ export declare const drainMachine: (description: ServiceDescription) => Machine;
404
422
  /** These are the static machines of the runtime, by the name that their events carry. */
405
423
  export declare const MACHINES: Readonly<Record<Exclude<MachineName, "drain" | "client">, Machine>>;
406
424
  //#endregion
407
- export { type Allowed, type Backoff, type Binding, type Bound, type Cancel, type Change, type Check, type CheckFn, type CheckMetrics, type CheckVerdict, type Claim, type Clock, type Compressed, type Compression, type ConsoleLoggerOptions, type ConsoleTarget, type Controller, type ControllerBuilder, type CooperativeFloor, type Coupling, DRAIN_RULES, DURATION_FRACTIONS, type Decision, type DelayBand, type Dependency, type DependencyHandle, type DurationHistogram, EPISODES_KEPT, EXIT_SIGNALS, type EmbeddedProcess, type Episode, type Epochs, type Evaluated, type ExitCodes, type ExitSignal, type ExitTrigger, FORMAT, type FailsBy, type Finding, type Gate, type Health, type HealthMetrics, type HealthServer, type HealthVerdict, type Heartbeat, type HeartbeatOptions, type HostStream, type Idempotency, type Inequality, type IterationContext, type Jitter, type JobAction, type JobContext, type JobFailure, type JobSettle, type JobSource, type KeyState, type KeyedLimiter, LOG_LEVELS, type Lifecycle, type LifecycleEvent, type LifecycleState, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type LogEntry, type LogFields, type LogFormat, type LogLevel, type Logger, type MachineName, type MemoryStore, type MessageShape, type MessageTrigger, O04, O09, O10, O16, type Operation, type OperationOf, type Outcome, PROCESS_TRIGGERS, type Phase, type PhaseContext, type PhaseWork, type PlatformClockOptions, type PodTiming, type Poll, type ProbeAnswer, type ProbeKind, type ProcessHost, type ProcessPort, type ProcessTrigger, type Profile, type ProgressMarks, type QueueDrain, type QueueDrainOptions, type QueueKnobs, type Recorder, type RedeliveryPolicy, type RefusalCause, type Refused, type RepeatSignal, type RequestEnd, type RequestEvent, type RequestFn, type RequestOptions, type RequestStream, type RequestWork, type RequeueCause, type Result, type Retrier, type RetrierOptions, type RetryOptions, type RoutePattern, type RouteRequest, type Rule, type RunOptions, SLIDING_WINDOW_MACHINE, STAGES, type Scenario, type ScenarioValue, type ScopedChange, type ServiceBuilder, type ServiceDescription, type ShutdownOptions, type Side, type SlidingWindow, type Span, type Stage, type StartOptions, type Statistic, type Step, type Stop, type StopWay, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type Term, type TimerMark, type TimerMarks, type Timing, type TokenBucket, type Transport, type TransportImpl, UNCAUGHT_ORIGINS, type UncaughtOptions, type UncaughtOrigin, type UnitRequest, type Verdict, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, compress, compression, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, stageRank, symbolsOf, verdictOf, watchdog };
425
+ export { type Allowed, type Backoff, type Binding, type Bound, type Cancel, type Change, type Check, type CheckFn, type CheckMetrics, type CheckVerdict, type Claim, type Clock, type Compressed, type Compression, type ConsoleLoggerOptions, type ConsoleTarget, type Controller, type ControllerBuilder, type CooperativeFloor, type Coupling, DRAIN_RULES, DURATION_FRACTIONS, type Decision, type DelayBand, type Dependency, type DependencyHandle, type DurationHistogram, EPISODES_KEPT, EXIT_SIGNALS, type EmbeddedProcess, type Episode, type Epochs, type Evaluated, type ExitCodes, type ExitSignal, type ExitTrigger, FORMAT, type FailsBy, type Finding, type Gate, type Health, type HealthMetrics, type HealthServer, type HealthVerdict, type Heartbeat, type HeartbeatOptions, type HostStream, type Idempotency, type IdentityType, type Inequality, type IterationContext, type Jitter, type JobAction, type JobContext, type JobFailure, type JobSettle, type JobSource, type KeyState, type KeyedLimiter, LOG_LEVELS, type Lifecycle, type LifecycleEvent, type LifecycleState, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type LogEntry, type LogFields, type LogFormat, type LogLevel, type Logger, type MachineName, type MemoryStore, type MessageShape, type MessageTrigger, O04, O09, O10, O16, type Operation, type OperationOf, type Outcome, PROCESS_TRIGGERS, type Phase, type PhaseContext, type PhaseWork, type PlatformClockOptions, type PodTiming, type Poll, type ProbeAnswer, type ProbeKind, type ProcessHost, type ProcessPort, type ProcessTrigger, type Profile, type ProgressMarks, type QueueDrain, type QueueDrainOptions, type QueueKnobs, type Recorder, type RedeliveryPolicy, type RefusalCause, type Refused, type RepeatSignal, type RequestEnd, type RequestEvent, type RequestFn, type RequestOptions, type RequestStream, type RequestWork, type RequeueCause, type Result, type Retrier, type RetrierOptions, type RetryOptions, type RoutePattern, type RouteRequest, type Rule, type RunOptions, SLIDING_WINDOW_MACHINE, STAGES, type Scenario, type ScenarioValue, type ScopedChange, type ServiceBuilder, type ServiceDescription, type ShutdownOptions, type Side, type SlidingWindow, type Span, type Stage, type StartOptions, type Statistic, type Step, type Stop, type StopWay, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type Term, type TimerMark, type TimerMarks, type Timing, type TokenBucket, type Transport, type TransportImpl, UNCAUGHT_ORIGINS, type UncaughtOptions, type UncaughtOrigin, type UnitRequest, type Verdict, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, compress, compression, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, stageRank, symbolsOf, verdictOf, watchdog };
408
426
  //# sourceMappingURL=index.d.ts.map
package/build/index.js CHANGED
@@ -1903,7 +1903,7 @@ const SERVICE_RULES = [
1903
1903
  * `Retry-After` of the policy. Otherwise a caller that does not read the header sends again too
1904
1904
  * early, and the limiter refuses each early call again.
1905
1905
  *
1906
- * The identifiers O29 and O30 are provisional. The corpus of the law in jarvis (R3, track B) has 28
1906
+ * The identifiers O29 and O30 are provisional. The private corpus of the law (R3, track B) has 28
1907
1907
  * rules, O01 to O28. It does not have these two rules yet, thus they take the next two identifiers.
1908
1908
  */
1909
1909
  const LIMITER_RULES = [{
@@ -2519,6 +2519,48 @@ const lintStop = (svc, scenario, rules, way) => {
2519
2519
  }];
2520
2520
  };
2521
2521
  //#endregion
2522
+ //#region src/identity.ts
2523
+ /**
2524
+ * The exported type names that hold or reach a value that service knows by identity. A package
2525
+ * whose public API takes or gives a value of one of these types has service as a peer dependency.
2526
+ * A plain dependency is not sufficient. Then the package and its caller use one copy of service.
2527
+ *
2528
+ * The roots are `Lifecycle` and `RequestStream`, the keys of the maps, and `TransportImpl` and
2529
+ * `RequestHandler`, whose values write to the maps of their own copy. The list is each exported type
2530
+ * that names a root, or names a type of the list, in its declaration. A type can be on the list
2531
+ * although its own use crosses copies safely: for that type, a peer is the safe choice.
2532
+ *
2533
+ * `identity.test.ts` calculates this list from the sources and from the maps, thus the list stays
2534
+ * current.
2535
+ */
2536
+ const IDENTITY_TYPES = [
2537
+ "Client",
2538
+ "GrpcClient",
2539
+ "HttpClient",
2540
+ "HttpTransport",
2541
+ "IterationContext",
2542
+ "JobContext",
2543
+ "Lifecycle",
2544
+ "MongoClient",
2545
+ "MountContext",
2546
+ "PgClient",
2547
+ "QueueDrain",
2548
+ "QueueDrainOptions",
2549
+ "RabbitClient",
2550
+ "RedisClient",
2551
+ "RedisSender",
2552
+ "RequestHandler",
2553
+ "RequestStream",
2554
+ "ServiceBuilder",
2555
+ "SubjectFactory",
2556
+ "TransportImpl",
2557
+ "TransportSubject",
2558
+ "UpgradeHandler",
2559
+ "WorkerLoop",
2560
+ "WorkerLoopOptions",
2561
+ "WsClient"
2562
+ ];
2563
+ //#endregion
2522
2564
  //#region src/profiles.ts
2523
2565
  const s = (value) => ({
2524
2566
  value,
@@ -3505,6 +3547,6 @@ const MACHINES = {
3505
3547
  watchdog: WATCHDOG_MACHINE
3506
3548
  };
3507
3549
  //#endregion
3508
- export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, verdictOf, watchdog, workerLoop };
3550
+ export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, IDENTITY_TYPES, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, verdictOf, watchdog, workerLoop };
3509
3551
 
3510
3552
  //# sourceMappingURL=index.js.map