@gkoos/caracal 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.
Files changed (49) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +311 -0
  4. package/dist/chunk-5CXDW7W6.js +202 -0
  5. package/dist/chunk-5CXDW7W6.js.map +1 -0
  6. package/dist/circuit-breaker-BSkcV0W_.d.ts +296 -0
  7. package/dist/fetch.d.ts +58 -0
  8. package/dist/fetch.js +117 -0
  9. package/dist/fetch.js.map +1 -0
  10. package/dist/index.d.ts +19 -0
  11. package/dist/index.js +1065 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/postgres.d.ts +28 -0
  14. package/dist/postgres.js +56 -0
  15. package/dist/postgres.js.map +1 -0
  16. package/dist/redis.d.ts +59 -0
  17. package/dist/redis.js +549 -0
  18. package/dist/redis.js.map +1 -0
  19. package/dist/retry-BFP_k3Hg.d.ts +26 -0
  20. package/dist/testing/index.d.ts +45 -0
  21. package/dist/testing/index.js +101 -0
  22. package/dist/testing/index.js.map +1 -0
  23. package/dist/types-Tf9T76C7.d.ts +187 -0
  24. package/package.json +127 -0
  25. package/src/adapters/fetch/adapter.ts +122 -0
  26. package/src/adapters/fetch/index.ts +15 -0
  27. package/src/adapters/fetch/retry-after.ts +111 -0
  28. package/src/adapters/postgres/adapter.ts +102 -0
  29. package/src/adapters/postgres/index.ts +7 -0
  30. package/src/coordination/redis/bulkhead.ts +61 -0
  31. package/src/coordination/redis/circuit-breaker.ts +270 -0
  32. package/src/coordination/redis/client.ts +78 -0
  33. package/src/coordination/redis/eval-script.ts +71 -0
  34. package/src/coordination/redis/keys.ts +32 -0
  35. package/src/coordination/redis/leases.ts +44 -0
  36. package/src/coordination/redis/scripts.ts +314 -0
  37. package/src/core/bulkhead.ts +336 -0
  38. package/src/core/circuit-breaker.ts +1066 -0
  39. package/src/core/index.ts +36 -0
  40. package/src/core/operation.ts +174 -0
  41. package/src/core/retry.ts +204 -0
  42. package/src/core/runtime.ts +123 -0
  43. package/src/core/scope-state-cache.ts +50 -0
  44. package/src/core/timeout.ts +73 -0
  45. package/src/core/types.ts +230 -0
  46. package/src/fetch.ts +17 -0
  47. package/src/index.ts +49 -0
  48. package/src/postgres.ts +9 -0
  49. package/src/redis.ts +8 -0
package/dist/redis.js ADDED
@@ -0,0 +1,549 @@
1
+ import { Redis, Cluster } from 'ioredis';
2
+ import { createHash } from 'crypto';
3
+
4
+ // src/coordination/redis/client.ts
5
+ var CoordinatorUnavailableError = class extends Error {
6
+ coordination = "distributed";
7
+ constructor(cause) {
8
+ super("Redis coordination unavailable; command outcome may be unknown", {
9
+ cause
10
+ });
11
+ this.name = "CoordinatorUnavailableError";
12
+ }
13
+ };
14
+ function attachErrorSink(emitter) {
15
+ emitter.on("error", () => {
16
+ });
17
+ }
18
+ function createCoordinationClient(url, commandTimeout = 1e3) {
19
+ if (!Number.isSafeInteger(commandTimeout) || commandTimeout < 1)
20
+ throw new RangeError("commandTimeout must be a positive integer");
21
+ const client = new Redis(url, {
22
+ lazyConnect: true,
23
+ enableOfflineQueue: false,
24
+ maxRetriesPerRequest: 0,
25
+ autoResendUnfulfilledCommands: false,
26
+ commandTimeout,
27
+ connectTimeout: commandTimeout,
28
+ retryStrategy: (attempt) => Math.min(attempt * 50, 1e3)
29
+ });
30
+ attachErrorSink(client);
31
+ return client;
32
+ }
33
+ function createCoordinationClusterClient(nodes, commandTimeout = 1e3) {
34
+ if (!Number.isSafeInteger(commandTimeout) || commandTimeout < 1)
35
+ throw new RangeError("commandTimeout must be a positive integer");
36
+ if (!Array.isArray(nodes) || nodes.length === 0)
37
+ throw new RangeError("nodes must be a non-empty array of { host, port }");
38
+ const cluster = new Cluster([...nodes], {
39
+ lazyConnect: true,
40
+ enableOfflineQueue: false,
41
+ clusterRetryStrategy: (attempt) => Math.min(attempt * 50, 1e3),
42
+ redisOptions: {
43
+ commandTimeout,
44
+ connectTimeout: commandTimeout,
45
+ maxRetriesPerRequest: 0,
46
+ autoResendUnfulfilledCommands: false
47
+ }
48
+ });
49
+ attachErrorSink(cluster);
50
+ return cluster;
51
+ }
52
+ var scriptHashes = /* @__PURE__ */ new Map();
53
+ function scriptSha(script) {
54
+ const cached = scriptHashes.get(script);
55
+ if (cached !== void 0) return cached;
56
+ const sha = createHash("sha1").update(script).digest("hex");
57
+ scriptHashes.set(script, sha);
58
+ return sha;
59
+ }
60
+ function errorMessage(error) {
61
+ if (typeof error === "string") return error;
62
+ if (error instanceof Error) return error.message;
63
+ return "";
64
+ }
65
+ async function evalScript(client, script, numberOfKeys, ...args) {
66
+ const evalsha = client.evalsha;
67
+ if (typeof evalsha !== "function") {
68
+ return client.eval(script, numberOfKeys, ...args);
69
+ }
70
+ try {
71
+ return await evalsha.call(client, scriptSha(script), numberOfKeys, ...args);
72
+ } catch (error) {
73
+ if (!errorMessage(error).includes("NOSCRIPT")) throw error;
74
+ return client.eval(script, numberOfKeys, ...args);
75
+ }
76
+ }
77
+ function coordinationKey(namespace, policy, operation, scope, suffix = "leases") {
78
+ for (const value of [namespace, policy, operation, scope, suffix]) {
79
+ if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > 1024)
80
+ throw new TypeError(
81
+ "Coordination identities must be nonempty strings of at most 1024 UTF-8 bytes"
82
+ );
83
+ }
84
+ const identity = createHash("sha256").update(JSON.stringify([namespace, policy, operation, scope])).digest("hex");
85
+ return `caracal:v1:{${identity}}:${suffix}`;
86
+ }
87
+
88
+ // src/coordination/redis/scripts.ts
89
+ var leaseV1 = `
90
+ local action = ARGV[1]
91
+ local token = ARGV[2]
92
+ local ttl = tonumber(ARGV[3])
93
+ local limit = tonumber(ARGV[4])
94
+ local time = redis.call('TIME')
95
+ local now = time[1] * 1000 + math.floor(time[2] / 1000)
96
+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
97
+ local existing = redis.call('ZSCORE', KEYS[1], token)
98
+ if action == 'release' then
99
+ return redis.call('ZREM', KEYS[1], token)
100
+ end
101
+ if action == 'renew' and not existing then return 0 end
102
+ if action == 'acquire' and existing then return 1 end
103
+ if action == 'acquire' and redis.call('ZCARD', KEYS[1]) >= limit then return 0 end
104
+ redis.call('ZADD', KEYS[1], now + ttl, token)
105
+ local latest = redis.call('ZREVRANGE', KEYS[1], 0, 0, 'WITHSCORES')
106
+ redis.call('PEXPIREAT', KEYS[1], math.ceil(tonumber(latest[2])))
107
+ return 1
108
+ `;
109
+ var bulkheadLeaseV1 = `local function transition()
110
+ ${leaseV1}
111
+ end
112
+ local allowed = transition()
113
+ return {allowed, redis.call('ZCARD', KEYS[1])}`;
114
+ var breakerObserveV1 = `
115
+ local outcome = ARGV[1]
116
+ local expectGen = tonumber(ARGV[2])
117
+ local windowTtl = tonumber(ARGV[3])
118
+ local minTP = tonumber(ARGV[4])
119
+ local threshNum = tonumber(ARGV[5])
120
+ local windowSize = tonumber(ARGV[6])
121
+ local openMs = tonumber(ARGV[7])
122
+ local uuid = ARGV[8]
123
+ local t = redis.call('TIME')
124
+ local now = t[1] * 1000 + math.floor(t[2] / 1000)
125
+ local f = redis.call('HMGET', KEYS[1], 'state', 'generation')
126
+ local state = f[1] or 'closed'
127
+ local gen = tonumber(f[2]) or 0
128
+ if state ~= 'closed' then
129
+ local sc = (state == 'open' and 1) or (state == 'half-open' and 2) or 0
130
+ return {0, sc, gen, 0, 0}
131
+ end
132
+ if redis.call('EXISTS', KEYS[1]) == 0 then
133
+ -- No live state hash: a scope we have never seen, or a hash that was lost
134
+ -- while its window survived.
135
+ if expectGen ~= 0 then
136
+ -- The caller holds a generation this key cannot confirm.
137
+ return {0, 0, 0, 0, 0}
138
+ end
139
+ if redis.call('EXISTS', KEYS[2]) == 1 then
140
+ -- Members from a superseded epoch are still here. Mint an epoch that has
141
+ -- never been used for this key (derived from the observation's own uuid, so
142
+ -- no clock is involved) instead of restarting at a value those members
143
+ -- would match.
144
+ --
145
+ -- Bounded to 11 hex digits (44 bits, <= 14 decimal digits) so the value
146
+ -- prints exactly with stock Lua number formatting: the epoch is read back
147
+ -- from the hash as a decimal string by both this script and the client, and
148
+ -- a larger value could be written in scientific notation and break the
149
+ -- round-trip.
150
+ gen = tonumber(string.sub(redis.sha1hex(uuid), 1, 11), 16)
151
+ if not gen or gen == 0 then gen = 1 end
152
+ else
153
+ gen = 0
154
+ end
155
+ redis.call('HSET', KEYS[1], 'state', 'closed', 'generation', gen,
156
+ 'openedAt', 0, 'probeCount', 0, 'probeSuccesses', 0)
157
+ elseif gen ~= expectGen then
158
+ return {0, 0, gen, 0, 0}
159
+ end
160
+ redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now - windowTtl)
161
+ local member = tostring(gen) .. ':' .. uuid .. ':' .. outcome
162
+ redis.call('ZADD', KEYS[2], 'NX', now, member)
163
+ local cnt = redis.call('ZCARD', KEYS[2])
164
+ if cnt > windowSize then
165
+ redis.call('ZREMRANGEBYRANK', KEYS[2], 0, cnt - windowSize - 1)
166
+ end
167
+ redis.call('PEXPIREAT', KEYS[2], now + windowTtl)
168
+ local all = redis.call('ZRANGE', KEYS[2], 0, -1)
169
+ local prefix = tostring(gen) .. ':'
170
+ local wTotal = 0
171
+ local wFail = 0
172
+ for _, m in ipairs(all) do
173
+ if string.sub(m, 1, #prefix) == prefix then
174
+ wTotal = wTotal + 1
175
+ if string.sub(m, -8) == ':failure' then wFail = wFail + 1 end
176
+ end
177
+ end
178
+ if wTotal >= minTP and wFail * 1000 >= threshNum * wTotal then
179
+ gen = gen + 1
180
+ redis.call('HSET', KEYS[1], 'state', 'open', 'generation', gen,
181
+ 'openedAt', now, 'probeCount', 0, 'probeSuccesses', 0)
182
+ -- OPEN state must never expire: a missing key is treated as closed,
183
+ -- which would silently admit unrestricted traffic and reset the generation.
184
+ redis.call('PERSIST', KEYS[1])
185
+ return {2, 1, gen, wTotal, wFail}
186
+ end
187
+ if redis.call('EXISTS', KEYS[1]) == 1 then
188
+ -- Still CLOSED. The cleanup TTL must not expire the state before the window
189
+ -- it governs, otherwise retained members would survive their epoch.
190
+ redis.call('PEXPIRE', KEYS[1], math.max(openMs * 2, windowTtl))
191
+ end
192
+ return {1, 0, gen, wTotal, wFail}
193
+ `;
194
+ var breakerAdmitProbeV1 = `
195
+ local probeToken = ARGV[1]
196
+ local openMs = tonumber(ARGV[2])
197
+ local maxProbes = tonumber(ARGV[3])
198
+ local probeLeaseTtl = tonumber(ARGV[4])
199
+ local t = redis.call('TIME')
200
+ local now = t[1] * 1000 + math.floor(t[2] / 1000)
201
+ local f = redis.call('HMGET', KEYS[1], 'state', 'generation', 'openedAt',
202
+ 'probeCount', 'probeSuccesses')
203
+ local state = f[1] or 'closed'
204
+ local gen = tonumber(f[2]) or 0
205
+ local openedAt = tonumber(f[3]) or 0
206
+ local transitioned = 0
207
+ if state == 'closed' then
208
+ return {0, 0, gen, 0, 0}
209
+ end
210
+ if state == 'open' then
211
+ if now - openedAt < openMs then
212
+ return {0, 1, gen, 0, 0}
213
+ end
214
+ state = 'half-open'
215
+ transitioned = 1
216
+ redis.call('HSET', KEYS[1], 'state', 'half-open', 'probeSuccesses', 0, 'probeCount', 0)
217
+ -- OPEN/HALF_OPEN must never expire; PERSIST removes any prior cleanup TTL.
218
+ redis.call('PERSIST', KEYS[1])
219
+ -- Tokens from the superseded recovery window must not consume slots in this
220
+ -- one; their settle is dropped by the generation check anyway.
221
+ redis.call('DEL', KEYS[2])
222
+ end
223
+ redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now)
224
+ local activeProbes = redis.call('ZCARD', KEYS[2])
225
+ if activeProbes >= maxProbes then
226
+ return {0, 2, gen, activeProbes, transitioned}
227
+ end
228
+ redis.call('ZADD', KEYS[2], 'NX', now + probeLeaseTtl, probeToken)
229
+ activeProbes = activeProbes + 1
230
+ redis.call('HSET', KEYS[1], 'probeCount', activeProbes)
231
+ -- State hash must not expire while recovery probes are in flight.
232
+ redis.call('PERSIST', KEYS[1])
233
+ -- Probes sorted set expires naturally once the last lease elapses.
234
+ redis.call('PEXPIREAT', KEYS[2], now + probeLeaseTtl + 1000)
235
+ return {1, 2, gen, activeProbes, transitioned}
236
+ `;
237
+ var breakerSettleProbeV1 = `
238
+ local probeToken = ARGV[1]
239
+ local outcome = ARGV[2]
240
+ local expectGen = tonumber(ARGV[3])
241
+ local halfOpenSucc = tonumber(ARGV[4])
242
+ local openMs = tonumber(ARGV[5])
243
+ local windowTtl = tonumber(ARGV[6])
244
+ local t = redis.call('TIME')
245
+ local now = t[1] * 1000 + math.floor(t[2] / 1000)
246
+ local f = redis.call('HMGET', KEYS[1], 'state', 'generation', 'probeSuccesses', 'probeCount')
247
+ local state = f[1] or 'closed'
248
+ local gen = tonumber(f[2]) or 0
249
+ local probeSucc = tonumber(f[3]) or 0
250
+ local probeCnt = tonumber(f[4]) or 0
251
+ local sc = (state == 'open' and 1) or (state == 'half-open' and 2) or 0
252
+ local deadline = redis.call('ZSCORE', KEYS[2], probeToken)
253
+ if not deadline then
254
+ -- Never admitted, already settled, or dropped with its recovery window.
255
+ return {0, sc, gen}
256
+ end
257
+ redis.call('ZREM', KEYS[2], probeToken)
258
+ if tonumber(deadline) <= now then
259
+ -- The lease elapsed while the probe was still running: its slot was
260
+ -- recoverable, so the result cannot be counted. Release the slot it still
261
+ -- occupied so the probe count keeps matching the token set.
262
+ probeCnt = math.max(0, probeCnt - 1)
263
+ redis.call('HSET', KEYS[1], 'probeCount', probeCnt)
264
+ return {0, sc, gen}
265
+ end
266
+ if state ~= 'half-open' or gen ~= expectGen then
267
+ return {0, sc, gen}
268
+ end
269
+ probeCnt = math.max(0, probeCnt - 1)
270
+ if outcome == 'failure' then
271
+ gen = gen + 1
272
+ redis.call('HSET', KEYS[1], 'state', 'open', 'generation', gen,
273
+ 'openedAt', now, 'probeCount', 0, 'probeSuccesses', 0)
274
+ -- Re-opened: OPEN must not expire (see breakerObserveV1 TTL policy).
275
+ redis.call('PERSIST', KEYS[1])
276
+ -- In-flight probes belong to the dead generation; free their slots so the
277
+ -- next recovery window starts with full capacity.
278
+ redis.call('DEL', KEYS[2])
279
+ return {2, 1, gen}
280
+ end
281
+ probeSucc = probeSucc + 1
282
+ if probeSucc >= halfOpenSucc then
283
+ gen = gen + 1
284
+ redis.call('HSET', KEYS[1], 'state', 'closed', 'generation', gen,
285
+ 'probeCount', 0, 'probeSuccesses', 0)
286
+ -- Newly CLOSED: expire for cleanup, but never before the window it governs.
287
+ redis.call('PEXPIRE', KEYS[1], math.max(openMs * 2, windowTtl))
288
+ redis.call('DEL', KEYS[2])
289
+ return {2, 0, gen}
290
+ end
291
+ redis.call('HSET', KEYS[1], 'probeSuccesses', probeSucc, 'probeCount', probeCnt)
292
+ -- Still HALF_OPEN: must not expire while recovery is in progress.
293
+ redis.call('PERSIST', KEYS[1])
294
+ return {1, 2, gen}
295
+ `;
296
+
297
+ // src/coordination/redis/bulkhead.ts
298
+ function redisCoordinator(client, options) {
299
+ const namespace = options.namespace;
300
+ coordinationKey(namespace, "bulkhead", "validate", "validate");
301
+ const coordinator = {
302
+ async command(identity, action, token, leaseMs, limit) {
303
+ if (!["acquire", "renew", "release"].includes(action) || typeof token !== "string" || !token || token.length > 256)
304
+ throw new TypeError("Invalid bulkhead lease action or token");
305
+ if (![leaseMs, limit].every(
306
+ (value) => Number.isSafeInteger(value) && value > 0
307
+ ) || leaseMs > 864e5)
308
+ throw new RangeError("Invalid bulkhead lease duration or limit");
309
+ const key = coordinationKey(
310
+ namespace,
311
+ `bulkhead:${identity.name}`,
312
+ identity.operation,
313
+ identity.scope
314
+ );
315
+ try {
316
+ const result = await evalScript(
317
+ client,
318
+ bulkheadLeaseV1,
319
+ 1,
320
+ key,
321
+ action,
322
+ token,
323
+ leaseMs,
324
+ limit
325
+ );
326
+ if (!Array.isArray(result) || result.length !== 2 || ![0, 1].includes(result[0]) || !Number.isSafeInteger(result[1]) || result[1] < 0)
327
+ throw new Error("Invalid bulkhead reply");
328
+ return { allowed: result[0] === 1, occupancy: result[1] };
329
+ } catch (error) {
330
+ throw new CoordinatorUnavailableError(error);
331
+ }
332
+ }
333
+ };
334
+ return Object.freeze(coordinator);
335
+ }
336
+
337
+ // src/coordination/redis/circuit-breaker.ts
338
+ function breakerKeys(namespace, identity) {
339
+ const policy = `breaker:${identity.name}`;
340
+ const hash = coordinationKey(
341
+ namespace,
342
+ policy,
343
+ identity.operation,
344
+ identity.scope,
345
+ "breaker"
346
+ );
347
+ const obs = coordinationKey(
348
+ namespace,
349
+ policy,
350
+ identity.operation,
351
+ identity.scope,
352
+ "observations"
353
+ );
354
+ const prob = coordinationKey(
355
+ namespace,
356
+ policy,
357
+ identity.operation,
358
+ identity.scope,
359
+ "probes"
360
+ );
361
+ return [hash, obs, prob];
362
+ }
363
+ function assertArray(reply, minLen, label) {
364
+ if (!Array.isArray(reply) || reply.length < minLen || reply.some((v) => typeof v !== "number" || !Number.isSafeInteger(v))) {
365
+ throw new Error(
366
+ `Invalid ${label} reply from Redis: ${JSON.stringify(reply)}`
367
+ );
368
+ }
369
+ return reply;
370
+ }
371
+ var STATE_CODES = ["closed", "open", "half-open"];
372
+ function decodeState(code) {
373
+ const s = STATE_CODES[code];
374
+ if (!s) throw new Error(`Unknown breaker state code: ${code}`);
375
+ return s;
376
+ }
377
+ function redisCircuitBreakerCoordinator(client, options) {
378
+ const { namespace } = options;
379
+ coordinationKey(
380
+ namespace,
381
+ "breaker:validate",
382
+ "validate",
383
+ "validate",
384
+ "breaker"
385
+ );
386
+ const coordinator = {
387
+ async readState(identity) {
388
+ const [hashKey] = breakerKeys(namespace, identity);
389
+ try {
390
+ const fields = await client.hmget(hashKey, "state", "generation");
391
+ const rawState = fields[0];
392
+ if (!rawState) return null;
393
+ const state = rawState;
394
+ if (!STATE_CODES.includes(state))
395
+ throw new Error(`Unknown breaker state: ${rawState}`);
396
+ const generation = parseInt(fields[1] ?? "0", 10);
397
+ return { state, generation };
398
+ } catch (error) {
399
+ throw new CoordinatorUnavailableError(error);
400
+ }
401
+ },
402
+ async observe(identity, params) {
403
+ const [hashKey, obsKey] = breakerKeys(namespace, identity);
404
+ const {
405
+ generation,
406
+ outcome,
407
+ uuid,
408
+ windowTtlMs,
409
+ minimumThroughput,
410
+ failureThresholdNumerator,
411
+ windowSize,
412
+ openMs
413
+ } = params;
414
+ try {
415
+ const reply = await evalScript(
416
+ client,
417
+ breakerObserveV1,
418
+ 2,
419
+ hashKey,
420
+ obsKey,
421
+ outcome,
422
+ generation,
423
+ windowTtlMs,
424
+ minimumThroughput,
425
+ failureThresholdNumerator,
426
+ windowSize,
427
+ openMs,
428
+ uuid
429
+ );
430
+ const r = assertArray(reply, 5, "breakerObserveV1");
431
+ const [status, , newGen, windowTotal, windowFailures] = r;
432
+ if (status === 0) {
433
+ return {
434
+ type: "stale",
435
+ currentGeneration: newGen
436
+ };
437
+ }
438
+ if (status === 2) {
439
+ return {
440
+ type: "opened",
441
+ newGeneration: newGen,
442
+ windowTotal,
443
+ windowFailures
444
+ };
445
+ }
446
+ return {
447
+ type: "observed",
448
+ generation: newGen,
449
+ windowTotal,
450
+ windowFailures
451
+ };
452
+ } catch (error) {
453
+ throw new CoordinatorUnavailableError(error);
454
+ }
455
+ },
456
+ async admitProbe(identity, params) {
457
+ const [hashKey, , probeKey] = breakerKeys(namespace, identity);
458
+ const { probeToken, openMs, halfOpenProbes, probeLeaseTtlMs } = params;
459
+ try {
460
+ const reply = await evalScript(
461
+ client,
462
+ breakerAdmitProbeV1,
463
+ 2,
464
+ hashKey,
465
+ probeKey,
466
+ probeToken,
467
+ openMs,
468
+ halfOpenProbes,
469
+ probeLeaseTtlMs
470
+ );
471
+ const r = assertArray(reply, 5, "breakerAdmitProbeV1");
472
+ const [status, stateCode, gen, probeCount, transitioned] = r;
473
+ if (status === 0) {
474
+ const reason = stateCode === 0 ? "closed" : stateCode === 1 ? "open" : "probe-limit";
475
+ return {
476
+ type: "rejected",
477
+ reason,
478
+ generation: gen
479
+ };
480
+ }
481
+ return {
482
+ type: "admitted",
483
+ generation: gen,
484
+ probeCount,
485
+ stateChanged: transitioned === 1
486
+ };
487
+ } catch (error) {
488
+ throw new CoordinatorUnavailableError(error);
489
+ }
490
+ },
491
+ async settleProbe(identity, params) {
492
+ const [hashKey, , probeKey] = breakerKeys(namespace, identity);
493
+ const {
494
+ probeToken,
495
+ outcome,
496
+ generation,
497
+ halfOpenSuccesses,
498
+ openMs,
499
+ windowTtlMs
500
+ } = params;
501
+ try {
502
+ const reply = await evalScript(
503
+ client,
504
+ breakerSettleProbeV1,
505
+ 2,
506
+ hashKey,
507
+ probeKey,
508
+ probeToken,
509
+ outcome,
510
+ generation,
511
+ halfOpenSuccesses,
512
+ openMs,
513
+ // Floor for the CLOSED cleanup TTL; older callers that do not pass it
514
+ // keep the historical openMs x 2 behaviour.
515
+ windowTtlMs ?? openMs * 2
516
+ );
517
+ const r = assertArray(reply, 3, "breakerSettleProbeV1");
518
+ const [status, stateCode, newGen] = r;
519
+ if (status === 0) {
520
+ return {
521
+ type: "stale",
522
+ generation: newGen
523
+ };
524
+ }
525
+ const state = decodeState(stateCode);
526
+ if (status === 2) {
527
+ return {
528
+ type: "transitioned",
529
+ newState: state,
530
+ newGeneration: newGen,
531
+ previousState: "half-open"
532
+ };
533
+ }
534
+ return {
535
+ type: "settled",
536
+ state,
537
+ generation: newGen
538
+ };
539
+ } catch (error) {
540
+ throw new CoordinatorUnavailableError(error);
541
+ }
542
+ }
543
+ };
544
+ return Object.freeze(coordinator);
545
+ }
546
+
547
+ export { CoordinatorUnavailableError, createCoordinationClient, createCoordinationClusterClient, redisCircuitBreakerCoordinator, redisCoordinator };
548
+ //# sourceMappingURL=redis.js.map
549
+ //# sourceMappingURL=redis.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/coordination/redis/client.ts","../src/coordination/redis/eval-script.ts","../src/coordination/redis/keys.ts","../src/coordination/redis/scripts.ts","../src/coordination/redis/bulkhead.ts","../src/coordination/redis/circuit-breaker.ts"],"names":["createHash"],"mappings":";;;;AAEO,IAAM,2BA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,EAAM,SAAA;AAAA,UACN,KAAA;AAAA,UACA,UAAA,EAAY;AAAA,SACd;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,MAAM,IAAI,4BAA4B,KAAK,CAAA;AAAA,MAC7C;AAAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,MAAA,CAAO,OAAO,WAAW,CAAA;AAClC","file":"redis.js","sourcesContent":["import { Cluster, Redis } from \"ioredis\"\n\nexport class CoordinatorUnavailableError extends Error {\n readonly coordination = \"distributed\"\n constructor(cause: unknown) {\n super(\"Redis coordination unavailable; command outcome may be unknown\", {\n cause,\n })\n this.name = \"CoordinatorUnavailableError\"\n }\n}\n\nfunction attachErrorSink(emitter: {\n on(event: \"error\", listener: () => void): void\n}): void {\n emitter.on(\"error\", () => {\n /* Commands surface errors; never crash on an unhandled EventEmitter error. */\n })\n}\n\n/** Standalone Redis client. Caller owns it and must disconnect at shutdown. */\nexport function createCoordinationClient(\n url: string,\n commandTimeout = 1000,\n): Redis {\n if (!Number.isSafeInteger(commandTimeout) || commandTimeout < 1)\n throw new RangeError(\"commandTimeout must be a positive integer\")\n const client = new Redis(url, {\n lazyConnect: true,\n enableOfflineQueue: false,\n maxRetriesPerRequest: 0,\n autoResendUnfulfilledCommands: false,\n commandTimeout,\n connectTimeout: commandTimeout,\n retryStrategy: (attempt) => Math.min(attempt * 50, 1000),\n })\n attachErrorSink(client)\n return client\n}\n\nexport interface ClusterNode {\n readonly host: string\n readonly port: number\n}\n\n/**\n * Redis Cluster client. Caller owns it and must disconnect at shutdown.\n *\n * All coordination keys use a hash-tag so that every key for a given\n * policy+operation+scope lands on the same cluster slot. Multi-key Lua\n * scripts (circuit breaker) are therefore cluster-safe without cross-slot\n * concerns.\n *\n * Call `connect()` before use and `disconnect()` at shutdown, matching the\n * standalone client contract.\n */\nexport function createCoordinationClusterClient(\n nodes: ReadonlyArray<ClusterNode>,\n commandTimeout = 1000,\n): Cluster {\n if (!Number.isSafeInteger(commandTimeout) || commandTimeout < 1)\n throw new RangeError(\"commandTimeout must be a positive integer\")\n if (!Array.isArray(nodes) || nodes.length === 0)\n throw new RangeError(\"nodes must be a non-empty array of { host, port }\")\n const cluster = new Cluster([...nodes], {\n lazyConnect: true,\n enableOfflineQueue: false,\n clusterRetryStrategy: (attempt) => Math.min(attempt * 50, 1000),\n redisOptions: {\n commandTimeout,\n connectTimeout: commandTimeout,\n maxRetriesPerRequest: 0,\n autoResendUnfulfilledCommands: false,\n },\n })\n attachErrorSink(cluster)\n return cluster\n}\n","import { createHash } from \"node:crypto\"\n\n/**\n * Minimal Lua-script capability required by the Redis coordinators.\n *\n * `eval` is always required. `evalsha` is optional so structural test doubles\n * and clients that only expose `eval` keep working; when it is missing the\n * script body is sent with `eval`.\n */\nexport interface ScriptClient {\n eval(\n script: string,\n numberOfKeys: number,\n ...args: (string | number)[]\n ): Promise<unknown>\n evalsha?(\n sha: string,\n numberOfKeys: number,\n ...args: (string | number)[]\n ): Promise<unknown>\n}\n\nconst scriptHashes = new Map<string, string>()\n\n/** SHA1 of a script body. Redis keys its script cache by exactly this value. */\nexport function scriptSha(script: string): string {\n const cached = scriptHashes.get(script)\n if (cached !== undefined) return cached\n const sha = createHash(\"sha1\").update(script).digest(\"hex\")\n scriptHashes.set(script, sha)\n return sha\n}\n\nfunction errorMessage(error: unknown): string {\n if (typeof error === \"string\") return error\n if (error instanceof Error) return error.message\n return \"\"\n}\n\n/**\n * Executes a Lua script, sending the body only when it has to.\n *\n * The script cache is keyed by SHA1, so the steady state is `EVALSHA` - a\n * 40-byte hash instead of kilobytes of Lua on every call. The full body goes\n * out with `EVAL` only when the client cannot send `EVALSHA`, or when the\n * server answers `NOSCRIPT`: the script cache lost the script to a restart, a\n * `SCRIPT FLUSH`, or (Redis 7.4 and later) LRU eviction under memory pressure.\n *\n * Retrying through `EVAL` is safe because Redis rejects an unknown SHA1 before\n * executing anything, so the failed command is known not to have run. This is\n * deliberately narrower than the coordinator's command-timeout rule, where the\n * outcome is unknown and a replay is never allowed. A timeout error is not a\n * `NOSCRIPT` error and propagates unchanged.\n */\nexport async function evalScript(\n client: ScriptClient,\n script: string,\n numberOfKeys: number,\n ...args: (string | number)[]\n): Promise<unknown> {\n const evalsha = client.evalsha\n if (typeof evalsha !== \"function\") {\n return client.eval(script, numberOfKeys, ...args)\n }\n try {\n return await evalsha.call(client, scriptSha(script), numberOfKeys, ...args)\n } catch (error) {\n if (!errorMessage(error).includes(\"NOSCRIPT\")) throw error\n return client.eval(script, numberOfKeys, ...args)\n }\n}\n","import { createHash } from \"node:crypto\"\n\n/**\n * Build a namespaced Redis key for a policy-scoped coordination slot.\n *\n * The SHA-256 hash of `[namespace, policy, operation, scope]` forms the\n * stable identity; `suffix` distinguishes multiple keys that share the\n * same identity (e.g. `:leases`, `:breaker`, `:observations`, `:probes`).\n * Default suffix is `\"leases\"` for backward compatibility with the bulkhead.\n */\nexport function coordinationKey(\n namespace: string,\n policy: string,\n operation: string,\n scope: string,\n suffix = \"leases\",\n): string {\n for (const value of [namespace, policy, operation, scope, suffix]) {\n if (\n typeof value !== \"string\" ||\n !value.trim() ||\n Buffer.byteLength(value) > 1024\n )\n throw new TypeError(\n \"Coordination identities must be nonempty strings of at most 1024 UTF-8 bytes\",\n )\n }\n const identity = createHash(\"sha256\")\n .update(JSON.stringify([namespace, policy, operation, scope]))\n .digest(\"hex\")\n return `caracal:v1:{${identity}}:${suffix}`\n}\n","// ---------------------------------------------------------------------------\n// Versioned atomic operations, internal to the Redis policy capabilities.\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Bulkhead scripts\n// ---------------------------------------------------------------------------\n\nexport const leaseV1 = `\nlocal action = ARGV[1]\nlocal token = ARGV[2]\nlocal ttl = tonumber(ARGV[3])\nlocal limit = tonumber(ARGV[4])\nlocal time = redis.call('TIME')\nlocal now = time[1] * 1000 + math.floor(time[2] / 1000)\nredis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)\nlocal existing = redis.call('ZSCORE', KEYS[1], token)\nif action == 'release' then\n return redis.call('ZREM', KEYS[1], token)\nend\nif action == 'renew' and not existing then return 0 end\nif action == 'acquire' and existing then return 1 end\nif action == 'acquire' and redis.call('ZCARD', KEYS[1]) >= limit then return 0 end\nredis.call('ZADD', KEYS[1], now + ttl, token)\nlocal latest = redis.call('ZREVRANGE', KEYS[1], 0, 0, 'WITHSCORES')\nredis.call('PEXPIREAT', KEYS[1], math.ceil(tonumber(latest[2])))\nreturn 1\n`\n\n/** Returns the decision and occupancy from the same atomic transition. */\nexport const bulkheadLeaseV1 = `local function transition()\\n${leaseV1}\\nend\\nlocal allowed = transition()\\nreturn {allowed, redis.call('ZCARD', KEYS[1])}`\n\n// ---------------------------------------------------------------------------\n// Circuit-breaker scripts\n//\n// Return arrays use fixed positions so the TypeScript caller can validate\n// and decode without field names (which Lua/Redis cannot return).\n//\n// stateCode encoding: 0=closed 1=open 2=half-open\n// ---------------------------------------------------------------------------\n\n/**\n * Record one attempt outcome into the distributed sliding window.\n * Atomically opens the breaker when the failure ratio meets the threshold.\n *\n * KEYS[1] = breaker state hash (:breaker)\n * KEYS[2] = observations sorted set (:observations)\n *\n * ARGV[1] = outcome \"success\" | \"failure\"\n * ARGV[2] = expectedGeneration integer\n * ARGV[3] = windowTtlMs observation retention window in ms\n * ARGV[4] = minimumThroughput min observations before opening\n * ARGV[5] = failureThresholdNum failure threshold × 1000 (e.g. 500 = 0.5)\n * ARGV[6] = windowSize max observations retained by count\n * ARGV[7] = openMs how long to stay OPEN; closed hash TTL = openMs×2\n * ARGV[8] = uuid unique string for member deduplication\n *\n * Returns: {status, stateCode, generation, windowTotal, windowFailures}\n * status 0 = stale (dropped; generation or state mismatch)\n * status 1 = observed, no transition (remained closed)\n * status 2 = observed, breaker opened (stateCode=1, generation incremented)\n *\n * TTL policy:\n * OPEN state → PERSIST (no expiry). A missing key is treated as closed by\n * all scripts, so expiring an open breaker would silently admit\n * unrestricted traffic and reset the generation counter.\n * CLOSED state → max(openMs×2, windowTtlMs) TTL for eventual cleanup of idle\n * scopes. Expiring a closed key is safe *only* because the TTL\n * outlives the observation window: the window is scoped by an\n * epoch, and an epoch that outlives its members is what keeps\n * cleanup from resurrecting them.\n *\n * Epochs:\n * `generation` increments on every transition, and a brand new value is minted\n * whenever the state hash has to be recreated while observation members from a\n * previous epoch are still present (state lost to eviction or admin cleanup).\n * Window membership is decided by comparing the stored epoch, so members from\n * a superseded epoch can never be counted again, and an attempt holding a\n * pre-loss generation can never pass the staleness check. A scope that has\n * never been observed keeps generation 0.\n */\nexport const breakerObserveV1 = `\nlocal outcome = ARGV[1]\nlocal expectGen = tonumber(ARGV[2])\nlocal windowTtl = tonumber(ARGV[3])\nlocal minTP = tonumber(ARGV[4])\nlocal threshNum = tonumber(ARGV[5])\nlocal windowSize = tonumber(ARGV[6])\nlocal openMs = tonumber(ARGV[7])\nlocal uuid = ARGV[8]\nlocal t = redis.call('TIME')\nlocal now = t[1] * 1000 + math.floor(t[2] / 1000)\nlocal f = redis.call('HMGET', KEYS[1], 'state', 'generation')\nlocal state = f[1] or 'closed'\nlocal gen = tonumber(f[2]) or 0\nif state ~= 'closed' then\n local sc = (state == 'open' and 1) or (state == 'half-open' and 2) or 0\n return {0, sc, gen, 0, 0}\nend\nif redis.call('EXISTS', KEYS[1]) == 0 then\n -- No live state hash: a scope we have never seen, or a hash that was lost\n -- while its window survived.\n if expectGen ~= 0 then\n -- The caller holds a generation this key cannot confirm.\n return {0, 0, 0, 0, 0}\n end\n if redis.call('EXISTS', KEYS[2]) == 1 then\n -- Members from a superseded epoch are still here. Mint an epoch that has\n -- never been used for this key (derived from the observation's own uuid, so\n -- no clock is involved) instead of restarting at a value those members\n -- would match.\n --\n -- Bounded to 11 hex digits (44 bits, <= 14 decimal digits) so the value\n -- prints exactly with stock Lua number formatting: the epoch is read back\n -- from the hash as a decimal string by both this script and the client, and\n -- a larger value could be written in scientific notation and break the\n -- round-trip.\n gen = tonumber(string.sub(redis.sha1hex(uuid), 1, 11), 16)\n if not gen or gen == 0 then gen = 1 end\n else\n gen = 0\n end\n redis.call('HSET', KEYS[1], 'state', 'closed', 'generation', gen,\n 'openedAt', 0, 'probeCount', 0, 'probeSuccesses', 0)\nelseif gen ~= expectGen then\n return {0, 0, gen, 0, 0}\nend\nredis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now - windowTtl)\nlocal member = tostring(gen) .. ':' .. uuid .. ':' .. outcome\nredis.call('ZADD', KEYS[2], 'NX', now, member)\nlocal cnt = redis.call('ZCARD', KEYS[2])\nif cnt > windowSize then\n redis.call('ZREMRANGEBYRANK', KEYS[2], 0, cnt - windowSize - 1)\nend\nredis.call('PEXPIREAT', KEYS[2], now + windowTtl)\nlocal all = redis.call('ZRANGE', KEYS[2], 0, -1)\nlocal prefix = tostring(gen) .. ':'\nlocal wTotal = 0\nlocal wFail = 0\nfor _, m in ipairs(all) do\n if string.sub(m, 1, #prefix) == prefix then\n wTotal = wTotal + 1\n if string.sub(m, -8) == ':failure' then wFail = wFail + 1 end\n end\nend\nif wTotal >= minTP and wFail * 1000 >= threshNum * wTotal then\n gen = gen + 1\n redis.call('HSET', KEYS[1], 'state', 'open', 'generation', gen,\n 'openedAt', now, 'probeCount', 0, 'probeSuccesses', 0)\n -- OPEN state must never expire: a missing key is treated as closed,\n -- which would silently admit unrestricted traffic and reset the generation.\n redis.call('PERSIST', KEYS[1])\n return {2, 1, gen, wTotal, wFail}\nend\nif redis.call('EXISTS', KEYS[1]) == 1 then\n -- Still CLOSED. The cleanup TTL must not expire the state before the window\n -- it governs, otherwise retained members would survive their epoch.\n redis.call('PEXPIRE', KEYS[1], math.max(openMs * 2, windowTtl))\nend\nreturn {1, 0, gen, wTotal, wFail}\n`\n\n/**\n * Admit a probe attempt. Transitions OPEN→HALF_OPEN when openMs has elapsed,\n * then atomically allocates a probe token slot.\n *\n * KEYS[1] = breaker state hash (:breaker)\n * KEYS[2] = probe tokens sorted set (:probes)\n *\n * ARGV[1] = probeToken unique UUID for this probe attempt\n * ARGV[2] = openMs determines OPEN→HALF_OPEN transition and TTL\n * ARGV[3] = halfOpenProbes maximum concurrent probe tokens\n * ARGV[4] = probeLeaseTtlMs probe token TTL in ms\n *\n * Returns: {status, stateCode, generation, probeCount, transitioned}\n * status 0 = rejected\n * stateCode 0 = breaker already CLOSED (no probe needed)\n * stateCode 1 = still OPEN (openMs not yet elapsed)\n * stateCode 2 = HALF_OPEN but probe limit reached\n * status 1 = admitted (probe token stored)\n * transitioned 1 = OPEN→HALF_OPEN transition happened in this call\n * transitioned 0 = was already HALF_OPEN\n */\nexport const breakerAdmitProbeV1 = `\nlocal probeToken = ARGV[1]\nlocal openMs = tonumber(ARGV[2])\nlocal maxProbes = tonumber(ARGV[3])\nlocal probeLeaseTtl = tonumber(ARGV[4])\nlocal t = redis.call('TIME')\nlocal now = t[1] * 1000 + math.floor(t[2] / 1000)\nlocal f = redis.call('HMGET', KEYS[1], 'state', 'generation', 'openedAt',\n 'probeCount', 'probeSuccesses')\nlocal state = f[1] or 'closed'\nlocal gen = tonumber(f[2]) or 0\nlocal openedAt = tonumber(f[3]) or 0\nlocal transitioned = 0\nif state == 'closed' then\n return {0, 0, gen, 0, 0}\nend\nif state == 'open' then\n if now - openedAt < openMs then\n return {0, 1, gen, 0, 0}\n end\n state = 'half-open'\n transitioned = 1\n redis.call('HSET', KEYS[1], 'state', 'half-open', 'probeSuccesses', 0, 'probeCount', 0)\n -- OPEN/HALF_OPEN must never expire; PERSIST removes any prior cleanup TTL.\n redis.call('PERSIST', KEYS[1])\n -- Tokens from the superseded recovery window must not consume slots in this\n -- one; their settle is dropped by the generation check anyway.\n redis.call('DEL', KEYS[2])\nend\nredis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now)\nlocal activeProbes = redis.call('ZCARD', KEYS[2])\nif activeProbes >= maxProbes then\n return {0, 2, gen, activeProbes, transitioned}\nend\nredis.call('ZADD', KEYS[2], 'NX', now + probeLeaseTtl, probeToken)\nactiveProbes = activeProbes + 1\nredis.call('HSET', KEYS[1], 'probeCount', activeProbes)\n-- State hash must not expire while recovery probes are in flight.\nredis.call('PERSIST', KEYS[1])\n-- Probes sorted set expires naturally once the last lease elapses.\nredis.call('PEXPIREAT', KEYS[2], now + probeLeaseTtl + 1000)\nreturn {1, 2, gen, activeProbes, transitioned}\n`\n\n/**\n * Record a probe attempt outcome. Removes the probe token and applies the\n * result: failure re-opens; sufficient successes close the breaker.\n *\n * KEYS[1] = breaker state hash (:breaker)\n * KEYS[2] = probe tokens sorted set (:probes)\n *\n * ARGV[1] = probeToken the token issued by admitProbe\n * ARGV[2] = outcome \"success\" | \"failure\"\n * ARGV[3] = expectedGeneration generation captured at admission time\n * ARGV[4] = halfOpenSuccesses consecutive probe successes needed to close\n * ARGV[5] = openMs how long the breaker stays OPEN (TTL floor)\n * ARGV[6] = windowTtlMs observation retention (TTL floor): the CLOSED\n * hash must outlive the window it governs\n *\n * Returns: {status, stateCode, generation}\n * status 0 = stale (token missing, lease elapsed, or generation mismatch;\n * the result is dropped and any consumed token is released)\n * status 1 = settled, no state transition (still HALF_OPEN)\n * status 2 = settled, state transition occurred\n * stateCode 0 = transitioned to CLOSED\n * stateCode 1 = transitioned back to OPEN (probe failure)\n *\n * A token carries its own deadline as its sorted-set score. When the lease has\n * elapsed the slot is already recoverable - admitProbe prunes expired tokens\n * and re-issues the slot - so the result must not count even while the member is\n * still present. The deadline is therefore checked under the same atomic call.\n */\nexport const breakerSettleProbeV1 = `\nlocal probeToken = ARGV[1]\nlocal outcome = ARGV[2]\nlocal expectGen = tonumber(ARGV[3])\nlocal halfOpenSucc = tonumber(ARGV[4])\nlocal openMs = tonumber(ARGV[5])\nlocal windowTtl = tonumber(ARGV[6])\nlocal t = redis.call('TIME')\nlocal now = t[1] * 1000 + math.floor(t[2] / 1000)\nlocal f = redis.call('HMGET', KEYS[1], 'state', 'generation', 'probeSuccesses', 'probeCount')\nlocal state = f[1] or 'closed'\nlocal gen = tonumber(f[2]) or 0\nlocal probeSucc = tonumber(f[3]) or 0\nlocal probeCnt = tonumber(f[4]) or 0\nlocal sc = (state == 'open' and 1) or (state == 'half-open' and 2) or 0\nlocal deadline = redis.call('ZSCORE', KEYS[2], probeToken)\nif not deadline then\n -- Never admitted, already settled, or dropped with its recovery window.\n return {0, sc, gen}\nend\nredis.call('ZREM', KEYS[2], probeToken)\nif tonumber(deadline) <= now then\n -- The lease elapsed while the probe was still running: its slot was\n -- recoverable, so the result cannot be counted. Release the slot it still\n -- occupied so the probe count keeps matching the token set.\n probeCnt = math.max(0, probeCnt - 1)\n redis.call('HSET', KEYS[1], 'probeCount', probeCnt)\n return {0, sc, gen}\nend\nif state ~= 'half-open' or gen ~= expectGen then\n return {0, sc, gen}\nend\nprobeCnt = math.max(0, probeCnt - 1)\nif outcome == 'failure' then\n gen = gen + 1\n redis.call('HSET', KEYS[1], 'state', 'open', 'generation', gen,\n 'openedAt', now, 'probeCount', 0, 'probeSuccesses', 0)\n -- Re-opened: OPEN must not expire (see breakerObserveV1 TTL policy).\n redis.call('PERSIST', KEYS[1])\n -- In-flight probes belong to the dead generation; free their slots so the\n -- next recovery window starts with full capacity.\n redis.call('DEL', KEYS[2])\n return {2, 1, gen}\nend\nprobeSucc = probeSucc + 1\nif probeSucc >= halfOpenSucc then\n gen = gen + 1\n redis.call('HSET', KEYS[1], 'state', 'closed', 'generation', gen,\n 'probeCount', 0, 'probeSuccesses', 0)\n -- Newly CLOSED: expire for cleanup, but never before the window it governs.\n redis.call('PEXPIRE', KEYS[1], math.max(openMs * 2, windowTtl))\n redis.call('DEL', KEYS[2])\n return {2, 0, gen}\nend\nredis.call('HSET', KEYS[1], 'probeSuccesses', probeSucc, 'probeCount', probeCnt)\n-- Still HALF_OPEN: must not expire while recovery is in progress.\nredis.call('PERSIST', KEYS[1])\nreturn {1, 2, gen}\n`\n","import type { BulkheadCoordinator } from \"../../core/bulkhead.js\"\nimport { CoordinatorUnavailableError } from \"./client.js\"\nimport { evalScript } from \"./eval-script.js\"\nimport { coordinationKey } from \"./keys.js\"\nimport type { RedisScriptClient } from \"./leases.js\"\nimport { bulkheadLeaseV1 } from \"./scripts.js\"\nexport function redisCoordinator(\n client: RedisScriptClient,\n options: { namespace: string },\n): BulkheadCoordinator {\n const namespace = options.namespace\n coordinationKey(namespace, \"bulkhead\", \"validate\", \"validate\")\n const coordinator: BulkheadCoordinator = {\n async command(identity, action, token, leaseMs, limit) {\n if (\n ![\"acquire\", \"renew\", \"release\"].includes(action) ||\n typeof token !== \"string\" ||\n !token ||\n token.length > 256\n )\n throw new TypeError(\"Invalid bulkhead lease action or token\")\n if (\n ![leaseMs, limit].every(\n (value) => Number.isSafeInteger(value) && value > 0,\n ) ||\n leaseMs > 86400000\n )\n throw new RangeError(\"Invalid bulkhead lease duration or limit\")\n const key = coordinationKey(\n namespace,\n `bulkhead:${identity.name}`,\n identity.operation,\n identity.scope,\n )\n try {\n const result = await evalScript(\n client,\n bulkheadLeaseV1,\n 1,\n key,\n action,\n token,\n leaseMs,\n limit,\n )\n if (\n !Array.isArray(result) ||\n result.length !== 2 ||\n ![0, 1].includes(result[0]) ||\n !Number.isSafeInteger(result[1]) ||\n result[1] < 0\n )\n throw new Error(\"Invalid bulkhead reply\")\n return { allowed: result[0] === 1, occupancy: result[1] as number }\n } catch (error) {\n throw new CoordinatorUnavailableError(error)\n }\n },\n }\n return Object.freeze(coordinator)\n}\n","import type {\n AdmitProbeResult,\n BreakerCoordinator,\n BreakerIdentity,\n BreakerState,\n ObserveResult,\n SettleProbeResult,\n} from \"../../core/circuit-breaker.js\"\nimport { CoordinatorUnavailableError } from \"./client.js\"\nimport { evalScript } from \"./eval-script.js\"\nimport { coordinationKey } from \"./keys.js\"\nimport type { RedisScriptClient } from \"./leases.js\"\nimport {\n breakerAdmitProbeV1,\n breakerObserveV1,\n breakerSettleProbeV1,\n} from \"./scripts.js\"\n\n// ---------------------------------------------------------------------------\n// Key helpers\n// ---------------------------------------------------------------------------\n\nfunction breakerKeys(\n namespace: string,\n identity: BreakerIdentity,\n): [hashKey: string, obsKey: string, probeKey: string] {\n const policy = `breaker:${identity.name}`\n const hash = coordinationKey(\n namespace,\n policy,\n identity.operation,\n identity.scope,\n \"breaker\",\n )\n const obs = coordinationKey(\n namespace,\n policy,\n identity.operation,\n identity.scope,\n \"observations\",\n )\n const prob = coordinationKey(\n namespace,\n policy,\n identity.operation,\n identity.scope,\n \"probes\",\n )\n return [hash, obs, prob]\n}\n\n// ---------------------------------------------------------------------------\n// Reply validation helpers\n// ---------------------------------------------------------------------------\n\nfunction assertArray(reply: unknown, minLen: number, label: string): unknown[] {\n if (\n !Array.isArray(reply) ||\n reply.length < minLen ||\n reply.some((v) => typeof v !== \"number\" || !Number.isSafeInteger(v))\n ) {\n throw new Error(\n `Invalid ${label} reply from Redis: ${JSON.stringify(reply)}`,\n )\n }\n return reply as unknown[]\n}\n\nconst STATE_CODES: BreakerState[] = [\"closed\", \"open\", \"half-open\"]\n\nfunction decodeState(code: number): BreakerState {\n const s = STATE_CODES[code]\n if (!s) throw new Error(`Unknown breaker state code: ${code}`)\n return s\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Policy-specific Redis coordinator for `circuitBreaker.distributed()`.\n *\n * The caller owns `client` and must connect/disconnect it independently.\n * `namespace` is prepended to every key; use a per-service, per-environment\n * value to avoid cross-deployment state collisions.\n */\nexport function redisCircuitBreakerCoordinator(\n client: RedisScriptClient,\n options: { readonly namespace: string },\n): BreakerCoordinator {\n const { namespace } = options\n // Validate namespace eagerly (coordinationKey throws on bad input).\n coordinationKey(\n namespace,\n \"breaker:validate\",\n \"validate\",\n \"validate\",\n \"breaker\",\n )\n\n const coordinator: BreakerCoordinator = {\n async readState(identity) {\n const [hashKey] = breakerKeys(namespace, identity)\n try {\n const fields = await client.hmget(hashKey, \"state\", \"generation\")\n const rawState = fields[0]\n if (!rawState) return null\n const state = rawState as BreakerState\n if (!STATE_CODES.includes(state))\n throw new Error(`Unknown breaker state: ${rawState}`)\n const generation = parseInt(fields[1] ?? \"0\", 10)\n return { state, generation }\n } catch (error) {\n throw new CoordinatorUnavailableError(error)\n }\n },\n\n async observe(identity, params) {\n const [hashKey, obsKey] = breakerKeys(namespace, identity)\n const {\n generation,\n outcome,\n uuid,\n windowTtlMs,\n minimumThroughput,\n failureThresholdNumerator,\n windowSize,\n openMs,\n } = params\n try {\n const reply = await evalScript(\n client,\n breakerObserveV1,\n 2,\n hashKey,\n obsKey,\n outcome,\n generation,\n windowTtlMs,\n minimumThroughput,\n failureThresholdNumerator,\n windowSize,\n openMs,\n uuid,\n )\n const r = assertArray(reply, 5, \"breakerObserveV1\") as number[]\n const [status, , newGen, windowTotal, windowFailures] = r\n if (status === 0) {\n return {\n type: \"stale\",\n currentGeneration: newGen,\n } satisfies ObserveResult\n }\n if (status === 2) {\n return {\n type: \"opened\",\n newGeneration: newGen,\n windowTotal,\n windowFailures,\n } satisfies ObserveResult\n }\n return {\n type: \"observed\",\n generation: newGen,\n windowTotal,\n windowFailures,\n } satisfies ObserveResult\n } catch (error) {\n throw new CoordinatorUnavailableError(error)\n }\n },\n\n async admitProbe(identity, params) {\n const [hashKey, , probeKey] = breakerKeys(namespace, identity)\n const { probeToken, openMs, halfOpenProbes, probeLeaseTtlMs } = params\n try {\n const reply = await evalScript(\n client,\n breakerAdmitProbeV1,\n 2,\n hashKey,\n probeKey,\n probeToken,\n openMs,\n halfOpenProbes,\n probeLeaseTtlMs,\n )\n const r = assertArray(reply, 5, \"breakerAdmitProbeV1\") as number[]\n const [status, stateCode, gen, probeCount, transitioned] = r\n if (status === 0) {\n const reason =\n stateCode === 0\n ? \"closed\"\n : stateCode === 1\n ? \"open\"\n : \"probe-limit\"\n return {\n type: \"rejected\",\n reason,\n generation: gen,\n } satisfies AdmitProbeResult\n }\n return {\n type: \"admitted\",\n generation: gen,\n probeCount,\n stateChanged: transitioned === 1,\n } satisfies AdmitProbeResult\n } catch (error) {\n throw new CoordinatorUnavailableError(error)\n }\n },\n\n async settleProbe(identity, params) {\n const [hashKey, , probeKey] = breakerKeys(namespace, identity)\n const {\n probeToken,\n outcome,\n generation,\n halfOpenSuccesses,\n openMs,\n windowTtlMs,\n } = params\n try {\n const reply = await evalScript(\n client,\n breakerSettleProbeV1,\n 2,\n hashKey,\n probeKey,\n probeToken,\n outcome,\n generation,\n halfOpenSuccesses,\n openMs,\n // Floor for the CLOSED cleanup TTL; older callers that do not pass it\n // keep the historical openMs x 2 behaviour.\n windowTtlMs ?? openMs * 2,\n )\n const r = assertArray(reply, 3, \"breakerSettleProbeV1\") as number[]\n const [status, stateCode, newGen] = r\n if (status === 0) {\n return {\n type: \"stale\",\n generation: newGen,\n } satisfies SettleProbeResult\n }\n const state = decodeState(stateCode)\n if (status === 2) {\n return {\n type: \"transitioned\",\n newState: state,\n newGeneration: newGen,\n previousState: \"half-open\",\n } satisfies SettleProbeResult\n }\n return {\n type: \"settled\",\n state,\n generation: newGen,\n } satisfies SettleProbeResult\n } catch (error) {\n throw new CoordinatorUnavailableError(error)\n }\n },\n }\n\n return Object.freeze(coordinator)\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import { h as Outcome, O as OperationCapabilities, e as ExecutionMetadata, P as Policy } from './types-Tf9T76C7.js';
2
+
3
+ /**
4
+ * Settled-attempt information passed to a custom `delay` function.
5
+ *
6
+ * `result` and `error` are conveniences over `outcome`; the core never
7
+ * interprets them, so an adapter-specific helper can pace retries from
8
+ * protocol feedback (for example an HTTP `Retry-After` header) without
9
+ * leaking protocol types into the core.
10
+ */
11
+ interface RetryContext {
12
+ readonly outcome: Outcome<unknown>;
13
+ readonly result: unknown;
14
+ readonly error: unknown;
15
+ readonly capabilities: OperationCapabilities;
16
+ readonly metadata: ExecutionMetadata;
17
+ }
18
+ type RetryDelay = number | ((attempt: number, context: RetryContext) => number);
19
+ interface RetryOptions {
20
+ readonly maxAttempts: number;
21
+ readonly delay?: RetryDelay;
22
+ }
23
+ /** Retries adapter-classified failures within a single logical invocation. */
24
+ declare function retry(options: RetryOptions): Policy;
25
+
26
+ export { type RetryContext as R, type RetryDelay as a, type RetryOptions as b, retry as r };