claim-once 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/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-11-26)
4
+
5
+ - `claim-once-lab --check` exits 1 if claim-once ran any effect twice or lost one, so the lab works as a CI gate. `labProblems(rows)` is exported from `claim-once/lab` for the same check in code.
6
+ - CI runs the full lab (20 operations, 8 runners) with `--check` on Node 20, 22 and 24 and writes the table to the job summary.
7
+ - README: how to pass the fencing token to your own database so a paused worker cannot overwrite a newer result, and a comparison with idemfence, Redis locks and BullMQ `jobId`. A Postgres store is not part of this release.
8
+
9
+ ## 0.1.0
10
+
11
+ - First release: Redis Lua claim state machine (pending, done, failed, in_doubt, free) with leases, heartbeats and fencing tokens.
12
+ - `runOnce`, manual `reserve` / `begin` / `complete`, `inspect`, `resolve` and a `reconcile` hook.
13
+ - `onceProcessor` for BullMQ and `onceTool` for tool calls.
14
+ - `claim-once-lab` crash lab with real child processes and SIGKILL.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Krrish Kumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,249 @@
1
- # Temporary Holding Version
1
+ # claim-once
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
+ [![npm](https://img.shields.io/npm/v/claim-once)](https://www.npmjs.com/package/claim-once)
4
+ [![CI](https://github.com/Krrishkumar125/claim-once/actions/workflows/ci.yml/badge.svg)](https://github.com/Krrishkumar125/claim-once/actions/workflows/ci.yml)
5
+
6
+ **Run a side effect at most once per operation key, across every worker, with Redis. When it cannot know, it says so.**
7
+
8
+ Queues and agents retry. BullMQ hands a stalled job to another worker. A tool call gets replayed after a timeout. A process dies between sending the email and writing down that it sent it. Each of those is a chance to charge a card twice, or to quietly never charge it at all.
9
+
10
+ `claim-once` gives each operation a key and a small state machine in Redis. One caller wins the claim. A repeat call gets the stored result back. If a worker crashed after the effect may have started, the key goes to `in_doubt` and stays there until you check the real system, instead of the library guessing.
11
+
12
+ ```bash
13
+ npm install claim-once ioredis
14
+ ```
15
+
16
+ ```ts
17
+ import { Redis } from 'ioredis';
18
+ import { createClaimOnce } from 'claim-once';
19
+
20
+ const once = createClaimOnce({ redis: new Redis(process.env.REDIS_URL), namespace: 'billing' });
21
+
22
+ const receipt = await once.runOnce(`refund:${orderId}`, async ({ idempotencyKey }) => {
23
+ return stripe.refunds.create({ payment_intent: pi }, { idempotencyKey });
24
+ });
25
+ ```
26
+
27
+ Call it again with the same key, from any process, and you get the same `receipt` back without a second refund.
28
+
29
+ ## What it guarantees, and what it does not
30
+
31
+ This is **at most once effect execution with an explicit in_doubt state**. It is not "exactly once". Nothing that talks to an outside system over a network can promise that on its own.
32
+
33
+ - Under any number of concurrent callers on any number of machines, at most one holds a live claim on a key. Every state change is one Lua script, so Redis runs it atomically.
34
+ - If a worker dies **after claiming but before the effect began**, the lease runs out and the next caller takes over with a higher fencing token. Nothing is lost.
35
+ - If a worker dies **after the effect began but before it reported back**, nobody can tell from Redis whether the charge went through. The key becomes `in_doubt` and every later call throws `InDoubtError` until you reconcile it. You get no duplicate, and no silent loss either, but you do get work to do.
36
+ - A slow worker that was only stalled (not dead) can still finish with its token and settle the key as done.
37
+
38
+ The limits, plainly:
39
+
40
+ - **Redis is the source of truth.** If Redis loses writes (failover without persistence, a flushed instance), claims are lost with it. Use a Redis with AOF or replicas you trust for this.
41
+ - **The effect itself can still run twice in one case:** your reconcile hook says `not_happened` when it actually did happen. Reconcile against the real system, using the idempotency key.
42
+ - **Leases use the Redis server clock,** so worker clock skew does not matter, but a worker blocked longer than its lease will be treated as gone. Pick a lease longer than your worst pause, and let heartbeats extend it.
43
+ - **Downstream idempotency is still the best protection.** `ctx.idempotencyKey` is stable for a key across every attempt. Pass it to Stripe, your email provider, or your own API so a retry after `in_doubt` is harmless there too. `ctx.token` strictly increases per key if your downstream can reject stale writers.
44
+
45
+ ## How it works
46
+
47
+ Each key is one Redis hash with a state:
48
+
49
+ | State | Meaning | Next call gets |
50
+ |---|---|---|
51
+ | `pending` | Claimed, lease live | `InProgressError` (or waits, with `onBusy: 'wait'`) |
52
+ | `pending`, lease ran out, effect not begun | Owner died before doing anything | A takeover with a new token |
53
+ | `in_doubt` | Lease ran out after the effect began, or the effect threw an ambiguous error | `InDoubtError`, or your `reconcile` hook runs |
54
+ | `done` | Result stored | The stored result |
55
+ | `failed` | Marked failed for good | `FailedError` |
56
+ | `free` | Released after a failure that did not run the effect | A new claim |
57
+
58
+ `runOnce` does this for you: `reserve`, then `begin` right before calling your function, a heartbeat every `leaseMs / 3`, then `complete` with the result. You can call those steps yourself for multi-step work:
59
+
60
+ ```ts
61
+ const r = await once.reserve('payout:42');
62
+ if (r.status === 'reserved') {
63
+ const { claim } = r;
64
+ const quote = await loadQuote(); // safe: a crash here frees the key after the lease
65
+ await claim.begin(); // from here on, a lost lease means in_doubt
66
+ const res = await bank.payout(quote, { idempotencyKey: claim.idempotencyKey });
67
+ await claim.complete(res);
68
+ }
69
+ ```
70
+
71
+ ## Fencing your own writes
72
+
73
+ The fencing token protects Redis, and you can pass it on so a downstream store protects itself too. Every claim gets a token higher than any earlier claim on the same key, and `runOnce` hands it to your function as `ctx.token`. Store it with the write and refuse writes that carry a lower one:
74
+
75
+ ```ts
76
+ await once.runOnce(`ledger:${orderId}`, async ({ token }) => {
77
+ // Postgres: the row only changes if no newer claim has written it.
78
+ const res = await sql`
79
+ UPDATE orders SET status = 'refunded', fence = ${token}
80
+ WHERE id = ${orderId} AND fence < ${token}`;
81
+ if (res.count === 0) throw new Error('a newer claim already wrote this order');
82
+ });
83
+ ```
84
+
85
+ A worker that was paused (a GC pause, a frozen VM) and comes back after a takeover then cannot overwrite the newer result, even if its own Redis calls are slow to fail.
86
+
87
+ ## Errors from your function
88
+
89
+ By default a thrown error **releases** the key, which means "the effect did not happen, a retry is fine". That is right for a declined card or a 400. It is wrong for a timeout after the request was sent. Tell it which is which:
90
+
91
+ ```ts
92
+ await once.runOnce(key, sendInvoice, {
93
+ onError: (err) => (isTimeout(err) ? 'in_doubt' : isBadRequest(err) ? 'fail' : 'release'),
94
+ });
95
+ ```
96
+
97
+ `maxAttempts` on the client turns the Nth release into `failed`.
98
+
99
+ ## Reconciling in_doubt keys
100
+
101
+ Pass a `reconcile` hook and `runOnce` calls it once when it finds an in_doubt key:
102
+
103
+ ```ts
104
+ const once = createClaimOnce({
105
+ redis,
106
+ namespace: 'billing',
107
+ reconcile: async ({ idempotencyKey }) => {
108
+ const found = await stripe.refunds.list({ payment_intent: pi }); // or look up your own ledger
109
+ const hit = found.data.find((r) => r.metadata.key === idempotencyKey);
110
+ if (hit) return { status: 'done', result: hit };
111
+ return { status: 'not_happened' }; // only if you are sure; this allows a new attempt
112
+ // return undefined to leave it in_doubt for a human
113
+ },
114
+ });
115
+ ```
116
+
117
+ Or settle keys from a script with `once.inspect(key)` and `once.resolve(key, token, outcome)`. `resolve` needs the token from the in_doubt record, so two reconcilers cannot both settle the same key.
118
+
119
+ ## BullMQ
120
+
121
+ ```ts
122
+ import { Worker } from 'bullmq';
123
+ import { onceProcessor } from 'claim-once';
124
+
125
+ new Worker('billing', onceProcessor(once, async (job, { idempotencyKey }) => {
126
+ return chargeCustomer(job.data, { idempotencyKey });
127
+ }), { connection });
128
+ ```
129
+
130
+ The key defaults to `<queueName>:<job.id>`. If the same work can arrive as different jobs (a user double clicks and two jobs get added), key it by the business id instead: `onceProcessor(once, fn, { key: (job) => 'charge:' + job.data.orderId })`.
131
+
132
+ When a stalled job is redelivered while the first worker still holds the claim, the second gets `InProgressError`, so BullMQ retries it later and it then receives the stored result. Give the queue `attempts` and a `backoff`. An `InDoubtError` means a person or a reconcile hook needs to look; you may want to move those jobs aside with BullMQ's `UnrecoverableError`.
133
+
134
+ ## Tool calls
135
+
136
+ ```ts
137
+ import { onceTool } from 'claim-once';
138
+
139
+ const sendEmail = onceTool(once, 'send_email', async (args: { to: string; body: string }) => {
140
+ return mailer.send(args);
141
+ });
142
+
143
+ // Many tool frameworks call execute(args, { toolCallId }). The helper reads that id.
144
+ await sendEmail({ to, body }, { toolCallId: 'call_abc' });
145
+ ```
146
+
147
+ A replayed call with the same tool name and call id returns the first result. Pass `callId: (args, options) => ...` if your framework names it differently.
148
+
149
+ ## The crash lab
150
+
151
+ `claim-once` ships a lab that starts real Node processes against a real Redis, kills them with `SIGKILL` at chosen points, and counts how many times the side effect ran. The effect appends a line to a file, so a kill cannot undo an effect that already happened.
152
+
153
+ ```bash
154
+ npx claim-once-lab --redis redis://127.0.0.1:6379
155
+ ```
156
+
157
+ It compares four strategies:
158
+
159
+ - **no guard**: just run it.
160
+ - **check, run, then set done**: `GET done`, run, `SET done`. The common first attempt.
161
+ - **SET NX first, then run**: mark the key before the effect, so a crash after marking forgets the work.
162
+ - **claim-once**: `reserve`, `begin`, run, `complete`.
163
+
164
+ And four scenarios. In the crash scenarios each operation's first worker is killed at the crash point, the lease runs out, and a second worker gets every job again, the way a queue redelivers.
165
+
166
+ This is the output of a real run (20 operations per scenario, 8 concurrent runners, 400 ms lease, Redis 8.10 on Linux, Node 24):
167
+
168
+ | Scenario | Strategy | Ops | Effects run | Duplicates | Lost | in_doubt |
169
+ |---|---|---:|---:|---:|---:|---:|
170
+ | SIGKILL after the effect, before it is recorded | no guard | 20 | 40 | 20 | 0 | 0 |
171
+ | SIGKILL after the effect, before it is recorded | check, run, then set done | 20 | 40 | 20 | 0 | 0 |
172
+ | SIGKILL after the effect, before it is recorded | SET NX first, then run | 20 | 20 | 0 | 0 | 0 |
173
+ | SIGKILL after the effect, before it is recorded | claim-once | 20 | 20 | 0 | 0 | 20 |
174
+ | SIGKILL after the claim, before the effect | no guard | 20 | 20 | 0 | 0 | 0 |
175
+ | SIGKILL after the claim, before the effect | check, run, then set done | 20 | 20 | 0 | 0 | 0 |
176
+ | SIGKILL after the claim, before the effect | SET NX first, then run | 20 | 0 | 0 | 20 | 0 |
177
+ | SIGKILL after the claim, before the effect | claim-once | 20 | 20 | 0 | 0 | 0 |
178
+ | event loop blocked past the lease, job redelivered | no guard | 20 | 40 | 20 | 0 | 0 |
179
+ | event loop blocked past the lease, job redelivered | check, run, then set done | 20 | 40 | 20 | 0 | 0 |
180
+ | event loop blocked past the lease, job redelivered | SET NX first, then run | 20 | 20 | 0 | 0 | 0 |
181
+ | event loop blocked past the lease, job redelivered | claim-once | 20 | 20 | 0 | 0 | 0 |
182
+ | concurrent runners on the same keys | no guard | 20 | 160 | 140 | 0 | 0 |
183
+ | concurrent runners on the same keys | check, run, then set done | 20 | 160 | 140 | 0 | 0 |
184
+ | concurrent runners on the same keys | SET NX first, then run | 20 | 20 | 0 | 0 | 0 |
185
+ | concurrent runners on the same keys | claim-once | 20 | 20 | 0 | 0 | 0 |
186
+
187
+ 160 worker processes were SIGKILLed in that run.
188
+
189
+ How to read it:
190
+
191
+ - Killed **after the effect**: claim-once ran each effect once and left all 20 keys `in_doubt`, which is the honest answer. The marking strategy also ran each once, but only because it never retries anything, which the next row shows.
192
+ - Killed **before the effect**: marking first lost all 20 operations with nothing flagging them. claim-once saw that the effect never began and took over.
193
+ - **Stalled past the lease**: the stalled worker could not heartbeat, a second worker started, saw a lease that ran out after the effect began, and backed off with in_doubt. The first worker then woke up, ran the effect and settled the key as done with its own token.
194
+ - **Concurrent**: one claim per key won, the rest got `InProgressError`.
195
+
196
+ The same lab runs in CI on every push, on Node 20, 22 and 24, with `--check`: the build fails if claim-once runs any effect twice or loses one, and the table for that run is in the job summary of the [CI workflow](https://github.com/Krrishkumar125/claim-once/actions/workflows/ci.yml). Run it yourself with `npx claim-once-lab --check`.
197
+
198
+ The lab uses keys under `claim-once-lab:*` and deletes them when it finishes. Point it at a scratch Redis anyway. You can also run it from code: `import { runLab, formatTable } from 'claim-once/lab'`.
199
+
200
+ ## Compared with
201
+
202
+ Checked on 26 Nov 2026.
203
+
204
+ | | **claim-once** | [idemfence](https://www.npmjs.com/package/idemfence) 0.1.0 | Redis locks (Redlock and similar) | BullMQ `jobId` |
205
+ | --- | --- | --- | --- | --- |
206
+ | Scope | Any side effect: jobs, tool calls, scripts | HTTP requests (Idempotency-Key header) | Mutual exclusion | Enqueueing |
207
+ | Fencing tokens | Yes | Yes | No | No |
208
+ | Stores and replays the result | Yes | Yes, the HTTP response | No | No |
209
+ | Says "unknown" after a crash mid-effect (`in_doubt` plus reconcile hook) | Yes | No (none in its 0.1.0 code or docs) | No | No |
210
+ | Store | Redis | PostgreSQL | Redis | Redis |
211
+ | Crash lab with real SIGKILL | Yes, in CI | No | No | No |
212
+
213
+ If your idempotency boundary is an HTTP API and your data lives in Postgres, idemfence is built for that. claim-once is for work that happens inside workers and agents, where the question after a crash is whether the effect already happened.
214
+
215
+ A Postgres store for claim-once is not in this release. The state machine is small, but every transition has to stay one atomic step with the same lease and token rules, and that needs its own crash lab run before it ships.
216
+
217
+ ## API
218
+
219
+ `createClaimOnce(options)` returns a `ClaimOnce`.
220
+
221
+ | Option | Default | |
222
+ |---|---|---|
223
+ | `redis` | required | An ioredis client or Cluster |
224
+ | `namespace` | `claim-once` | Key prefix |
225
+ | `leaseMs` | `30000` | How long a claim stays exclusive without a heartbeat |
226
+ | `retentionMs` | 7 days | How long records, including results, are kept |
227
+ | `maxAttempts` | `0` (no limit) | Releases after which the key becomes failed |
228
+ | `owner` | host, pid, random | Written to records, for debugging |
229
+ | `serialize` / `deserialize` | JSON | How results are stored |
230
+ | `reconcile` | none | Default hook for in_doubt keys |
231
+
232
+ Methods:
233
+
234
+ - `runOnce(key, fn, { leaseMs, heartbeatMs, onBusy, waitTimeoutMs, onError, reconcile })`. `fn` receives `{ key, idempotencyKey, token, signal }`. `signal` aborts if the heartbeat finds the claim was taken away.
235
+ - `reserve(key)` returns `reserved` (with a `Claim`), `done`, `busy`, `in_doubt` or `failed`.
236
+ - `Claim`: `begin()`, `heartbeat()`, `complete(result)`, `release(error?)`, `fail(error)`, `markInDoubt(error?)`. Each throws `StaleClaimError` if the token is no longer current.
237
+ - `inspect(key)`, `resolve(key, token, outcome)`, `forget(key)`.
238
+
239
+ Errors: `InProgressError`, `InDoubtError`, `FailedError`, `StaleClaimError`, all extending `ClaimOnceError` and carrying `key`.
240
+
241
+ Results must survive your `serialize` function. With the default JSON, a `Date` comes back as a string.
242
+
243
+ ## Requirements
244
+
245
+ Node 18 or newer. Redis 6 or newer with Lua scripting (tested on Redis 7 and 8). `ioredis` 5 is a peer dependency. `bullmq` is optional and only needed for your own workers.
246
+
247
+ ## License
248
+
249
+ MIT, Krrish Kumar
@@ -0,0 +1,392 @@
1
+ // src/errors.ts
2
+ var ClaimOnceError = class extends Error {
3
+ key;
4
+ constructor(message, key) {
5
+ super(message);
6
+ this.name = new.target.name;
7
+ this.key = key;
8
+ }
9
+ };
10
+ var InProgressError = class extends ClaimOnceError {
11
+ owner;
12
+ retryAfterMs;
13
+ constructor(key, owner, retryAfterMs) {
14
+ super(`claim-once: "${key}" is already claimed by ${owner || "another caller"} (lease ends in ${retryAfterMs} ms)`, key);
15
+ this.owner = owner;
16
+ this.retryAfterMs = retryAfterMs;
17
+ }
18
+ };
19
+ var InDoubtError = class extends ClaimOnceError {
20
+ token;
21
+ record;
22
+ constructor(key, token, record) {
23
+ super(`claim-once: "${key}" is in_doubt (token ${token}). The effect may have run. Reconcile before retrying.`, key);
24
+ this.token = token;
25
+ this.record = record;
26
+ }
27
+ };
28
+ var FailedError = class extends ClaimOnceError {
29
+ reason;
30
+ constructor(key, reason) {
31
+ super(`claim-once: "${key}" is marked failed: ${reason}`, key);
32
+ this.reason = reason;
33
+ }
34
+ };
35
+ var StaleClaimError = class extends ClaimOnceError {
36
+ token;
37
+ state;
38
+ constructor(key, token, state) {
39
+ super(`claim-once: claim on "${key}" with token ${token} is no longer current (record is ${state})`, key);
40
+ this.token = token;
41
+ this.state = state;
42
+ }
43
+ };
44
+
45
+ // src/claim-once.ts
46
+ import { createHash, randomBytes } from "crypto";
47
+ import { hostname } from "os";
48
+
49
+ // src/scripts.ts
50
+ var NOW = `
51
+ local k = KEYS[1]
52
+ local tm = redis.call('TIME')
53
+ local now = tonumber(tm[1]) * 1000 + math.floor(tonumber(tm[2]) / 1000)
54
+ `;
55
+ var RESERVE = `${NOW}
56
+ local owner = ARGV[1]
57
+ local lease = tonumber(ARGV[2])
58
+ local keep = tonumber(ARGV[3])
59
+ local s = redis.call('HGET', k, 's')
60
+ if s == 'done' then return {'done', redis.call('HGET', k, 'r') or '', redis.call('HGET', k, 't') or '0'} end
61
+ if s == 'failed' then return {'failed', redis.call('HGET', k, 'e') or '', redis.call('HGET', k, 't') or '0'} end
62
+ if s == 'in_doubt' then return {'in_doubt', redis.call('HGET', k, 't') or '0', redis.call('HGET', k, 'o') or ''} end
63
+ local takeover = '0'
64
+ if s == 'pending' then
65
+ local l = tonumber(redis.call('HGET', k, 'l') or '0')
66
+ if l > now then
67
+ return {'busy', redis.call('HGET', k, 't') or '0', redis.call('HGET', k, 'o') or '', tostring(l - now)}
68
+ end
69
+ if redis.call('HGET', k, 'b') == '1' then
70
+ redis.call('HSET', k, 's', 'in_doubt', 'u', now)
71
+ return {'in_doubt', redis.call('HGET', k, 't') or '0', redis.call('HGET', k, 'o') or ''}
72
+ end
73
+ takeover = '1'
74
+ end
75
+ local t = redis.call('HINCRBY', k, 't', 1)
76
+ local a = redis.call('HINCRBY', k, 'a', 1)
77
+ redis.call('HSET', k, 's', 'pending', 'o', owner, 'l', now + lease, 'b', '0', 'u', now)
78
+ redis.call('HSETNX', k, 'c', now)
79
+ redis.call('HDEL', k, 'r', 'e')
80
+ redis.call('PEXPIRE', k, keep)
81
+ return {'reserved', tostring(t), takeover, tostring(a)}
82
+ `;
83
+ var OWNED = `
84
+ if redis.call('HGET', k, 't') ~= ARGV[1] then return 'stale' end
85
+ local s = redis.call('HGET', k, 's')
86
+ `;
87
+ var BEGIN = `${NOW}${OWNED}
88
+ if s ~= 'pending' then return s end
89
+ redis.call('HSET', k, 'b', '1', 'l', now + tonumber(ARGV[2]), 'u', now)
90
+ return 'ok'
91
+ `;
92
+ var HEARTBEAT = `${NOW}${OWNED}
93
+ if s ~= 'pending' then return s end
94
+ redis.call('HSET', k, 'l', now + tonumber(ARGV[2]), 'u', now)
95
+ return 'ok'
96
+ `;
97
+ var COMPLETE = `${NOW}${OWNED}
98
+ if s ~= 'pending' and s ~= 'in_doubt' then return s end
99
+ redis.call('HSET', k, 's', 'done', 'r', ARGV[2], 'u', now)
100
+ redis.call('HDEL', k, 'l', 'e')
101
+ redis.call('PEXPIRE', k, tonumber(ARGV[3]))
102
+ return 'ok'
103
+ `;
104
+ var RELEASE = `${NOW}${OWNED}
105
+ if s ~= 'pending' and s ~= 'in_doubt' then return s end
106
+ local a = tonumber(redis.call('HGET', k, 'a') or '0')
107
+ local max = tonumber(ARGV[3])
108
+ if max > 0 and a >= max then
109
+ redis.call('HSET', k, 's', 'failed', 'e', ARGV[2], 'u', now)
110
+ redis.call('HDEL', k, 'l')
111
+ return 'failed'
112
+ end
113
+ redis.call('HSET', k, 's', 'free', 'e', ARGV[2], 'b', '0', 'u', now)
114
+ redis.call('HDEL', k, 'l')
115
+ return 'released'
116
+ `;
117
+ var FAIL = `${NOW}${OWNED}
118
+ if s ~= 'pending' and s ~= 'in_doubt' then return s end
119
+ redis.call('HSET', k, 's', 'failed', 'e', ARGV[2], 'u', now)
120
+ redis.call('HDEL', k, 'l')
121
+ return 'ok'
122
+ `;
123
+ var MARK_IN_DOUBT = `${NOW}${OWNED}
124
+ if s ~= 'pending' then return s end
125
+ redis.call('HSET', k, 's', 'in_doubt', 'e', ARGV[2], 'u', now)
126
+ return 'ok'
127
+ `;
128
+ var RESOLVE = `${NOW}${OWNED}
129
+ if s ~= 'in_doubt' then return s end
130
+ local outcome = ARGV[2]
131
+ if outcome == 'done' then
132
+ redis.call('HSET', k, 's', 'done', 'r', ARGV[3], 'u', now)
133
+ redis.call('HDEL', k, 'l', 'e')
134
+ redis.call('PEXPIRE', k, tonumber(ARGV[4]))
135
+ elseif outcome == 'not_happened' then
136
+ redis.call('HSET', k, 's', 'free', 'b', '0', 'u', now)
137
+ redis.call('HDEL', k, 'l')
138
+ else
139
+ redis.call('HSET', k, 's', 'failed', 'e', ARGV[3], 'u', now)
140
+ redis.call('HDEL', k, 'l')
141
+ end
142
+ return 'ok'
143
+ `;
144
+
145
+ // src/claim-once.ts
146
+ var DAY = 864e5;
147
+ var Scripts = class {
148
+ constructor(redis) {
149
+ this.redis = redis;
150
+ }
151
+ redis;
152
+ shas = /* @__PURE__ */ new Map();
153
+ async run(script, key, args) {
154
+ let sha = this.shas.get(script);
155
+ if (!sha) {
156
+ sha = createHash("sha1").update(script).digest("hex");
157
+ this.shas.set(script, sha);
158
+ }
159
+ try {
160
+ return await this.redis.evalsha(sha, 1, key, ...args);
161
+ } catch (err) {
162
+ if (err instanceof Error && /NOSCRIPT/.test(err.message)) return this.redis.eval(script, 1, key, ...args);
163
+ throw err;
164
+ }
165
+ }
166
+ };
167
+ function errorText(err) {
168
+ if (err instanceof Error) return `${err.name}: ${err.message}`.slice(0, 500);
169
+ return String(err).slice(0, 500);
170
+ }
171
+ var Claim = class {
172
+ constructor(core, key, token, attempt) {
173
+ this.core = core;
174
+ this.key = key;
175
+ this.token = token;
176
+ this.attempt = attempt;
177
+ }
178
+ core;
179
+ key;
180
+ token;
181
+ attempt;
182
+ get idempotencyKey() {
183
+ return this.core.idempotencyKey(this.key);
184
+ }
185
+ /**
186
+ * Call right before the side effect. From here on, a lost lease means in_doubt instead of a
187
+ * silent retry. Throws StaleClaimError if someone else took the key over in the meantime.
188
+ */
189
+ async begin(leaseMs) {
190
+ await this.owned(BEGIN, [this.token, leaseMs ?? this.core.leaseMs]);
191
+ }
192
+ /** Extend the lease. Throws StaleClaimError if the claim is no longer ours. */
193
+ async heartbeat(leaseMs) {
194
+ await this.owned(HEARTBEAT, [this.token, leaseMs ?? this.core.leaseMs]);
195
+ }
196
+ /** Store the result. Later calls for this key get it back without running anything. */
197
+ async complete(result) {
198
+ await this.owned(COMPLETE, [this.token, this.core.serialize(result), this.core.retentionMs]);
199
+ }
200
+ /** The effect did not happen. Free the key for a retry (or mark failed after maxAttempts). */
201
+ async release(error) {
202
+ const r = String(await this.core.scripts.run(RELEASE, this.core.redisKey(this.key), [this.token, error === void 0 ? "" : errorText(error), this.core.maxAttempts]));
203
+ if (r === "released" || r === "failed") return r;
204
+ throw new StaleClaimError(this.key, this.token, r);
205
+ }
206
+ /** Mark the key failed for good. Later calls throw FailedError. */
207
+ async fail(error) {
208
+ await this.owned(FAIL, [this.token, errorText(error)]);
209
+ }
210
+ /** We cannot tell whether the effect happened. Park the key as in_doubt for reconciliation. */
211
+ async markInDoubt(error) {
212
+ await this.owned(MARK_IN_DOUBT, [this.token, error === void 0 ? "" : errorText(error)]);
213
+ }
214
+ async owned(script, args) {
215
+ const r = String(await this.core.scripts.run(script, this.core.redisKey(this.key), args));
216
+ if (r !== "ok") throw new StaleClaimError(this.key, this.token, r);
217
+ }
218
+ };
219
+ var ClaimOnce = class {
220
+ redis;
221
+ namespace;
222
+ leaseMs;
223
+ retentionMs;
224
+ owner;
225
+ maxAttempts;
226
+ serialize;
227
+ deserialize;
228
+ /** @internal */
229
+ scripts;
230
+ defaultReconcile;
231
+ constructor(opts) {
232
+ if (!opts?.redis) throw new TypeError("claim-once: `redis` (an ioredis client) is required");
233
+ this.redis = opts.redis;
234
+ this.namespace = opts.namespace ?? "claim-once";
235
+ this.leaseMs = opts.leaseMs ?? 3e4;
236
+ this.retentionMs = opts.retentionMs ?? 7 * DAY;
237
+ this.owner = opts.owner ?? `${hostname()}:${process.pid}:${randomBytes(3).toString("hex")}`;
238
+ this.maxAttempts = opts.maxAttempts ?? 0;
239
+ this.serialize = opts.serialize ?? ((v) => v === void 0 ? "" : JSON.stringify(v));
240
+ this.deserialize = opts.deserialize ?? ((raw) => raw === "" ? void 0 : JSON.parse(raw));
241
+ this.defaultReconcile = opts.reconcile;
242
+ if (!(this.leaseMs > 0)) throw new RangeError("claim-once: leaseMs must be > 0");
243
+ if (!(this.retentionMs > this.leaseMs)) throw new RangeError("claim-once: retentionMs must be greater than leaseMs");
244
+ this.scripts = new Scripts(this.redis);
245
+ }
246
+ /** @internal */
247
+ redisKey(key) {
248
+ if (typeof key !== "string" || key.length === 0) throw new TypeError("claim-once: key must be a non-empty string");
249
+ return `${this.namespace}:{${key}}`;
250
+ }
251
+ idempotencyKey(key) {
252
+ return `${this.namespace}:${key}`;
253
+ }
254
+ /** Try to take the key. Atomic: under any number of concurrent callers, at most one gets `reserved`. */
255
+ async reserve(key, opts = {}) {
256
+ const raw = await this.scripts.run(RESERVE, this.redisKey(key), [this.owner, opts.leaseMs ?? this.leaseMs, this.retentionMs]);
257
+ const [status, a = "", b = "", c = ""] = raw.map(String);
258
+ switch (status) {
259
+ case "reserved":
260
+ return { status, claim: new Claim(this, key, Number(a), Number(c)), takeover: b === "1" };
261
+ case "done":
262
+ return { status, result: this.deserialize(a), token: Number(b) };
263
+ case "failed":
264
+ return { status, reason: a, token: Number(b) };
265
+ case "in_doubt":
266
+ return { status, token: Number(a), owner: b };
267
+ case "busy":
268
+ return { status, token: Number(a), owner: b, retryAfterMs: Number(c) };
269
+ default:
270
+ throw new Error(`claim-once: unexpected script reply ${JSON.stringify(raw)}`);
271
+ }
272
+ }
273
+ /** Read the record for a key, or null if none exists. */
274
+ async inspect(key) {
275
+ const rk = this.redisKey(key);
276
+ const [h, ttl] = await Promise.all([this.redis.hgetall(rk), this.redis.pttl(rk)]);
277
+ if (!h || !h.s) return null;
278
+ const num = (v) => v === void 0 ? null : Number(v);
279
+ return {
280
+ key,
281
+ state: h.s,
282
+ token: Number(h.t ?? 0),
283
+ owner: h.o ?? "",
284
+ attempts: Number(h.a ?? 0),
285
+ began: h.b === "1",
286
+ leaseExpiresAt: num(h.l),
287
+ createdAt: num(h.c),
288
+ updatedAt: num(h.u),
289
+ ...h.r !== void 0 ? { result: h.r } : {},
290
+ ...h.e ? { error: h.e } : {},
291
+ ttlMs: ttl
292
+ };
293
+ }
294
+ /**
295
+ * Settle an in_doubt key after checking the downstream system. `token` must be the one
296
+ * reported by InDoubtError / inspect(), so two reconcilers cannot both settle it.
297
+ */
298
+ async resolve(key, token, outcome) {
299
+ const payload = outcome.status === "done" ? this.serialize(outcome.result) : outcome.status === "failed" ? outcome.reason : "";
300
+ const r = String(await this.scripts.run(RESOLVE, this.redisKey(key), [token, outcome.status, payload, this.retentionMs]));
301
+ if (r !== "ok") throw new StaleClaimError(key, token, r);
302
+ }
303
+ /** Delete a record. An operator tool; normal code should not need it. */
304
+ async forget(key) {
305
+ return await this.redis.del(this.redisKey(key)) === 1;
306
+ }
307
+ /**
308
+ * Run `fn` at most once for `key`. A repeat call returns the stored result.
309
+ * Throws InProgressError, InDoubtError or FailedError instead of guessing.
310
+ */
311
+ async runOnce(key, fn, opts = {}) {
312
+ const leaseMs = opts.leaseMs ?? this.leaseMs;
313
+ const reconcile = opts.reconcile ?? this.defaultReconcile;
314
+ const waitUntil = Date.now() + (opts.waitTimeoutMs ?? leaseMs * 2);
315
+ let reconciled = false;
316
+ let delay = 25;
317
+ for (; ; ) {
318
+ const r = await this.reserve(key, { leaseMs });
319
+ if (r.status === "done") return r.result;
320
+ if (r.status === "failed") throw new FailedError(key, r.reason);
321
+ if (r.status === "busy") {
322
+ if (opts.onBusy !== "wait" || Date.now() >= waitUntil) throw new InProgressError(key, r.owner, r.retryAfterMs);
323
+ await sleep(Math.min(delay, r.retryAfterMs + 5, Math.max(1, waitUntil - Date.now())));
324
+ delay = Math.min(delay * 2, 500);
325
+ continue;
326
+ }
327
+ if (r.status === "in_doubt") {
328
+ if (!reconcile || reconciled) throw new InDoubtError(key, r.token, await this.inspect(key));
329
+ reconciled = true;
330
+ const record = await this.inspect(key);
331
+ const outcome = await reconcile({ key, idempotencyKey: this.idempotencyKey(key), token: r.token, record });
332
+ if (!outcome) throw new InDoubtError(key, r.token, record);
333
+ await this.resolve(key, r.token, outcome.status === "done" ? { status: "done", result: outcome.result } : outcome);
334
+ continue;
335
+ }
336
+ return this.execute(r.claim, fn, opts, leaseMs);
337
+ }
338
+ }
339
+ async execute(claim, fn, opts, leaseMs) {
340
+ const ac = new AbortController();
341
+ await claim.begin(leaseMs);
342
+ const every = opts.heartbeatMs ?? Math.floor(leaseMs / 3);
343
+ let timer;
344
+ if (every > 0) {
345
+ timer = setInterval(() => {
346
+ claim.heartbeat(leaseMs).catch((err) => {
347
+ if (err instanceof StaleClaimError) {
348
+ clearInterval(timer);
349
+ ac.abort(err);
350
+ }
351
+ });
352
+ }, every);
353
+ timer.unref?.();
354
+ }
355
+ let result;
356
+ try {
357
+ result = await fn({ key: claim.key, idempotencyKey: claim.idempotencyKey, token: claim.token, signal: ac.signal });
358
+ } catch (err) {
359
+ clearInterval(timer);
360
+ const decision = opts.onError ? opts.onError(err) : "release";
361
+ try {
362
+ if (decision === "fail") await claim.fail(err);
363
+ else if (decision === "in_doubt") await claim.markInDoubt(err);
364
+ else await claim.release(err);
365
+ } catch (settleErr) {
366
+ if (!(settleErr instanceof StaleClaimError)) throw settleErr;
367
+ }
368
+ throw err;
369
+ }
370
+ clearInterval(timer);
371
+ await claim.complete(result);
372
+ return result;
373
+ }
374
+ };
375
+ function sleep(ms) {
376
+ return new Promise((r) => setTimeout(r, ms));
377
+ }
378
+ function createClaimOnce(opts) {
379
+ return new ClaimOnce(opts);
380
+ }
381
+
382
+ export {
383
+ ClaimOnceError,
384
+ InProgressError,
385
+ InDoubtError,
386
+ FailedError,
387
+ StaleClaimError,
388
+ Claim,
389
+ ClaimOnce,
390
+ createClaimOnce
391
+ };
392
+ //# sourceMappingURL=chunk-FP5ZF55P.js.map