spool-sdk 0.0.0-stage → 0.2.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
- # Temporary Holding Version
1
+ # spool-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript SDK for [Spool](https://github.com/ishyverma/spool), durable execution for AI agents on plain Postgres. Steps are recorded as they finish, so a run survives any worker or engine crash and resumes from its last recorded step.
4
+
5
+ ```sh
6
+ npm install spool-sdk # Node 24+
7
+ npx spool-engine # the engine, with DATABASE_URL and SPOOL_API_KEY set
8
+ ```
9
+
10
+ ```ts
11
+ import { Worker, workflow } from "spool-sdk";
12
+
13
+ const research = workflow("research-agent", async (ctx, input: { topic: string }) => {
14
+ const plan = await ctx.step("plan", () => llm.plan(input.topic));
15
+ const notes = await ctx.step("search", () => web.search(plan.query, { signal: ctx.signal }));
16
+ return ctx.step("write", () => llm.write(notes));
17
+ });
18
+
19
+ const worker = new Worker({
20
+ url: "http://127.0.0.1:7070",
21
+ apiKey: process.env.SPOOL_API_KEY!,
22
+ workflows: [research],
23
+ concurrency: 10,
24
+ });
25
+ worker.start();
26
+ process.on("SIGTERM", () => void worker.stop());
27
+ ```
28
+
29
+ ## How a run executes
30
+
31
+ A workflow function runs from the top on every attempt. Each `ctx.step(name, fn)` takes the next position in the run:
32
+
33
+ - If the engine has already recorded a step at that position, the step returns the stored output and `fn` is not called. The name must match, or the run stops with `StepMismatchError`: the code changed while the run was in flight.
34
+ - Otherwise `fn` runs, its output is recorded, and the step returns once the engine has acknowledged it.
35
+
36
+ So put everything that has an effect or costs money inside a step, keep step names stable, and await each step before starting the next. Outputs are stored as JSON and returned in that form on the first run too, so a `Date` comes back as a string every time.
37
+
38
+ Execution is at least once: if a worker dies after a step ran but before it was recorded, the next attempt runs it again.
39
+
40
+ ## When things go wrong
41
+
42
+ | Situation | What the worker does |
43
+ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
44
+ | The connection to the engine drops | Runs keep going; reports wait and are resent on the next connection. Reconnects with full-jitter backoff |
45
+ | The lease is lost (worker stalled, run reclaimed) | `ctx.signal` aborts and the run stops before its next step. Another worker continues it from the journal |
46
+ | A step was renamed or reordered mid-run | The run stops with an error log before anything runs |
47
+ | A step throws | The failure is recorded and the run stops here; the engine runs it again from that step after a growing random delay, up to `maxAttempts` times (default 3), then fails the run |
48
+ | A step throws `NonRetryableError` | The run fails at once |
49
+ | Workflow code throws outside any step | Treated as a failure of the next step |
50
+ | `stop()` | No new work; running runs finish (up to `drainTimeoutMs`, 30 s by default), then the stream closes |
51
+
52
+ ## Side effects that must happen once
53
+
54
+ A step can run more than once: after a failure, or when its worker dies before the step is recorded. Give anything with an external effect the step's idempotency key, which is the same on every try of that step:
55
+
56
+ ```ts
57
+ await ctx.step("charge", () =>
58
+ stripe.paymentIntents.create(
59
+ { amount: 4200, currency: "usd", customer },
60
+ { idempotencyKey: ctx.idempotencyKey },
61
+ ),
62
+ );
63
+ ```
64
+
65
+ `ctx.idempotencyKey` is `${runId}:${position}` and can only be read inside a step function.
66
+
67
+ ## Model calls
68
+
69
+ Wrap a call to a model in `ctx.llm` and return its answer with the model's name and token counts. It is a step (run once, replayed from the journal, retried on failure), and the engine also records the model, tokens, latency and cost, priced from its `SPOOL_LLM_PRICES` table:
70
+
71
+ ```ts
72
+ const plan = await ctx.llm("plan", async () => {
73
+ const message = await anthropic.messages.create({
74
+ model: "claude-sonnet-5-5",
75
+ max_tokens: 1024,
76
+ messages: [{ role: "user", content: `Plan research on ${input.topic}` }],
77
+ });
78
+ return {
79
+ output: message.content,
80
+ model: message.model,
81
+ inputTokens: message.usage.input_tokens,
82
+ outputTokens: message.usage.output_tokens,
83
+ };
84
+ });
85
+ ```
86
+
87
+ A replay returns the stored answer without calling the model again, so a recorded call is never paid for twice. A call that throws is retried like any step and records no usage; usage that is not a model name and two whole token counts fails the step for good, because it is a bug in the function.
88
+
89
+ ### Rate limits
90
+
91
+ Give a step or model call a `rateLimit` key to keep it within a provider's limit, set on the engine with `LimitsService.SetRateLimit` (for 500 requests a minute: capacity 500, refill 500/60 per second):
92
+
93
+ ```ts
94
+ const answer = await ctx.llm("answer", callModel, { rateLimit: "anthropic" });
95
+ ```
96
+
97
+ Before the call first runs, the engine takes a token from the key's bucket and records that as its own step, `(rate:anthropic)`, just before this one. If no token is due yet, the run stops on this worker without holding it and resumes, already holding its reserved token, once it is due. A replay or retry never takes a second token. A key with no limit set does not limit.
98
+
99
+ ## Sleeping and waiting for events
100
+
101
+ A run can pause for minutes or months without holding a worker, a lease or a connection:
102
+
103
+ ```ts
104
+ await ctx.sleep("24h"); // or milliseconds; at most 365 days
105
+
106
+ const answer = await ctx.waitForEvent<{ approved: boolean }>(
107
+ "approval",
108
+ { runId: ctx.runId }, // an event matches when its payload contains this object
109
+ { timeout: "7d" },
110
+ );
111
+ if (answer === null) return { status: "expired" }; // no event before the timeout
112
+ ```
113
+
114
+ Both stop the run on this worker (by throwing `RunSleepingError` or `RunWaitingError`, which you should let propagate); the engine queues it again when the time passes or the event arrives, and any worker replays it to that point and goes on. Send events with `RunService.SendEvent`, for example from a webhook:
115
+
116
+ ```sh
117
+ curl -H 'content-type: application/json' -H "authorization: Bearer $SPOOL_API_KEY" \
118
+ -d '{"tenantId":"acme","name":"approval","payload":{"runId":"01a2…","approved":true}}' \
119
+ http://127.0.0.1:7070/spool.v1.RunService/SendEvent
120
+ # {"eventId":"42","resumed":1}
121
+ ```
122
+
123
+ An event that arrives after the run started but before it reaches the wait is not lost: the wait takes it at once. Each run receives a given event at most once. Event payloads are JSON objects of at most 256 KiB.
124
+
125
+ ## Retries
126
+
127
+ ```ts
128
+ import { NonRetryableError } from "spool-sdk";
129
+
130
+ const answer = await ctx.step("call-model", () => llm.complete(prompt), { maxAttempts: 5 });
131
+
132
+ await ctx.step("validate", () => {
133
+ if (plan.queries.length === 0) throw new NonRetryableError("the plan has no queries");
134
+ });
135
+ ```
136
+
137
+ The engine keeps every failed attempt with its error's class and message (never the stack). A step that succeeds starts the count over for the next one.
138
+
139
+ ## Options
140
+
141
+ | Option | Default | Meaning |
142
+ | ---------------- | ----------------------- | --------------------------------------------------------- |
143
+ | `url`, `apiKey` | required | The engine and its API key; or pass `transport` instead |
144
+ | `workflows` | required | The workflows this worker runs |
145
+ | `concurrency` | 10 | Runs at once; the engine never sends more |
146
+ | `queue` | `default` | Queue to take work from |
147
+ | `workerId` | host, pid and a suffix | Lease holder name, stable across reconnects |
148
+ | `logger` | warnings to the console | Anything with pino's `debug/info/warn/error(fields, msg)` |
149
+ | `backoff` | 100 ms base, 5 s cap | Reconnect and resend delays |
150
+ | `drainTimeoutMs` | 30000 | How long `stop()` waits for running runs |
@@ -0,0 +1,15 @@
1
+ export interface BackoffPolicy {
2
+ /** The first delay is drawn from [0, baseMs). */
3
+ readonly baseMs: number;
4
+ /** No delay exceeds this. */
5
+ readonly capMs: number;
6
+ }
7
+ /**
8
+ * Full jitter: a uniform draw from [0, min(cap, base × 2^attempt)). Many workers that lost
9
+ * the engine at the same moment spread their retries out instead of returning together.
10
+ */
11
+ export declare function backoffDelay(attempt: number, policy: BackoffPolicy, random?: () => number): number;
12
+ /** Resolves after `ms`, or rejects with the signal's reason as soon as it aborts. */
13
+ export declare function sleep(ms: number, signal: AbortSignal): Promise<void>;
14
+ /** Settles like `promise`, or rejects with the signal's reason if it aborts first. */
15
+ export declare function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Full jitter: a uniform draw from [0, min(cap, base × 2^attempt)). Many workers that lost
3
+ * the engine at the same moment spread their retries out instead of returning together.
4
+ */
5
+ export function backoffDelay(attempt, policy, random = Math.random) {
6
+ // 2^attempt overflows to Infinity for large attempts; min() keeps the result finite.
7
+ const ceiling = Math.min(policy.capMs, policy.baseMs * 2 ** attempt);
8
+ return Math.floor(random() * ceiling);
9
+ }
10
+ /** Resolves after `ms`, or rejects with the signal's reason as soon as it aborts. */
11
+ export function sleep(ms, signal) {
12
+ return new Promise((resolve, reject) => {
13
+ if (signal.aborted) {
14
+ reject(abortReason(signal));
15
+ return;
16
+ }
17
+ const onAbort = () => {
18
+ clearTimeout(timer);
19
+ reject(abortReason(signal));
20
+ };
21
+ const timer = setTimeout(() => {
22
+ signal.removeEventListener("abort", onAbort);
23
+ resolve();
24
+ }, ms);
25
+ signal.addEventListener("abort", onAbort, { once: true });
26
+ });
27
+ }
28
+ /** Settles like `promise`, or rejects with the signal's reason if it aborts first. */
29
+ export function abortable(promise, signal) {
30
+ if (signal.aborted)
31
+ return Promise.reject(abortReason(signal));
32
+ return new Promise((resolve, reject) => {
33
+ const onAbort = () => {
34
+ reject(abortReason(signal));
35
+ };
36
+ signal.addEventListener("abort", onAbort, { once: true });
37
+ promise.then((value) => {
38
+ signal.removeEventListener("abort", onAbort);
39
+ resolve(value);
40
+ }, (error) => {
41
+ signal.removeEventListener("abort", onAbort);
42
+ reject(error instanceof Error ? error : new Error(String(error)));
43
+ });
44
+ });
45
+ }
46
+ /** The SDK always aborts with an Error; anything else is wrapped so callers get one. */
47
+ function abortReason(signal) {
48
+ const reason = signal.reason;
49
+ return reason instanceof Error ? reason : new Error(String(reason));
50
+ }
51
+ //# sourceMappingURL=backoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backoff.js","sourceRoot":"","sources":["../src/backoff.ts"],"names":[],"mappings":"AAOA;;;GAGG;AACH,MAAM,UAAU,YAAY,CAC1B,OAAe,EACf,MAAqB,EACrB,SAAuB,IAAI,CAAC,MAAM;IAElC,qFAAqF;IACrF,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,M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I,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,OAAO,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE;YACR,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC7C,OAAO,CAAC,KAAK,CAAC,CAAC;QACjB,CAAC,EACD,CAAC,KAAc,EAAE,EAAE;YACjB,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC7C,MAAM,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACpE,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,wFAAwF;AACxF,SAAS,WAAW,CAAC,MAAmB;IACtC,MAAM,MAAM,GAAY,MAAM,CAAC,MAAM,CAAC;IACtC,OAAO,MAAM,YAAY,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AACtE,CAAC"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * An unbounded in-memory queue read as an async iterable: producers push, one consumer
3
+ * iterates. The worker's outgoing stream: runs, the heartbeat timer and the pull logic all
4
+ * push requests into it. Producers bound what they push; the channel does not.
5
+ */
6
+ export declare class Channel<T> implements AsyncIterable<T> {
7
+ #private;
8
+ /** Queues an item; returns false, dropping it, once the channel is closed. */
9
+ push(item: T): boolean;
10
+ /** Ends the iteration after the queued items; with an error, the iterator then throws it. */
11
+ close(error?: Error): void;
12
+ [Symbol.asyncIterator](): AsyncIterator<T>;
13
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * An unbounded in-memory queue read as an async iterable: producers push, one consumer
3
+ * iterates. The worker's outgoing stream: runs, the heartbeat timer and the pull logic all
4
+ * push requests into it. Producers bound what they push; the channel does not.
5
+ */
6
+ export class Channel {
7
+ #items = [];
8
+ #closed = false;
9
+ #error;
10
+ #wake;
11
+ /** Queues an item; returns false, dropping it, once the channel is closed. */
12
+ push(item) {
13
+ if (this.#closed)
14
+ return false;
15
+ this.#items.push(item);
16
+ this.#wake?.();
17
+ return true;
18
+ }
19
+ /** Ends the iteration after the queued items; with an error, the iterator then throws it. */
20
+ close(error) {
21
+ if (this.#closed)
22
+ return;
23
+ this.#closed = true;
24
+ this.#error = error;
25
+ this.#wake?.();
26
+ }
27
+ async *[Symbol.asyncIterator]() {
28
+ for (;;) {
29
+ const item = this.#items.shift();
30
+ if (item !== undefined) {
31
+ yield item;
32
+ continue;
33
+ }
34
+ if (this.#closed) {
35
+ if (this.#error !== undefined)
36
+ throw this.#error;
37
+ return;
38
+ }
39
+ await new Promise((resolve) => {
40
+ this.#wake = resolve;
41
+ });
42
+ this.#wake = undefined;
43
+ }
44
+ }
45
+ }
46
+ //# sourceMappingURL=channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.js","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,OAAO,OAAO;IAClB,MAAM,GAAQ,EAAE,CAAC;IACjB,OAAO,GAAG,KAAK,CAAC;IAChB,MAAM,CAAoB;IAC1B,KAAK,CAA2B;IAEhC,8EAA8E;IAC9E,IAAI,CAAC,IAAO;QACV,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO,KAAK,CAAC;QAC/B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;QACf,OAAO,IAAI,CAAC;IACd,CAAC;IAED,6FAA6F;IAC7F,KAAK,CAAC,KAAa;QACjB,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,KAAK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