barejs 0.1.55 → 0.1.56

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.
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import type { Context, Middleware } from '../core/context';
2
3
  import type { CachedIdempotentEntry, IdempotencyStore } from './store';
3
4
 
@@ -10,32 +11,55 @@ export interface IdempotencyOptions {
10
11
  maxKeys?: number;
11
12
  /** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
12
13
  store?: IdempotencyStore;
14
+ /**
15
+ * Scope string mixed into the cache key so one caller can never replay another caller's response.
16
+ * Default: SHA-256 of the Authorization and Cookie headers.
17
+ */
18
+ keyScope?: (ctx: Context) => string | undefined;
13
19
  }
14
20
 
21
+ const REPLAY_HEADERS = ['location', 'content-location', 'etag'];
22
+ const pickReplayHeaders = (res: Response): Record<string, string> | undefined => {
23
+ let out: Record<string, string> | undefined;
24
+ for (const h of REPLAY_HEADERS) {
25
+ const v = res.headers.get(h);
26
+ if (v !== null) (out ??= {})[h] = v;
27
+ }
28
+ return out;
29
+ };
30
+
31
+ const defaultKeyScope = (ctx: Context): string => {
32
+ const a = ctx.req.headers.get('authorization') || '';
33
+ const c = ctx.req.headers.get('cookie') || '';
34
+ if (!a && !c) return '';
35
+ return createHash('sha256').update(a).update('\0').update(c).digest('hex');
36
+ };
37
+
15
38
  const buildReplayResponse = (existing: CachedIdempotentEntry): Response => {
16
39
  if (existing.rawBody !== undefined) {
17
40
  return new Response(existing.rawBody, {
18
41
  status: existing.status,
19
42
  headers: {
43
+ ...(existing.headers || {}),
20
44
  'content-type': existing.contentType || 'application/json',
21
45
  'X-Idempotent-Replayed': 'true'
22
46
  }
23
47
  });
24
48
  }
25
- return Response.json(existing.body, {
49
+ return Response.json(existing.body ?? null, {
26
50
  status: existing.status,
27
51
  headers: { 'X-Idempotent-Replayed': 'true' }
28
52
  });
29
53
  };
30
54
 
31
- const extractIdemKey = (ctx: Context, headerName: string): string | undefined => {
55
+ const extractIdemKey = (ctx: Context, headerName: string, keyScope: (ctx: Context) => string | undefined): string | undefined => {
32
56
  const rawKey = ctx.req.headers.get(headerName)?.trim();
33
57
  if (!rawKey) return undefined;
34
58
  const rawUrl = ctx.req.url;
35
59
  const s = rawUrl.indexOf('/', 8);
36
60
  const q = s === -1 ? -1 : rawUrl.indexOf('?', s);
37
61
  const path = s === -1 ? '/' : (q === -1 ? rawUrl.slice(s) : rawUrl.slice(s, q));
38
- return `${ctx.req.method}:${path}:${rawKey}`;
62
+ return `${ctx.req.method}:${path}:${keyScope(ctx) || ''}:${rawKey}`;
39
63
  };
40
64
 
41
65
  /**
@@ -45,13 +69,15 @@ const extractIdemKey = (ctx: Context, headerName: string): string | undefined =>
45
69
  export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
46
70
  const headerName = (options.headerName || 'idempotency-key').toLowerCase();
47
71
  const ttlMs = options.ttlMs ?? 300_000;
72
+ const keyScope = options.keyScope ?? defaultKeyScope;
48
73
  const maxKeys = options.maxKeys ?? 10_000;
49
74
  const externalStore = options.store;
50
75
 
51
76
  if (externalStore) {
77
+ const hasAcquireToken = typeof externalStore.acquireToken === 'function';
52
78
  const storeLockShim = { delete: (k: string) => { void externalStore.release(k); } };
53
79
  const mw: Middleware = async (ctx: Context) => {
54
- const key = extractIdemKey(ctx, headerName);
80
+ const key = extractIdemKey(ctx, headerName, keyScope);
55
81
  if (!key) {
56
82
  (ctx as any)._idempotencyKey = undefined;
57
83
  return undefined;
@@ -63,7 +89,18 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
63
89
  return buildReplayResponse(existing);
64
90
  }
65
91
 
66
- const acquired = await externalStore.acquire(key, ttlMs);
92
+ let acquired = false;
93
+ let lockToken: string | undefined;
94
+ if (hasAcquireToken) {
95
+ const tok = await externalStore.acquireToken!(key, ttlMs);
96
+ if (tok) {
97
+ acquired = true;
98
+ lockToken = tok;
99
+ }
100
+ } else {
101
+ acquired = await externalStore.acquire(key, ttlMs);
102
+ }
103
+
67
104
  if (!acquired) {
68
105
  (ctx as any)._idempotencyKey = undefined;
69
106
  return Response.json(
@@ -72,33 +109,82 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
72
109
  );
73
110
  }
74
111
 
112
+ if ((ctx as any)._detached) {
113
+ (ctx as any)._idempotencyKey = undefined;
114
+ await externalStore.release(key, lockToken);
115
+ return undefined;
116
+ }
117
+
118
+ let recheck: CachedIdempotentEntry | undefined;
119
+ try {
120
+ recheck = await externalStore.get(key);
121
+ } catch (err) {
122
+ (ctx as any)._idempotencyKey = undefined;
123
+ await externalStore.release(key, lockToken);
124
+ throw err;
125
+ }
126
+
127
+ if ((ctx as any)._detached) {
128
+ (ctx as any)._idempotencyKey = undefined;
129
+ await externalStore.release(key, lockToken);
130
+ return undefined;
131
+ }
132
+
133
+ if (recheck && Date.now() < recheck.expiresAt) {
134
+ (ctx as any)._idempotencyKey = undefined;
135
+ await externalStore.release(key, lockToken);
136
+ return buildReplayResponse(recheck);
137
+ }
138
+
75
139
  (ctx as any)._idempotencyKey = key;
76
- (ctx as any)._idemInFlight = storeLockShim;
140
+ (ctx as any)._idemExtToken = lockToken;
141
+ (ctx as any)._idemInFlight = hasAcquireToken
142
+ ? {
143
+ delete: (k: string) => {
144
+ const tok = (ctx as any)._idemExtToken;
145
+ (ctx as any)._idemExtToken = undefined;
146
+ void externalStore.release(k, tok);
147
+ }
148
+ }
149
+ : storeLockShim;
77
150
  return undefined;
78
151
  };
79
152
 
80
153
  (mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
81
154
  const key = (ctx as any)._idempotencyKey;
82
155
  if (!key) return;
83
- (ctx as any)._idempotencyKey = undefined;
84
- (ctx as any)._idemInFlight = undefined;
85
- const isStream = resVal instanceof Response && (resVal.headers.get('content-type') || '').includes('text/event-stream');
86
- const clonedRes = !isStream && status >= 200 && status < 300 && resVal instanceof Response ? resVal.clone() : null;
156
+ const isResp = resVal instanceof Response;
157
+ const isStream = isResp && (resVal.headers.get('content-type') || '').includes('text/event-stream');
158
+ let clonedRes: any = null;
159
+ if (!isStream && status >= 200 && status < 300 && isResp) {
160
+ try { clonedRes = resVal.clone(); } catch { clonedRes = null; }
161
+ }
87
162
  const ct = clonedRes ? (clonedRes.headers.get('content-type') || 'application/json') : undefined;
88
- void (async () => {
163
+ return (async () => {
89
164
  try {
90
- if (!isStream && status >= 200 && status < 300) {
91
- if (clonedRes) {
92
- const buf = await clonedRes.arrayBuffer();
93
- await externalStore.set(key, { status, rawBody: buf, contentType: ct, expiresAt: Date.now() + ttlMs }, ttlMs);
165
+ if (!(ctx as any)._detached && !isStream && status >= 200 && status < 300) {
166
+ if (isResp) {
167
+ if (clonedRes) {
168
+ const buf = await clonedRes.arrayBuffer();
169
+ if (!(ctx as any)._detached) {
170
+ await externalStore.set(key, { status, rawBody: buf, contentType: ct, headers: pickReplayHeaders(clonedRes), expiresAt: Date.now() + ttlMs }, ttlMs);
171
+ }
172
+ }
94
173
  } else {
95
- await externalStore.set(key, { status, body: resVal, expiresAt: Date.now() + ttlMs }, ttlMs);
174
+ await externalStore.set(key, { status, body: resVal ?? null, expiresAt: Date.now() + ttlMs }, ttlMs);
96
175
  }
97
176
  }
98
177
  } catch {
99
178
  // Best-effort cache write
100
179
  } finally {
101
- await externalStore.release(key);
180
+ const extToken = (ctx as any)._idemExtToken;
181
+ const alreadyReleased = Boolean((ctx as any)._detached) || !(ctx as any)._idempotencyKey;
182
+ (ctx as any)._idempotencyKey = undefined;
183
+ (ctx as any)._idemExtToken = undefined;
184
+ (ctx as any)._idemInFlight = undefined;
185
+ if (!alreadyReleased) {
186
+ await externalStore.release(key, extToken);
187
+ }
102
188
  }
103
189
  })();
104
190
  };
@@ -106,9 +192,11 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
106
192
  (mw as any).__idempotencyRelease = (ctx: Context) => {
107
193
  const key = (ctx as any)._idempotencyKey;
108
194
  if (key) {
195
+ const extToken = (ctx as any)._idemExtToken;
109
196
  (ctx as any)._idempotencyKey = undefined;
197
+ (ctx as any)._idemExtToken = undefined;
110
198
  (ctx as any)._idemInFlight = undefined;
111
- void externalStore.release(key);
199
+ void externalStore.release(key, extToken);
112
200
  }
113
201
  };
114
202
 
@@ -116,7 +204,7 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
116
204
  }
117
205
 
118
206
  const cache = new Map<string, CachedIdempotentEntry>();
119
- const inFlight = new Set<string>();
207
+ const inFlight = new Map<string, { token: string; expiresAt: number }>();
120
208
 
121
209
  const evictIfNeeded = () => {
122
210
  if (cache.size >= maxKeys) {
@@ -126,7 +214,7 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
126
214
  };
127
215
 
128
216
  const mw: Middleware = (ctx: Context) => {
129
- const key = extractIdemKey(ctx, headerName);
217
+ const key = extractIdemKey(ctx, headerName, keyScope);
130
218
  if (!key) {
131
219
  (ctx as any)._idempotencyKey = undefined;
132
220
  return undefined;
@@ -142,55 +230,84 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
142
230
  cache.delete(key);
143
231
  }
144
232
 
145
- if (inFlight.has(key)) {
146
- (ctx as any)._idempotencyKey = undefined;
147
- return Response.json(
148
- { status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
149
- { status: 409 }
150
- );
233
+ const lockEntry = inFlight.get(key);
234
+ if (lockEntry !== undefined) {
235
+ if (now < lockEntry.expiresAt) {
236
+ (ctx as any)._idempotencyKey = undefined;
237
+ return Response.json(
238
+ { status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
239
+ { status: 409 }
240
+ );
241
+ }
242
+ inFlight.delete(key);
151
243
  }
152
244
 
153
- inFlight.add(key);
245
+ const token = crypto.randomUUID();
246
+ inFlight.set(key, { token, expiresAt: now + ttlMs });
154
247
  (ctx as any)._idempotencyKey = key;
155
- (ctx as any)._idemInFlight = inFlight;
248
+ (ctx as any)._idemToken = token;
249
+ (ctx as any)._idemInFlight = {
250
+ delete: (k: string) => {
251
+ const cur = inFlight.get(k);
252
+ if (cur && cur.token === token) inFlight.delete(k);
253
+ }
254
+ };
156
255
  return undefined;
157
256
  };
158
257
 
258
+ const releaseOwned = (ctx: Context, key: string) => {
259
+ const token = (ctx as any)._idemToken;
260
+ (ctx as any)._idempotencyKey = undefined;
261
+ (ctx as any)._idemToken = undefined;
262
+ (ctx as any)._idemInFlight = undefined;
263
+ const cur = inFlight.get(key);
264
+ if (cur && (!token || cur.token === token)) {
265
+ inFlight.delete(key);
266
+ }
267
+ };
268
+
159
269
  (mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
160
270
  const key = (ctx as any)._idempotencyKey;
161
271
  if (!key) return;
162
- (ctx as any)._idempotencyKey = undefined;
163
- (ctx as any)._idemInFlight = undefined;
164
- inFlight.delete(key);
165
- if (status >= 200 && status < 300) {
166
- if (resVal instanceof Response) {
167
- const ct = resVal.headers.get('content-type') || 'application/json';
168
- resVal.clone().arrayBuffer().then((buf) => {
169
- evictIfNeeded();
170
- cache.set(key, {
171
- status,
172
- rawBody: buf,
173
- contentType: ct,
174
- expiresAt: Date.now() + ttlMs
272
+ const isResp = resVal instanceof Response;
273
+ const isStream = isResp && (resVal.headers.get('content-type') || '').includes('text/event-stream');
274
+ if (!(ctx as any)._detached && !isStream && status >= 200 && status < 300) {
275
+ if (isResp) {
276
+ let cloned: any = null;
277
+ try { cloned = resVal.clone(); } catch { cloned = null; }
278
+ if (cloned) {
279
+ const ct = cloned.headers.get('content-type') || 'application/json';
280
+ return cloned.arrayBuffer().then((buf: ArrayBuffer) => {
281
+ if ((ctx as any)._detached) return;
282
+ evictIfNeeded();
283
+ cache.set(key, {
284
+ status,
285
+ rawBody: buf,
286
+ contentType: ct,
287
+ headers: pickReplayHeaders(cloned),
288
+ expiresAt: Date.now() + ttlMs
289
+ });
290
+ }).catch(() => {}).finally(() => {
291
+ releaseOwned(ctx, key);
175
292
  });
176
- }).catch(() => {});
177
- } else {
178
- evictIfNeeded();
179
- cache.set(key, {
180
- status,
181
- body: resVal,
182
- expiresAt: Date.now() + ttlMs
183
- });
293
+ }
294
+ releaseOwned(ctx, key);
295
+ return;
184
296
  }
297
+ evictIfNeeded();
298
+ cache.set(key, {
299
+ status,
300
+ body: resVal ?? null,
301
+ expiresAt: Date.now() + ttlMs
302
+ });
185
303
  }
304
+ releaseOwned(ctx, key);
186
305
  };
187
306
 
188
307
  (mw as any).__idempotencyRelease = (ctx: Context) => {
189
308
  const key = (ctx as any)._idempotencyKey;
190
309
  if (key) {
191
- (ctx as any)._idempotencyKey = undefined;
192
- (ctx as any)._idemInFlight = undefined;
193
- inFlight.delete(key);
310
+ releaseOwned(ctx, key);
194
311
  }
195
312
  };
196
313
 
@@ -20,7 +20,7 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
20
20
  const windowMs = options.windowMs ?? 60_000;
21
21
  const max = options.max ?? 100;
22
22
  const message = options.message ?? 'Too many requests, please try again later.';
23
- const maxEntries = options.maxEntries ?? 10_000;
23
+ const maxEntries = Math.max(1, options.maxEntries ?? 10_000);
24
24
  const keyGenerator = options.keyGenerator ?? ((ctx: Context) => ctx.ip);
25
25
  const store = options.store;
26
26
 
@@ -73,15 +73,25 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
73
73
  if (now >= v.resetAt) buckets.delete(k);
74
74
  if (buckets.size < maxEntries) break;
75
75
  }
76
- if (buckets.size >= maxEntries) {
77
- const firstKey = buckets.keys().next().value;
78
- if (firstKey !== undefined) buckets.delete(firstKey);
76
+ }
77
+ let storeKey = key;
78
+ if (buckets.size >= maxEntries && !buckets.has(key)) {
79
+ // Table is full of live buckets: never evict them (would let a flooder reset a victim's counter).
80
+ // Fold overflow keys into one shared bucket instead.
81
+ storeKey = '\0__overflow__';
82
+ const ob = buckets.get(storeKey);
83
+ if (ob && now < ob.resetAt) {
84
+ ob.count++;
85
+ return finalizeBucket(ctx, ob.count, ob.resetAt, now, next);
79
86
  }
80
87
  }
81
88
  bucket = { count: 1, resetAt: now + windowMs };
82
- buckets.set(key, bucket);
89
+ buckets.delete(storeKey);
90
+ buckets.set(storeKey, bucket);
83
91
  } else {
84
92
  bucket.count++;
93
+ buckets.delete(key);
94
+ buckets.set(key, bucket);
85
95
  }
86
96
 
87
97
  return finalizeBucket(ctx, bucket.count, bucket.resetAt, now, next);
@@ -20,18 +20,26 @@ export interface CircuitBreakerOptions {
20
20
  export const circuitBreaker = (options: CircuitBreakerOptions = {}): Middleware => {
21
21
  const failureThreshold = options.failureThreshold ?? 5;
22
22
  const resetTimeoutMs = options.resetTimeoutMs ?? 30_000;
23
- const isFailure = options.isFailure ?? ((res: any, err?: any) => Boolean(err) || (res instanceof Response && res.status >= 500));
23
+ const isFailure = options.isFailure ?? ((res: any, err?: any) => Boolean(err) || (res instanceof Response && (res.status >= 500 || res.status === 408)));
24
24
 
25
25
  let state: CircuitState = 'CLOSED';
26
26
  let failures = 0;
27
27
  let openedAt = 0;
28
28
  let halfOpenInFlight = false;
29
+ let epoch = 0;
30
+ let probeSeq = 0;
31
+ let activeProbe = 0;
29
32
 
30
33
  const setState = (nextState: CircuitState) => {
31
34
  if (state !== nextState) {
32
35
  const prev = state;
33
36
  state = nextState;
34
- options.onStateChange?.(prev, nextState);
37
+ epoch++;
38
+ try {
39
+ options.onStateChange?.(prev, nextState);
40
+ } catch {
41
+ // Ignore user callback errors on state transition
42
+ }
35
43
  }
36
44
  };
37
45
 
@@ -60,8 +68,24 @@ export const circuitBreaker = (options: CircuitBreakerOptions = {}): Middleware
60
68
  isHalfOpenProbe = true;
61
69
  }
62
70
 
71
+ const entryEpoch = epoch;
72
+ let probeTimer: ReturnType<typeof setTimeout> | undefined;
73
+ const myProbe = isHalfOpenProbe ? ++probeSeq : 0;
74
+ if (isHalfOpenProbe) {
75
+ activeProbe = myProbe;
76
+ // A probe that never settles must not wedge the breaker forever.
77
+ probeTimer = setTimeout(() => {
78
+ if (activeProbe === myProbe && entryEpoch === epoch) {
79
+ halfOpenInFlight = false;
80
+ activeProbe = 0;
81
+ openedAt = Date.now();
82
+ setState('OPEN');
83
+ }
84
+ }, Math.min(Math.max(resetTimeoutMs, 1), 2 ** 31 - 1));
85
+ }
63
86
  try {
64
87
  const res = await exec();
88
+ if (entryEpoch !== epoch) return res;
65
89
  if (isFailure(res)) {
66
90
  failures++;
67
91
  if (isHalfOpenProbe || failures >= failureThreshold) {
@@ -74,14 +98,17 @@ export const circuitBreaker = (options: CircuitBreakerOptions = {}): Middleware
74
98
  }
75
99
  return res;
76
100
  } catch (err) {
77
- failures++;
78
- if (isHalfOpenProbe || failures >= failureThreshold) {
79
- openedAt = Date.now();
80
- setState('OPEN');
101
+ if (entryEpoch === epoch && isFailure(undefined, err)) {
102
+ failures++;
103
+ if (isHalfOpenProbe || failures >= failureThreshold) {
104
+ openedAt = Date.now();
105
+ setState('OPEN');
106
+ }
81
107
  }
82
108
  throw err;
83
109
  } finally {
84
- if (isHalfOpenProbe) halfOpenInFlight = false;
110
+ if (probeTimer !== undefined) clearTimeout(probeTimer);
111
+ if (isHalfOpenProbe && activeProbe === myProbe) { halfOpenInFlight = false; activeProbe = 0; }
85
112
  }
86
113
  };
87
114
 
@@ -7,6 +7,8 @@ export interface CachedIdempotentEntry {
7
7
  body?: any;
8
8
  rawBody?: ArrayBuffer;
9
9
  contentType?: string;
10
+ /** Replayed safe headers (Location, Content-Location, ETag) */
11
+ headers?: Record<string, string>;
10
12
  expiresAt: number;
11
13
  }
12
14
 
@@ -14,7 +16,8 @@ export interface IdempotencyStore {
14
16
  get(key: string): Promise<CachedIdempotentEntry | undefined> | CachedIdempotentEntry | undefined;
15
17
  set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> | void;
16
18
  acquire(key: string, ttlMs?: number): Promise<boolean> | boolean;
17
- release(key: string): Promise<void> | void;
19
+ acquireToken?(key: string, ttlMs?: number): Promise<string | null> | string | null;
20
+ release(key: string, tokenOverride?: string): Promise<void> | void;
18
21
  }
19
22
 
20
23
  export interface RevocationStore {
@@ -74,6 +77,9 @@ export const redisStore = (client: any, options: RedisStoreOptions = {}): BareSt
74
77
  }
75
78
  };
76
79
 
80
+ const lockTokens = new Map<string, string[]>();
81
+ const RELEASE_LUA = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
82
+
77
83
  return {
78
84
  async increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> {
79
85
  const fullKey = `${prefix}rl:${key}`;
@@ -110,6 +116,7 @@ export const redisStore = (client: any, options: RedisStoreOptions = {}): BareSt
110
116
  status: parsed.status,
111
117
  rawBody: buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
112
118
  contentType: parsed.contentType,
119
+ headers: parsed.headers,
113
120
  expiresAt: parsed.expiresAt
114
121
  };
115
122
  }
@@ -127,24 +134,61 @@ export const redisStore = (client: any, options: RedisStoreOptions = {}): BareSt
127
134
  if (entry.rawBody !== undefined) {
128
135
  serializable.rawBodyBase64 = Buffer.from(entry.rawBody).toString('base64');
129
136
  serializable.contentType = entry.contentType;
137
+ if (entry.headers) serializable.headers = entry.headers;
130
138
  } else {
131
139
  serializable.body = entry.body;
132
140
  }
133
141
  await setWithTtl(`${prefix}idem:${key}`, JSON.stringify(serializable), ttlMs);
134
142
  },
135
143
 
136
- async acquire(key: string, ttlMs: number = 30_000): Promise<boolean> {
144
+ async acquireToken(key: string, ttlMs: number = 30_000): Promise<string | null> {
137
145
  const lockKey = `${prefix}idem:lock:${key}`;
146
+ const token = crypto.randomUUID();
138
147
  if (useSend) {
139
- const res = await client.send('SET', [lockKey, '1', 'PX', String(ttlMs), 'NX']);
140
- return res === 'OK' || res === true;
148
+ const res = await client.send('SET', [lockKey, token, 'PX', String(ttlMs), 'NX']);
149
+ return (res === 'OK' || res === true) ? token : null;
141
150
  }
142
- const res = await client.set(lockKey, '1', 'PX', ttlMs, 'NX');
143
- return res === 'OK' || res === true || res === 1;
151
+ const res = await client.set(lockKey, token, 'PX', ttlMs, 'NX');
152
+ return (res === 'OK' || res === true || res === 1) ? token : null;
153
+ },
154
+
155
+ async acquire(key: string, ttlMs: number = 30_000): Promise<boolean> {
156
+ const token = await this.acquireToken!(key, ttlMs);
157
+ if (!token) return false;
158
+ let q = lockTokens.get(key);
159
+ if (!q) { q = []; lockTokens.set(key, q); }
160
+ q.push(token);
161
+ return true;
144
162
  },
145
163
 
146
- async release(key: string): Promise<void> {
147
- await cmdDel(`${prefix}idem:lock:${key}`);
164
+ async release(key: string, tokenOverride?: string): Promise<void> {
165
+ const lockKey = `${prefix}idem:lock:${key}`;
166
+ let token = tokenOverride;
167
+ if (token === undefined) {
168
+ const q = lockTokens.get(key);
169
+ token = q?.pop();
170
+ if (q && q.length === 0) lockTokens.delete(key);
171
+ }
172
+ if (!token) return;
173
+ if (useSend) {
174
+ try {
175
+ await client.send('EVAL', [RELEASE_LUA, '1', lockKey, token]);
176
+ return;
177
+ } catch {
178
+ // Fallback if mock/client does not support EVAL
179
+ }
180
+ } else if (typeof client.eval === 'function') {
181
+ try {
182
+ await client.eval(RELEASE_LUA, 1, lockKey, token);
183
+ return;
184
+ } catch {
185
+ // Fallback if mock/client does not support eval
186
+ }
187
+ }
188
+ const current = await cmdGet(lockKey);
189
+ if (current === token) {
190
+ await cmdDel(lockKey);
191
+ }
148
192
  },
149
193
 
150
194
  async revoke(tokenOrJti: string, ttlMs: number): Promise<void> {
@@ -8,13 +8,15 @@ export interface TimeoutOptions {
8
8
  export const timeout = (ms = 10000, options: TimeoutOptions = {}): Middleware => {
9
9
  const status = options.status ?? 408;
10
10
  const message = options.message ?? 'Request Timeout';
11
+ const delayMs = Number.isFinite(ms) ? Math.min(Math.max(ms, 0), 2 ** 31 - 1) : 2 ** 31 - 1;
11
12
 
12
- const mw: Middleware = async (_ctx: Context, next: Next) => {
13
+ const mw: Middleware = async (ctx: Context, next: Next) => {
13
14
  let timer: ReturnType<typeof setTimeout> | undefined;
14
15
  try {
15
16
  const nextPromise = Promise.resolve(next());
16
17
  const timeoutPromise = new Promise<Response>((resolve) => {
17
18
  timer = setTimeout(() => {
19
+ ctx._detached = true;
18
20
  nextPromise.catch(() => {});
19
21
  resolve(
20
22
  Response.json(
@@ -22,13 +24,13 @@ export const timeout = (ms = 10000, options: TimeoutOptions = {}): Middleware =>
22
24
  { status }
23
25
  )
24
26
  );
25
- }, ms);
27
+ }, delayMs);
26
28
  });
27
29
  return await Promise.race([nextPromise, timeoutPromise]);
28
30
  } finally {
29
31
  if (timer !== undefined) clearTimeout(timer);
30
32
  }
31
33
  };
32
- (mw as any).__timeout = { ms, status, message };
34
+ (mw as any).__timeout = { ms: delayMs, status, message };
33
35
  return mw;
34
36
  };