claim-once 0.0.0-stage → 0.1.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 +8 -0
- package/LICENSE +21 -0
- package/README.md +210 -2
- package/dist/chunk-FP5ZF55P.js +392 -0
- package/dist/chunk-FP5ZF55P.js.map +1 -0
- package/dist/chunk-TPZVW3TQ.js +436 -0
- package/dist/chunk-TPZVW3TQ.js.map +1 -0
- package/dist/index.cjs +452 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +248 -0
- package/dist/index.d.ts +248 -0
- package/dist/index.js +46 -0
- package/dist/index.js.map +1 -0
- package/dist/lab/cli.js +175 -0
- package/dist/lab/cli.js.map +1 -0
- package/dist/lab/index.cjs +553 -0
- package/dist/lab/index.cjs.map +1 -0
- package/dist/lab/index.d.cts +39 -0
- package/dist/lab/index.d.ts +39 -0
- package/dist/lab/index.js +143 -0
- package/dist/lab/index.js.map +1 -0
- package/dist/lab/worker.js +69 -0
- package/dist/lab/worker.js.map +1 -0
- package/package.json +103 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- First release: Redis Lua claim state machine (pending, done, failed, in_doubt, free) with leases, heartbeats and fencing tokens.
|
|
6
|
+
- `runOnce`, manual `reserve` / `begin` / `complete`, `inspect`, `resolve` and a `reconcile` hook.
|
|
7
|
+
- `onceProcessor` for BullMQ and `onceTool` for tool calls.
|
|
8
|
+
- `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,211 @@
|
|
|
1
|
-
#
|
|
1
|
+
# claim-once
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Run a side effect at most once per operation key, across every worker, with Redis. When it cannot know, it says so.**
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
`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.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install claim-once ioredis
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { Redis } from 'ioredis';
|
|
15
|
+
import { createClaimOnce } from 'claim-once';
|
|
16
|
+
|
|
17
|
+
const once = createClaimOnce({ redis: new Redis(process.env.REDIS_URL), namespace: 'billing' });
|
|
18
|
+
|
|
19
|
+
const receipt = await once.runOnce(`refund:${orderId}`, async ({ idempotencyKey }) => {
|
|
20
|
+
return stripe.refunds.create({ payment_intent: pi }, { idempotencyKey });
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Call it again with the same key, from any process, and you get the same `receipt` back without a second refund.
|
|
25
|
+
|
|
26
|
+
## What it guarantees, and what it does not
|
|
27
|
+
|
|
28
|
+
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.
|
|
29
|
+
|
|
30
|
+
- 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.
|
|
31
|
+
- 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.
|
|
32
|
+
- 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.
|
|
33
|
+
- A slow worker that was only stalled (not dead) can still finish with its token and settle the key as done.
|
|
34
|
+
|
|
35
|
+
The limits, plainly:
|
|
36
|
+
|
|
37
|
+
- **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.
|
|
38
|
+
- **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.
|
|
39
|
+
- **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.
|
|
40
|
+
- **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.
|
|
41
|
+
|
|
42
|
+
## How it works
|
|
43
|
+
|
|
44
|
+
Each key is one Redis hash with a state:
|
|
45
|
+
|
|
46
|
+
| State | Meaning | Next call gets |
|
|
47
|
+
|---|---|---|
|
|
48
|
+
| `pending` | Claimed, lease live | `InProgressError` (or waits, with `onBusy: 'wait'`) |
|
|
49
|
+
| `pending`, lease ran out, effect not begun | Owner died before doing anything | A takeover with a new token |
|
|
50
|
+
| `in_doubt` | Lease ran out after the effect began, or the effect threw an ambiguous error | `InDoubtError`, or your `reconcile` hook runs |
|
|
51
|
+
| `done` | Result stored | The stored result |
|
|
52
|
+
| `failed` | Marked failed for good | `FailedError` |
|
|
53
|
+
| `free` | Released after a failure that did not run the effect | A new claim |
|
|
54
|
+
|
|
55
|
+
`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:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const r = await once.reserve('payout:42');
|
|
59
|
+
if (r.status === 'reserved') {
|
|
60
|
+
const { claim } = r;
|
|
61
|
+
const quote = await loadQuote(); // safe: a crash here frees the key after the lease
|
|
62
|
+
await claim.begin(); // from here on, a lost lease means in_doubt
|
|
63
|
+
const res = await bank.payout(quote, { idempotencyKey: claim.idempotencyKey });
|
|
64
|
+
await claim.complete(res);
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Errors from your function
|
|
69
|
+
|
|
70
|
+
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:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
await once.runOnce(key, sendInvoice, {
|
|
74
|
+
onError: (err) => (isTimeout(err) ? 'in_doubt' : isBadRequest(err) ? 'fail' : 'release'),
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`maxAttempts` on the client turns the Nth release into `failed`.
|
|
79
|
+
|
|
80
|
+
## Reconciling in_doubt keys
|
|
81
|
+
|
|
82
|
+
Pass a `reconcile` hook and `runOnce` calls it once when it finds an in_doubt key:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
const once = createClaimOnce({
|
|
86
|
+
redis,
|
|
87
|
+
namespace: 'billing',
|
|
88
|
+
reconcile: async ({ idempotencyKey }) => {
|
|
89
|
+
const found = await stripe.refunds.list({ payment_intent: pi }); // or look up your own ledger
|
|
90
|
+
const hit = found.data.find((r) => r.metadata.key === idempotencyKey);
|
|
91
|
+
if (hit) return { status: 'done', result: hit };
|
|
92
|
+
return { status: 'not_happened' }; // only if you are sure; this allows a new attempt
|
|
93
|
+
// return undefined to leave it in_doubt for a human
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
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.
|
|
99
|
+
|
|
100
|
+
## BullMQ
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { Worker } from 'bullmq';
|
|
104
|
+
import { onceProcessor } from 'claim-once';
|
|
105
|
+
|
|
106
|
+
new Worker('billing', onceProcessor(once, async (job, { idempotencyKey }) => {
|
|
107
|
+
return chargeCustomer(job.data, { idempotencyKey });
|
|
108
|
+
}), { connection });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
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 })`.
|
|
112
|
+
|
|
113
|
+
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`.
|
|
114
|
+
|
|
115
|
+
## Tool calls
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { onceTool } from 'claim-once';
|
|
119
|
+
|
|
120
|
+
const sendEmail = onceTool(once, 'send_email', async (args: { to: string; body: string }) => {
|
|
121
|
+
return mailer.send(args);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
// Many tool frameworks call execute(args, { toolCallId }). The helper reads that id.
|
|
125
|
+
await sendEmail({ to, body }, { toolCallId: 'call_abc' });
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
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.
|
|
129
|
+
|
|
130
|
+
## The crash lab
|
|
131
|
+
|
|
132
|
+
`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.
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
npx claim-once-lab --redis redis://127.0.0.1:6379
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
It compares four strategies:
|
|
139
|
+
|
|
140
|
+
- **no guard**: just run it.
|
|
141
|
+
- **check, run, then set done**: `GET done`, run, `SET done`. The common first attempt.
|
|
142
|
+
- **SET NX first, then run**: mark the key before the effect, so a crash after marking forgets the work.
|
|
143
|
+
- **claim-once**: `reserve`, `begin`, run, `complete`.
|
|
144
|
+
|
|
145
|
+
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.
|
|
146
|
+
|
|
147
|
+
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):
|
|
148
|
+
|
|
149
|
+
| Scenario | Strategy | Ops | Effects run | Duplicates | Lost | in_doubt |
|
|
150
|
+
|---|---|---:|---:|---:|---:|---:|
|
|
151
|
+
| SIGKILL after the effect, before it is recorded | no guard | 20 | 40 | 20 | 0 | 0 |
|
|
152
|
+
| SIGKILL after the effect, before it is recorded | check, run, then set done | 20 | 40 | 20 | 0 | 0 |
|
|
153
|
+
| SIGKILL after the effect, before it is recorded | SET NX first, then run | 20 | 20 | 0 | 0 | 0 |
|
|
154
|
+
| SIGKILL after the effect, before it is recorded | claim-once | 20 | 20 | 0 | 0 | 20 |
|
|
155
|
+
| SIGKILL after the claim, before the effect | no guard | 20 | 20 | 0 | 0 | 0 |
|
|
156
|
+
| SIGKILL after the claim, before the effect | check, run, then set done | 20 | 20 | 0 | 0 | 0 |
|
|
157
|
+
| SIGKILL after the claim, before the effect | SET NX first, then run | 20 | 0 | 0 | 20 | 0 |
|
|
158
|
+
| SIGKILL after the claim, before the effect | claim-once | 20 | 20 | 0 | 0 | 0 |
|
|
159
|
+
| event loop blocked past the lease, job redelivered | no guard | 20 | 40 | 20 | 0 | 0 |
|
|
160
|
+
| event loop blocked past the lease, job redelivered | check, run, then set done | 20 | 40 | 20 | 0 | 0 |
|
|
161
|
+
| event loop blocked past the lease, job redelivered | SET NX first, then run | 20 | 20 | 0 | 0 | 0 |
|
|
162
|
+
| event loop blocked past the lease, job redelivered | claim-once | 20 | 20 | 0 | 0 | 0 |
|
|
163
|
+
| concurrent runners on the same keys | no guard | 20 | 160 | 140 | 0 | 0 |
|
|
164
|
+
| concurrent runners on the same keys | check, run, then set done | 20 | 160 | 140 | 0 | 0 |
|
|
165
|
+
| concurrent runners on the same keys | SET NX first, then run | 20 | 20 | 0 | 0 | 0 |
|
|
166
|
+
| concurrent runners on the same keys | claim-once | 20 | 20 | 0 | 0 | 0 |
|
|
167
|
+
|
|
168
|
+
160 worker processes were SIGKILLed in that run.
|
|
169
|
+
|
|
170
|
+
How to read it:
|
|
171
|
+
|
|
172
|
+
- 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.
|
|
173
|
+
- 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.
|
|
174
|
+
- **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.
|
|
175
|
+
- **Concurrent**: one claim per key won, the rest got `InProgressError`.
|
|
176
|
+
|
|
177
|
+
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'`.
|
|
178
|
+
|
|
179
|
+
## API
|
|
180
|
+
|
|
181
|
+
`createClaimOnce(options)` returns a `ClaimOnce`.
|
|
182
|
+
|
|
183
|
+
| Option | Default | |
|
|
184
|
+
|---|---|---|
|
|
185
|
+
| `redis` | required | An ioredis client or Cluster |
|
|
186
|
+
| `namespace` | `claim-once` | Key prefix |
|
|
187
|
+
| `leaseMs` | `30000` | How long a claim stays exclusive without a heartbeat |
|
|
188
|
+
| `retentionMs` | 7 days | How long records, including results, are kept |
|
|
189
|
+
| `maxAttempts` | `0` (no limit) | Releases after which the key becomes failed |
|
|
190
|
+
| `owner` | host, pid, random | Written to records, for debugging |
|
|
191
|
+
| `serialize` / `deserialize` | JSON | How results are stored |
|
|
192
|
+
| `reconcile` | none | Default hook for in_doubt keys |
|
|
193
|
+
|
|
194
|
+
Methods:
|
|
195
|
+
|
|
196
|
+
- `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.
|
|
197
|
+
- `reserve(key)` returns `reserved` (with a `Claim`), `done`, `busy`, `in_doubt` or `failed`.
|
|
198
|
+
- `Claim`: `begin()`, `heartbeat()`, `complete(result)`, `release(error?)`, `fail(error)`, `markInDoubt(error?)`. Each throws `StaleClaimError` if the token is no longer current.
|
|
199
|
+
- `inspect(key)`, `resolve(key, token, outcome)`, `forget(key)`.
|
|
200
|
+
|
|
201
|
+
Errors: `InProgressError`, `InDoubtError`, `FailedError`, `StaleClaimError`, all extending `ClaimOnceError` and carrying `key`.
|
|
202
|
+
|
|
203
|
+
Results must survive your `serialize` function. With the default JSON, a `Date` comes back as a string.
|
|
204
|
+
|
|
205
|
+
## Requirements
|
|
206
|
+
|
|
207
|
+
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.
|
|
208
|
+
|
|
209
|
+
## License
|
|
210
|
+
|
|
211
|
+
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
|