@strutvane/redis 0.0.0-stage → 0.2.0-next.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.
@@ -0,0 +1,1626 @@
1
+ import { a as deleteMatching, i as defineLua, n as asInteger, r as asNullableString, t as asArray } from "./driver-DEW-Sggt.mjs";
2
+ import { BootError, IDEMPOTENCY_TTL_MS, createCacheManager } from "@strutvane/framework";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { createClient } from "@redis/client";
6
+ import { StrutvaneError, token } from "@strutvane/framework/core";
7
+ import { join } from "node:path";
8
+ import { parseEnv } from "node:util";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
+ // src/cache-store.ts
11
+ const INCREMENT = defineLua(`
12
+ local current = redis.call('GET', KEYS[1])
13
+ if current and string.match(current, '^%-?%d+$') then
14
+ return redis.call('INCRBY', KEYS[1], ARGV[1])
15
+ end
16
+ if ARGV[2] == '' then
17
+ redis.call('SET', KEYS[1], ARGV[1])
18
+ else
19
+ redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])
20
+ end
21
+ return tonumber(ARGV[1])
22
+ `);
23
+ const PUT_MANY = defineLua(`
24
+ for i, key in ipairs(KEYS) do
25
+ if ARGV[1] == '' then
26
+ redis.call('SET', key, ARGV[i + 1])
27
+ else
28
+ redis.call('SET', key, ARGV[i + 1], 'PX', ARGV[1])
29
+ end
30
+ end
31
+ return #KEYS
32
+ `);
33
+ /**
34
+ * A cache store in Redis or Valkey.
35
+ *
36
+ * @example
37
+ * const cache = new RedisCacheStore({ driver: redis, space: KeySpace.root('blog:').area('cache') })
38
+ * await cache.put('stats', { posts: 3 }, 60)
39
+ * await cache.forTenant('acme').get('stats') // undefined: another namespace
40
+ */
41
+ var RedisCacheStore = class RedisCacheStore {
42
+ #driver;
43
+ #space;
44
+ #logger;
45
+ constructor(options) {
46
+ this.#driver = options.driver;
47
+ this.#space = options.space;
48
+ this.#logger = options.logger;
49
+ }
50
+ /** The key prefix of this store (for diagnostics). */
51
+ get prefix() {
52
+ return this.#space.prefix;
53
+ }
54
+ /**
55
+ * The same store, scoped to one tenant.
56
+ *
57
+ * @example
58
+ * await Cache.store('redis').forTenant(tenant.id).remember('dashboard', 60, build)
59
+ */
60
+ forTenant(tenantId) {
61
+ return new RedisCacheStore({
62
+ driver: this.#driver,
63
+ space: this.#space.tenant(tenantId),
64
+ ...this.#logger === void 0 ? {} : { logger: this.#logger }
65
+ });
66
+ }
67
+ async get(key) {
68
+ return decode(asNullableString(await this.#driver.command(["GET", this.#space.key(key)])));
69
+ }
70
+ async has(key) {
71
+ return await this.get(key) !== void 0;
72
+ }
73
+ async put(key, value, ttlSeconds) {
74
+ const full = this.#space.key(key);
75
+ const encoded = encode(value);
76
+ const px = expiry(ttlSeconds);
77
+ if (px === "expired") {
78
+ await this.#driver.command(["UNLINK", full]);
79
+ return;
80
+ }
81
+ await this.#driver.command(px === void 0 ? [
82
+ "SET",
83
+ full,
84
+ encoded
85
+ ] : [
86
+ "SET",
87
+ full,
88
+ encoded,
89
+ "PX",
90
+ px
91
+ ]);
92
+ }
93
+ async add(key, value, ttlSeconds) {
94
+ const full = this.#space.key(key);
95
+ const encoded = encode(value);
96
+ const px = expiry(ttlSeconds);
97
+ if (px === "expired") return false;
98
+ const reply = await this.#driver.command(px === void 0 ? [
99
+ "SET",
100
+ full,
101
+ encoded,
102
+ "NX"
103
+ ] : [
104
+ "SET",
105
+ full,
106
+ encoded,
107
+ "NX",
108
+ "PX",
109
+ px
110
+ ]);
111
+ return reply !== null && reply !== void 0;
112
+ }
113
+ async increment(key, by = 1, ttlSeconds) {
114
+ if (!Number.isSafeInteger(by)) throw new TypeError("increment() takes a whole number (Redis counters are integers).");
115
+ const px = expiry(ttlSeconds);
116
+ if (px === "expired") throw new RangeError("increment() needs a ttlSeconds above 0, or none.");
117
+ return asInteger(await this.#driver.script(INCREMENT, [this.#space.key(key)], [String(by), px ?? ""]));
118
+ }
119
+ /**
120
+ * Subtract from a counter (see {@link RedisCacheStore.increment}).
121
+ *
122
+ * @example
123
+ * await cache.decrement('seats', 1)
124
+ */
125
+ async decrement(key, by = 1, ttlSeconds) {
126
+ return this.increment(key, -by, ttlSeconds);
127
+ }
128
+ async ttl(key) {
129
+ const ms = asInteger(await this.#driver.command(["PTTL", this.#space.key(key)]));
130
+ return ms < 0 ? void 0 : Math.ceil(ms / 1e3);
131
+ }
132
+ async forget(key) {
133
+ return asInteger(await this.#driver.command(["UNLINK", this.#space.key(key)])) > 0;
134
+ }
135
+ async flush() {
136
+ await deleteMatching(this.#driver, this.#space.pattern());
137
+ }
138
+ /**
139
+ * Several values at once (`MGET`); missing keys are `undefined`.
140
+ *
141
+ * @example
142
+ * const { a, b } = await cache.many(['a', 'b'])
143
+ */
144
+ async many(keys) {
145
+ const result = {};
146
+ if (keys.length === 0) return result;
147
+ const replies = asArray(await this.#driver.command(["MGET", ...keys.map((key) => this.#space.key(key))]));
148
+ keys.forEach((key, index) => {
149
+ result[key] = decode(asNullableString(replies[index]));
150
+ });
151
+ return result;
152
+ }
153
+ /**
154
+ * Store several values atomically with one expiry.
155
+ *
156
+ * @example
157
+ * await cache.putMany({ a: 1, b: 2 }, 60)
158
+ */
159
+ async putMany(values, ttlSeconds) {
160
+ const entries = Object.entries(values);
161
+ if (entries.length === 0) return;
162
+ const keys = entries.map(([key]) => this.#space.key(key));
163
+ const encoded = entries.map(([, value]) => encode(value));
164
+ const px = expiry(ttlSeconds);
165
+ if (px === "expired") {
166
+ await this.#driver.command(["UNLINK", ...keys]);
167
+ return;
168
+ }
169
+ await this.#driver.script(PUT_MANY, keys, [px ?? "", ...encoded]);
170
+ }
171
+ /**
172
+ * Store a value with no expiry.
173
+ *
174
+ * @example
175
+ * await cache.forever('settings', { theme: 'dark' })
176
+ */
177
+ async forever(key, value) {
178
+ await this.put(key, value);
179
+ }
180
+ /**
181
+ * The cached value, or compute, store and return it. `undefined` results are not cached.
182
+ *
183
+ * @example
184
+ * const posts = await cache.remember('posts:count', 60, () => Post.query().count())
185
+ */
186
+ async remember(key, ttlSeconds, compute) {
187
+ const cached = await this.get(key);
188
+ if (cached !== void 0) return cached;
189
+ const value = await compute();
190
+ if (value !== void 0) await this.put(key, value, ttlSeconds);
191
+ return value;
192
+ }
193
+ /**
194
+ * Stale-while-revalidate (Laravel's `Cache::flexible`): a value younger than `freshSeconds` is
195
+ * returned as is; one younger than `staleSeconds` is returned at once and refreshed in the
196
+ * background (one refresher at a time, across processes); an older or missing one is computed
197
+ * now.
198
+ *
199
+ * @example
200
+ * const stats = await cache.flexible('stats', [5, 60], () => computeStats())
201
+ */
202
+ async flexible(key, [freshSeconds, staleSeconds], compute) {
203
+ if (!(freshSeconds > 0 && staleSeconds > freshSeconds)) throw new RangeError("flexible() needs [fresh, stale] seconds with 0 < fresh < stale.");
204
+ const entry = asFlexible(await this.get(key));
205
+ const now = Date.now();
206
+ if (entry !== void 0) {
207
+ const age = now - entry.t;
208
+ if (age < freshSeconds * 1e3) return entry.v;
209
+ if (age < staleSeconds * 1e3) {
210
+ this.#refresh(key, staleSeconds, compute);
211
+ return entry.v;
212
+ }
213
+ }
214
+ const value = await compute();
215
+ await this.put(key, {
216
+ v: value,
217
+ t: Date.now()
218
+ }, staleSeconds);
219
+ return value;
220
+ }
221
+ async #refresh(key, staleSeconds, compute) {
222
+ const guard = `${key}:refreshing`;
223
+ try {
224
+ if (!await this.add(guard, 1, Math.min(staleSeconds, 30))) return;
225
+ try {
226
+ const value = await compute();
227
+ await this.put(key, {
228
+ v: value,
229
+ t: Date.now()
230
+ }, staleSeconds);
231
+ } finally {
232
+ await this.forget(guard);
233
+ }
234
+ } catch (error) {
235
+ this.#logger?.warn("redis.cache.refresh_failed", {
236
+ key,
237
+ error
238
+ });
239
+ }
240
+ }
241
+ };
242
+ /** Milliseconds for `PX`, `undefined` for "forever", or `'expired'` for a ttl of 0 or less. */
243
+ function expiry(ttlSeconds) {
244
+ if (ttlSeconds === void 0) return void 0;
245
+ if (!Number.isFinite(ttlSeconds)) throw new RangeError("ttlSeconds must be a finite number.");
246
+ if (ttlSeconds <= 0) return "expired";
247
+ return String(Math.max(1, Math.round(ttlSeconds * 1e3)));
248
+ }
249
+ function encode(value) {
250
+ const encoded = JSON.stringify(value);
251
+ if (encoded === void 0) throw new TypeError("Cache values must be JSON-serialisable (not undefined, a function or a symbol).");
252
+ return encoded;
253
+ }
254
+ function decode(raw) {
255
+ if (raw === null) return void 0;
256
+ try {
257
+ return JSON.parse(raw);
258
+ } catch {
259
+ return;
260
+ }
261
+ }
262
+ function asFlexible(value) {
263
+ if (typeof value !== "object" || value === null || !("t" in value) || !("v" in value)) return void 0;
264
+ return typeof value.t === "number" ? value : void 0;
265
+ }
266
+ // src/cache-manager.ts
267
+ /**
268
+ * The cache manager with Redis stores: the framework's manager (memory and file stores, from
269
+ * `config/cache.ts`) plus every store whose driver is `redis`. The provider binds it as
270
+ * `CacheManagerToken`, so `Cache`, `node strut cache:clear --store=redis` and (with
271
+ * `CACHE_STORE=redis`) the `throttle` middleware all use Redis.
272
+ *
273
+ * ```ts
274
+ * // config/cache.ts
275
+ * stores: {
276
+ * file: { driver: 'file', path: 'storage/framework/cache' },
277
+ * redis: { driver: 'redis' }, // keys: <prefix>cache:…
278
+ * reports: { driver: 'redis', area: 'reports' }, // keys: <prefix>reports:…
279
+ * }
280
+ * ```
281
+ *
282
+ * A `redis` store always exists (like `memory` and `file`), so `CACHE_STORE=redis` works without
283
+ * editing `config/cache.ts`. A bad store entry stops boot with a friendly error.
284
+ *
285
+ * @module
286
+ */
287
+ /**
288
+ * Build the cache manager with Redis stores.
289
+ *
290
+ * @example
291
+ * const cache = createRedisCacheManager(options)
292
+ * await cache.store('redis').put('k', 1, 60)
293
+ */
294
+ function createRedisCacheManager(options) {
295
+ const { defaultStore, frameworkStores, redisStores } = split(options.config);
296
+ const framework = createCacheManager({
297
+ basePath: options.basePath,
298
+ clock: options.clock,
299
+ config: {
300
+ default: "memory",
301
+ stores: frameworkStores
302
+ }
303
+ });
304
+ const names = [.../* @__PURE__ */ new Set([...framework.storeNames, ...redisStores.keys()])].sort();
305
+ if (!names.includes(defaultStore)) throw unknownStore(defaultStore, names);
306
+ const created = /* @__PURE__ */ new Map();
307
+ return {
308
+ defaultStore,
309
+ storeNames: names,
310
+ store(name = defaultStore) {
311
+ const area = redisStores.get(name);
312
+ if (area === void 0) {
313
+ if (!names.includes(name)) throw unknownStore(name, names);
314
+ return framework.store(name);
315
+ }
316
+ let store = created.get(name);
317
+ if (store === void 0) {
318
+ store = new RedisCacheStore({
319
+ driver: options.driver(),
320
+ space: options.root.area(area),
321
+ ...options.logger === void 0 ? {} : { logger: options.logger }
322
+ });
323
+ created.set(name, store);
324
+ }
325
+ return store;
326
+ }
327
+ };
328
+ }
329
+ function split(value) {
330
+ if (value === void 0 || value === null) return {
331
+ defaultStore: "memory",
332
+ frameworkStores: {},
333
+ redisStores: /* @__PURE__ */ new Map([["redis", "cache"]])
334
+ };
335
+ if (typeof value !== "object" || Array.isArray(value)) throw invalid$1("config/cache.ts must export an object such as { default, stores }.");
336
+ const record = value;
337
+ const name = record["default"];
338
+ if (name !== void 0 && typeof name !== "string") throw invalid$1("cache.default must be a store name.");
339
+ const raw = record["stores"] ?? {};
340
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalid$1("cache.stores must map store names to { driver }.");
341
+ const frameworkStores = {};
342
+ const redisStores = /* @__PURE__ */ new Map([["redis", "cache"]]);
343
+ for (const [store, entry] of Object.entries(raw)) {
344
+ if ((typeof entry === "object" && entry !== null ? entry.driver : entry) !== "redis") {
345
+ redisStores.delete(store);
346
+ frameworkStores[store] = entry;
347
+ continue;
348
+ }
349
+ const options = typeof entry === "object" && entry !== null ? entry : {};
350
+ const area = options.area ?? "cache";
351
+ if (typeof area !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(area)) throw invalid$1(`cache.stores.${store}.area must be a short lowercase name (letters, digits, _ and -, starting with a letter).`);
352
+ for (const key of Object.keys(options)) if (key !== "driver" && key !== "area") throw invalid$1(`cache.stores.${store} has an unknown key "${key}" (a redis store takes driver and area).`);
353
+ redisStores.set(store, area);
354
+ }
355
+ return {
356
+ defaultStore: name ?? "memory",
357
+ frameworkStores,
358
+ redisStores
359
+ };
360
+ }
361
+ function invalid$1(message) {
362
+ return new BootError("invalid_cache_config", message, "Example: stores: { redis: { driver: 'redis' }, file: { driver: 'file' } } and CACHE_STORE=redis in .env.");
363
+ }
364
+ function unknownStore(name, names) {
365
+ return new BootError("unknown_cache_store", `There is no "${name}" cache store.`, `The stores are: ${names.join(", ")} (config/cache.ts).`);
366
+ }
367
+ // src/keys.ts
368
+ /**
369
+ * Key spaces: every key this package writes is `<app prefix><area>:<key>`, optionally with a
370
+ * tenant segment, `<app prefix><area>:t:<tenant>:<key>`.
371
+ *
372
+ * **Why:** one Redis is often shared by several apps (and several environments of one app), and a
373
+ * multi-tenant app must never let tenant A read, overwrite or flush tenant B's entries. Prefixes
374
+ * are how Redis users isolate data; this module makes them impossible to get wrong:
375
+ *
376
+ * - **Tenant ids are validated, not escaped.** A tenant id may only contain letters, digits, `_`
377
+ * and `-` (UUIDs, ULIDs, slugs and numbers fit). A tenant called `a:t:b` could otherwise reach
378
+ * into another tenant's namespace, so anything else is refused (fail closed).
379
+ * - **The tenant marker can't be forged from a key.** The tenant segment is `t:<id>:`, and a
380
+ * global (non-tenant) key may not start with `t:`, so a global key can never alias a tenant key.
381
+ * - **Flushing matches the prefix literally.** `SCAN MATCH` takes a glob, so `*`, `?`, `[`, `]`
382
+ * and `\` in a prefix are escaped; an app prefixed `a*` can't flush app `ab`'s keys.
383
+ * - **Keys are bounded.** Empty keys and keys over 1 KiB are refused: long keys are almost always
384
+ * a bug (a whole payload used as a key) and cost memory on every lookup.
385
+ *
386
+ * Keys travel as RESP bulk strings (length-prefixed), so a key containing CR/LF or spaces cannot
387
+ * inject a command; such keys are stored literally.
388
+ *
389
+ * @module
390
+ */
391
+ /** The longest key (in UTF-8 bytes) this package accepts from callers. */
392
+ const MAX_KEY_BYTES = 1024;
393
+ const TENANT_ID = /^[A-Za-z0-9_-]{1,128}$/;
394
+ const SEGMENT = /^[a-z][a-z0-9_-]{0,31}$/;
395
+ const PREFIX = /^[A-Za-z0-9_.:-]{0,128}$/;
396
+ const TENANT_MARKER = "t:";
397
+ /**
398
+ * Check an app prefix (`REDIS_PREFIX`): letters, digits and `_ . : -`, at most 128 characters.
399
+ * Returns an error message, or `undefined` when it is fine.
400
+ *
401
+ * @example
402
+ * prefixProblem('blog:') // undefined
403
+ * prefixProblem('a b') // 'may only contain …'
404
+ */
405
+ function prefixProblem(prefix) {
406
+ return PREFIX.test(prefix) ? void 0 : "may only contain letters, digits and _ . : - (at most 128 characters)";
407
+ }
408
+ /**
409
+ * Whether a tenant id can be used in a key (letters, digits, `_` and `-`; 1 to 128 characters).
410
+ *
411
+ * @example
412
+ * isValidTenantId('acme-1') // true
413
+ * isValidTenantId('a:t:b') // false
414
+ */
415
+ function isValidTenantId(id) {
416
+ return TENANT_ID.test(id);
417
+ }
418
+ /**
419
+ * Escape a literal string for a Redis glob pattern (`SCAN MATCH`, `KEYS`).
420
+ *
421
+ * @example
422
+ * globEscape('app*[1]') // 'app\\*\\[1\\]'
423
+ */
424
+ function globEscape(literal) {
425
+ return literal.replace(/[*?[\]\\]/g, (char) => `\\${char}`);
426
+ }
427
+ /**
428
+ * A namespace of keys. Immutable: {@link KeySpace.area} and {@link KeySpace.tenant} return new
429
+ * spaces.
430
+ *
431
+ * @example
432
+ * const cache = KeySpace.root('blog:').area('cache')
433
+ * cache.key('posts') // 'blog:cache:posts'
434
+ * cache.tenant('acme').key('posts') // 'blog:cache:t:acme:posts'
435
+ */
436
+ var KeySpace = class KeySpace {
437
+ /** The full prefix every key of this space starts with. */
438
+ prefix;
439
+ /** The tenant this space is scoped to, if any. */
440
+ tenantId;
441
+ #areaPrefix;
442
+ constructor(areaPrefix, tenantId) {
443
+ this.#areaPrefix = areaPrefix;
444
+ this.tenantId = tenantId;
445
+ this.prefix = tenantId === void 0 ? areaPrefix : `${areaPrefix}${TENANT_MARKER}${tenantId}:`;
446
+ }
447
+ /**
448
+ * The app-wide root (no area yet). Throws a `TypeError` for an invalid prefix.
449
+ *
450
+ * @example
451
+ * KeySpace.root('blog:')
452
+ */
453
+ static root(appPrefix) {
454
+ const problem = prefixProblem(appPrefix);
455
+ if (problem !== void 0) throw new TypeError(`The Redis key prefix ${problem}.`);
456
+ return new KeySpace(appPrefix, void 0);
457
+ }
458
+ /**
459
+ * A sub-area (`cache`, `lock`, `session`, …): lowercase, starting with a letter.
460
+ *
461
+ * @example
462
+ * KeySpace.root('blog:').area('lock').key('reports') // 'blog:lock:reports'
463
+ */
464
+ area(name) {
465
+ if (!SEGMENT.test(name)) throw new TypeError(`"${name}" is not a valid key area: use lowercase letters, digits, _ and - (starting with a letter).`);
466
+ if (this.tenantId !== void 0) throw new TypeError("Choose the area before the tenant: space.area(name).tenant(id).");
467
+ return new KeySpace(`${this.#areaPrefix}${name}:`, void 0);
468
+ }
469
+ /**
470
+ * The same area scoped to one tenant. Throws a `TypeError` for an id that could escape its
471
+ * namespace (see the module notes); re-scoping a tenant space is refused too.
472
+ *
473
+ * @example
474
+ * space.tenant('acme').key('stats') // '<prefix>t:acme:stats'
475
+ */
476
+ tenant(id) {
477
+ if (this.tenantId !== void 0) throw new TypeError("This key space is already scoped to a tenant.");
478
+ if (!isValidTenantId(id)) throw new TypeError("A tenant id used in Redis keys may only contain letters, digits, _ and - (1 to 128 characters).");
479
+ return new KeySpace(this.#areaPrefix, id);
480
+ }
481
+ /**
482
+ * The full key for `key`. Throws a `TypeError` for an empty or over-long key, or (in the global
483
+ * space) a key that starts with the tenant marker `t:`.
484
+ *
485
+ * @example
486
+ * KeySpace.root('blog:').area('cache').key('posts:1') // 'blog:cache:posts:1'
487
+ */
488
+ key(key) {
489
+ if (typeof key !== "string" || key.length === 0) throw new TypeError("A Redis key must be a non-empty string.");
490
+ if (Buffer.byteLength(key, "utf8") > 1024) throw new TypeError(`A Redis key may be at most ${MAX_KEY_BYTES} bytes.`);
491
+ if (this.tenantId === void 0 && key.startsWith(TENANT_MARKER)) throw new TypeError("Keys starting with \"t:\" are reserved for tenant scopes; use space.tenant(id).key(...).");
492
+ return `${this.prefix}${key}`;
493
+ }
494
+ /**
495
+ * The `SCAN MATCH` pattern for every key in this space (and, for a global space, every tenant's
496
+ * keys under it too: flushing an area clears it for all tenants).
497
+ *
498
+ * @example
499
+ * KeySpace.root('a*:').area('cache').pattern() // 'a\\*:cache:*'
500
+ */
501
+ pattern() {
502
+ return `${globEscape(this.prefix)}*`;
503
+ }
504
+ };
505
+ // src/config.ts
506
+ /**
507
+ * Connection settings: `config/redis.ts` (or Laravel's spot, `config/database.ts` → `redis`) plus
508
+ * the `REDIS_*` variables in `.env`.
509
+ *
510
+ * | Setting | Config key | Variable | Default |
511
+ * |---|---|---|---|
512
+ * | Full URL (`redis://` or `rediss://`) | none (secret) | `REDIS_URL` | not set |
513
+ * | Host | `host` | `REDIS_HOST` | `127.0.0.1` |
514
+ * | Port | `port` | `REDIS_PORT` | `6379` |
515
+ * | ACL user | `username` | `REDIS_USERNAME` | not set (the `default` user) |
516
+ * | Password | none (secret) | `REDIS_PASSWORD` | not set |
517
+ * | Database number | `database` | `REDIS_DB` | `0` |
518
+ * | TLS | `tls` | `REDIS_TLS` | `false` (`true` for `rediss://`) |
519
+ * | CA file for TLS | `tls_ca` | `REDIS_TLS_CA` | the system CAs |
520
+ * | TLS server name | `tls_servername` | `REDIS_TLS_SERVERNAME` | the host |
521
+ * | Key prefix | `prefix` | `REDIS_PREFIX` | the app name as a slug, then `:` |
522
+ * | Connect timeout | `connect_timeout` | `REDIS_CONNECT_TIMEOUT` | `5000` ms |
523
+ * | Command timeout | `command_timeout` | `REDIS_COMMAND_TIMEOUT` | `5000` ms |
524
+ *
525
+ * **Why the password and URL are never config keys:** the config tree is kept for every request,
526
+ * written to `bootstrap/cache` by `node strut config:cache` and easy to dump while debugging (the
527
+ * same reason `config/database.ts` leaves out `DB_PASSWORD`). They are read from the environment
528
+ * only when the connection opens.
529
+ *
530
+ * **Fail closed:** a bad value (a port of `abc`, an unknown URL scheme, `REDIS_TLS=false` with a
531
+ * `rediss://` URL) stops boot with `invalid_redis_config` instead of connecting somewhere
532
+ * unexpected or in plain text. TLS always verifies the server certificate; there is no switch to
533
+ * turn verification off.
534
+ *
535
+ * @module
536
+ */
537
+ const DEFAULT_TIMEOUT_MS = 5e3;
538
+ const MAX_TIMEOUT_MS = 6e5;
539
+ const CONFIG_KEYS = /* @__PURE__ */ new Set([
540
+ "host",
541
+ "port",
542
+ "username",
543
+ "database",
544
+ "tls",
545
+ "tls_ca",
546
+ "tls_servername",
547
+ "prefix",
548
+ "connect_timeout",
549
+ "command_timeout"
550
+ ]);
551
+ const SECRET_CONFIG_KEYS = /* @__PURE__ */ new Set(["password", "url"]);
552
+ /**
553
+ * Resolve and check the settings. Config keys win over variables (the config file usually reads
554
+ * the same variables); `REDIS_URL` wins over the separate host, port, user, password and database.
555
+ *
556
+ * @example
557
+ * resolveRedisSettings({ env: { REDIS_URL: 'rediss://app:secret@cache.example.com:6380/2' } })
558
+ * // { host: 'cache.example.com', port: 6380, username: 'app', database: 2, tls: true, … }
559
+ */
560
+ function resolveRedisSettings(options) {
561
+ const config = readConfig(options.config);
562
+ const env = options.env;
563
+ const pick = (key, variable) => {
564
+ const fromConfig = config[key];
565
+ if (fromConfig !== void 0 && String(fromConfig).trim() !== "") return String(fromConfig);
566
+ const fromEnv = env[variable];
567
+ return fromEnv === void 0 || fromEnv.trim() === "" ? void 0 : fromEnv.trim();
568
+ };
569
+ let host = pick("host", "REDIS_HOST") ?? "127.0.0.1";
570
+ let port = integer(pick("port", "REDIS_PORT"), "REDIS_PORT", 6379, 1, 65535);
571
+ let username = pick("username", "REDIS_USERNAME");
572
+ let password = nonEmpty(env["REDIS_PASSWORD"]);
573
+ let database = integer(pick("database", "REDIS_DB"), "REDIS_DB", 0, 0, 1023);
574
+ const tlsSetting = pick("tls", "REDIS_TLS");
575
+ let tls = tlsSetting === void 0 ? false : flag(tlsSetting, "REDIS_TLS");
576
+ const url = nonEmpty(env["REDIS_URL"]);
577
+ if (url !== void 0) {
578
+ const parsed = parseUrl(url);
579
+ if (parsed.tls === true && tlsSetting !== void 0 && !tls) throw invalid("REDIS_TLS is false but REDIS_URL uses rediss:// (TLS).", "Remove REDIS_TLS, or set it to true. A TLS URL is never downgraded to plain text.");
580
+ host = parsed.host;
581
+ port = parsed.port;
582
+ username = parsed.username ?? username;
583
+ password = parsed.password ?? password;
584
+ database = parsed.database ?? database;
585
+ tls = tls || parsed.tls;
586
+ }
587
+ const prefix = pick("prefix", "REDIS_PREFIX") ?? defaultPrefix(options.appName ?? env["APP_NAME"]);
588
+ const problem = prefixProblem(prefix);
589
+ if (problem !== void 0) throw invalid(`REDIS_PREFIX ${problem}.`, "Example: REDIS_PREFIX=blog: (one prefix per app).");
590
+ return Object.freeze({
591
+ host,
592
+ port,
593
+ username,
594
+ password,
595
+ database,
596
+ tls,
597
+ tlsCaFile: pick("tls_ca", "REDIS_TLS_CA"),
598
+ tlsServername: pick("tls_servername", "REDIS_TLS_SERVERNAME"),
599
+ prefix,
600
+ connectTimeoutMs: integer(pick("connect_timeout", "REDIS_CONNECT_TIMEOUT"), "REDIS_CONNECT_TIMEOUT", DEFAULT_TIMEOUT_MS, 1, MAX_TIMEOUT_MS),
601
+ commandTimeoutMs: integer(pick("command_timeout", "REDIS_COMMAND_TIMEOUT"), "REDIS_COMMAND_TIMEOUT", DEFAULT_TIMEOUT_MS, 1, MAX_TIMEOUT_MS)
602
+ });
603
+ }
604
+ /**
605
+ * A log-safe description of the settings: no password, no URL.
606
+ *
607
+ * @example
608
+ * logger.info('redis.connecting', describeSettings(settings))
609
+ */
610
+ function describeSettings(settings) {
611
+ return {
612
+ host: settings.host,
613
+ port: settings.port,
614
+ database: settings.database,
615
+ tls: settings.tls,
616
+ acl_user: settings.username ?? "default",
617
+ authenticated: settings.password !== void 0,
618
+ prefix: settings.prefix
619
+ };
620
+ }
621
+ /**
622
+ * The default key prefix: the app name as a lowercase slug, then `:` (`My Blog` → `my_blog:`).
623
+ *
624
+ * @example
625
+ * defaultPrefix('My Blog') // 'my_blog:'
626
+ */
627
+ function defaultPrefix(appName) {
628
+ const slug = (appName ?? "").normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64);
629
+ return `${slug === "" ? "strutvane" : slug}:`;
630
+ }
631
+ function parseUrl(text) {
632
+ let url;
633
+ try {
634
+ url = new URL(text);
635
+ } catch {
636
+ throw invalid("REDIS_URL is not a valid URL.", "Example: REDIS_URL=redis://user:pass@host:6379/0");
637
+ }
638
+ if (url.protocol !== "redis:" && url.protocol !== "rediss:") throw invalid(`REDIS_URL must start with redis:// or rediss:// (it starts with ${url.protocol}//).`, "Use rediss:// for TLS. Unix sockets and Sentinel/cluster URLs are not supported yet.");
639
+ if (url.hostname === "") throw invalid("REDIS_URL has no host.", "Example: REDIS_URL=redis://127.0.0.1:6379/0");
640
+ const path = url.pathname.replace(/^\//, "");
641
+ const database = path === "" ? void 0 : integer(path, "the database number in REDIS_URL", 0, 0, 1023);
642
+ return {
643
+ host: url.hostname.replace(/^\[|\]$/g, ""),
644
+ port: integer(url.port === "" ? void 0 : url.port, "the port in REDIS_URL", 6379, 1, 65535),
645
+ username: url.username === "" ? void 0 : safeDecode(url.username),
646
+ password: url.password === "" ? void 0 : safeDecode(url.password),
647
+ database,
648
+ tls: url.protocol === "rediss:"
649
+ };
650
+ }
651
+ function safeDecode(value) {
652
+ try {
653
+ return decodeURIComponent(value);
654
+ } catch {
655
+ throw invalid("REDIS_URL has a badly encoded user name or password.", "Percent-encode special characters in the user name and password (encodeURIComponent).");
656
+ }
657
+ }
658
+ function readConfig(value) {
659
+ if (value === void 0 || value === null) return {};
660
+ if (typeof value !== "object" || Array.isArray(value)) throw invalid("The redis config must be an object such as { host, port, prefix }.", "Example: defineConfig((env) => ({ host: env.string('REDIS_HOST', '127.0.0.1') }))");
661
+ const record = value;
662
+ for (const key of Object.keys(record)) {
663
+ if (SECRET_CONFIG_KEYS.has(key)) throw invalid(`The redis config must not contain "${key}".`, `Keep secrets out of the config tree: set ${key === "url" ? "REDIS_URL" : "REDIS_PASSWORD"} in .env; it is read when the connection opens.`);
664
+ if (!CONFIG_KEYS.has(key)) throw invalid(`The redis config has an unknown key "${key}".`, `Known keys: ${[...CONFIG_KEYS].join(", ")}.`);
665
+ const item = record[key];
666
+ if (item !== void 0 && ![
667
+ "string",
668
+ "number",
669
+ "boolean"
670
+ ].includes(typeof item)) throw invalid(`redis.${key} must be a string, number or boolean.`, "Read it with env.string(...).");
671
+ }
672
+ return record;
673
+ }
674
+ function nonEmpty(value) {
675
+ return value === void 0 || value === "" ? void 0 : value;
676
+ }
677
+ function integer(value, name, fallback, min, max) {
678
+ if (value === void 0) return fallback;
679
+ const trimmed = value.trim();
680
+ const parsed = /^\d+$/.test(trimmed) ? Number(trimmed) : NaN;
681
+ if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) throw invalid(`${name} must be a whole number from ${min} to ${max}.`, `It is ${JSON.stringify(trimmed.slice(0, 20))}.`);
682
+ return parsed;
683
+ }
684
+ function flag(value, name) {
685
+ const normalised = value.trim().toLowerCase();
686
+ if ([
687
+ "true",
688
+ "1",
689
+ "yes",
690
+ "on"
691
+ ].includes(normalised)) return true;
692
+ if ([
693
+ "false",
694
+ "0",
695
+ "no",
696
+ "off"
697
+ ].includes(normalised)) return false;
698
+ throw invalid(`${name} must be true or false.`, `It is ${JSON.stringify(value.slice(0, 10))}.`);
699
+ }
700
+ function invalid(message, hint) {
701
+ return new BootError("invalid_redis_config", message, hint);
702
+ }
703
+ // src/errors.ts
704
+ /** The package name, recorded as the owner of each error code. */
705
+ const PACKAGE_NAME = "@strutvane/redis";
706
+ /**
707
+ * The error definitions the provider registers.
708
+ *
709
+ * @example
710
+ * for (const definition of REDIS_ERRORS) registry.register(definition)
711
+ */
712
+ const REDIS_ERRORS = Object.freeze([Object.freeze({
713
+ code: "redis_unavailable",
714
+ status: 503,
715
+ title: "Service temporarily unavailable",
716
+ owner: PACKAGE_NAME
717
+ }), Object.freeze({
718
+ code: "lock_timeout",
719
+ status: 503,
720
+ title: "Resource busy",
721
+ owner: PACKAGE_NAME
722
+ })]);
723
+ /**
724
+ * The English message catalog for the codes above (RFC-0003 keys).
725
+ *
726
+ * @example
727
+ * REDIS_MESSAGES_EN['errors.lock_timeout.detail']
728
+ */
729
+ const REDIS_MESSAGES_EN = Object.freeze({
730
+ "errors.redis_unavailable.title": "Service temporarily unavailable",
731
+ "errors.redis_unavailable.detail": "The server is busy. Please try again in a moment.",
732
+ "errors.lock_timeout.title": "Resource busy",
733
+ "errors.lock_timeout.detail": "Someone else is working on this right now. Please try again."
734
+ });
735
+ /**
736
+ * A 503 `redis_unavailable` error. The cause stays on the error for the log, never for the client.
737
+ *
738
+ * @example
739
+ * throw redisUnavailable('connect', cause)
740
+ */
741
+ function redisUnavailable(operation, cause) {
742
+ return new StrutvaneError("redis_unavailable", {
743
+ status: 503,
744
+ params: { operation },
745
+ headers: { "Retry-After": "1" },
746
+ ...cause === void 0 ? {} : { cause }
747
+ });
748
+ }
749
+ /**
750
+ * A 503 `lock_timeout` error for the lock `name` (the name is the app's own key, never a secret).
751
+ *
752
+ * @example
753
+ * throw lockTimeout('reports:build', 10)
754
+ */
755
+ function lockTimeout(name, waitedSeconds) {
756
+ return new StrutvaneError("lock_timeout", {
757
+ status: 503,
758
+ params: {
759
+ lock: name,
760
+ waited_seconds: waitedSeconds
761
+ },
762
+ headers: { "Retry-After": "1" }
763
+ });
764
+ }
765
+ // src/connection.ts
766
+ /**
767
+ * The Redis connection: node-redis (`@redis/client`) behind the {@link RedisDriver} seam.
768
+ *
769
+ * **Why `@redis/client`:** it is the official, MIT-licensed client maintained by Redis Inc., works
770
+ * with Valkey (same protocol), supports TLS, ACL users, RESP3, Sentinel and cluster, and has **no
771
+ * runtime dependencies** (its two peers, OpenTelemetry and a hash library, are optional), so it
772
+ * adds nothing to the supply chain beyond itself. `ioredis` is in maintenance mode and pulls six
773
+ * dependencies.
774
+ *
775
+ * **Behaviour (and the failure scenarios it handles):**
776
+ * - **Lazy:** nothing connects until the first command, so `node strut make:*` and other commands
777
+ * that never touch Redis work while it is down.
778
+ * - **Fails fast while down:** the offline queue is off, so a command during an outage fails at
779
+ * once with the 503 `redis_unavailable` problem instead of piling up in memory. After a failed
780
+ * connect, new attempts wait `retryAfterMs` (a small circuit breaker), so a dead server doesn't
781
+ * make every request wait the full connect timeout.
782
+ * - **Reconnects:** once connected, a dropped socket reconnects with capped, jittered backoff.
783
+ * - **Bounded commands:** every command has a timeout (`REDIS_COMMAND_TIMEOUT`).
784
+ * - **Login failures fail closed:** a wrong password or a missing ACL permission is
785
+ * `redis_unavailable` for the caller and an error in the log (never the password).
786
+ * - **Graceful shutdown:** {@link RedisConnection.close} waits for pending replies, at most
787
+ * `closeTimeoutMs`, then drops the socket. Commands after close fail with `redis_unavailable`.
788
+ * - **TLS** always verifies the certificate (system CAs, or `REDIS_TLS_CA`).
789
+ *
790
+ * Sentinel and cluster are not wired yet (see README, "Not built yet"): node-redis supports both,
791
+ * and they will plug in behind the same {@link RedisDriver}.
792
+ *
793
+ * @module
794
+ */
795
+ /** Server error prefixes that mean "you may not": wrong login or missing ACL permission. */
796
+ const AUTH_ERRORS = /^(WRONGPASS|NOAUTH|NOPERM)\b/;
797
+ /** Socket error codes that may only appear in the message (node-redis wraps some errors). */
798
+ const NETWORK_ERROR = /\bE(?:CONNREFUSED|CONNRESET|TIMEDOUT|NOTFOUND|PIPE|HOSTUNREACH|NETUNREACH|AI_AGAIN)\b/;
799
+ /** Client-side error names that mean "the server is not reachable right now". */
800
+ const UNREACHABLE = /* @__PURE__ */ new Set([
801
+ "ClientClosedError",
802
+ "ClientOfflineError",
803
+ "ConnectionTimeoutError",
804
+ "SocketTimeoutError",
805
+ "TimeoutError",
806
+ "SocketClosedUnexpectedlyError",
807
+ "DisconnectsClientError",
808
+ "ReconnectStrategyError",
809
+ "AbortError"
810
+ ]);
811
+ /**
812
+ * One lazily opened connection, shared by every store of an app.
813
+ *
814
+ * @example
815
+ * const redis = new RedisConnection(resolveRedisSettings({ env: process.env }))
816
+ * await redis.command(['SET', 'k', 'v'])
817
+ * await redis.close()
818
+ */
819
+ var RedisConnection = class {
820
+ settings;
821
+ #logger;
822
+ #closeTimeoutMs;
823
+ #retryAfterMs;
824
+ #createClient;
825
+ #client;
826
+ #connecting;
827
+ #everReady = false;
828
+ #closed = false;
829
+ #failedAt;
830
+ #down = false;
831
+ constructor(settings, options = {}) {
832
+ this.settings = settings;
833
+ this.#logger = options.logger;
834
+ this.#closeTimeoutMs = options.closeTimeoutMs ?? 2e3;
835
+ this.#retryAfterMs = options.retryAfterMs ?? 1e3;
836
+ this.#createClient = options.createClient ?? ((clientOptions) => createClient(clientOptions));
837
+ }
838
+ /** Whether {@link RedisConnection.close} has been called. */
839
+ get closed() {
840
+ return this.#closed;
841
+ }
842
+ async command(args) {
843
+ const client = await this.#ready();
844
+ try {
845
+ return await client.sendCommand(args, { timeout: this.settings.commandTimeoutMs });
846
+ } catch (error) {
847
+ throw this.#translate(error, args[0] ?? "command");
848
+ }
849
+ }
850
+ async script(script, keys, args) {
851
+ const tail = [
852
+ String(keys.length),
853
+ ...keys,
854
+ ...args
855
+ ];
856
+ try {
857
+ return await this.command([
858
+ "EVALSHA",
859
+ script.sha1,
860
+ ...tail
861
+ ]);
862
+ } catch (error) {
863
+ if (error instanceof Error && error.message.startsWith("NOSCRIPT")) return this.command([
864
+ "EVAL",
865
+ script.source,
866
+ ...tail
867
+ ]);
868
+ throw error;
869
+ }
870
+ }
871
+ async ping() {
872
+ const started = performance.now();
873
+ await this.command(["PING"]);
874
+ return Math.max(0, Math.round((performance.now() - started) * 100) / 100);
875
+ }
876
+ /**
877
+ * A health check for readiness probes: never throws.
878
+ *
879
+ * @example
880
+ * const health = await redis.health() // { status: 'up', latency_ms: 0.4 }
881
+ */
882
+ async health() {
883
+ try {
884
+ return {
885
+ status: "up",
886
+ latency_ms: await this.ping()
887
+ };
888
+ } catch (error) {
889
+ const code = error.code;
890
+ return {
891
+ status: "down",
892
+ error: typeof code === "string" ? code : "redis_unavailable"
893
+ };
894
+ }
895
+ }
896
+ async close() {
897
+ if (this.#closed) return;
898
+ this.#closed = true;
899
+ const pending = this.#connecting;
900
+ let client = this.#client;
901
+ if (client === void 0 && pending !== void 0) client = await pending.catch(() => void 0);
902
+ this.#client = void 0;
903
+ if (client === void 0 || !client.isOpen) return;
904
+ let timer;
905
+ const timedOut = new Promise((resolve) => {
906
+ timer = setTimeout(() => resolve("timeout"), this.#closeTimeoutMs);
907
+ });
908
+ try {
909
+ if (await Promise.race([client.close().then(() => "closed"), timedOut]) === "timeout") {
910
+ this.#logger?.warn("redis.close_timeout", { timeout_ms: this.#closeTimeoutMs });
911
+ client.destroy();
912
+ }
913
+ } catch {
914
+ client.destroy();
915
+ } finally {
916
+ clearTimeout(timer);
917
+ }
918
+ this.#logger?.debug("redis.closed");
919
+ }
920
+ async #ready() {
921
+ if (this.#closed) throw redisUnavailable("closed");
922
+ const client = this.#client;
923
+ if (client?.isReady === true) return client;
924
+ if (client?.isOpen === true) throw redisUnavailable("reconnecting");
925
+ if (this.#connecting !== void 0) return this.#connecting;
926
+ if (this.#failedAt !== void 0 && Date.now() - this.#failedAt < this.#retryAfterMs) throw redisUnavailable("connect");
927
+ this.#connecting = this.#open().finally(() => {
928
+ this.#connecting = void 0;
929
+ });
930
+ return this.#connecting;
931
+ }
932
+ async #open() {
933
+ const client = this.#createClient(this.#clientOptions());
934
+ client.on("error", (error) => this.#onError(error));
935
+ try {
936
+ await client.connect();
937
+ } catch (error) {
938
+ this.#failedAt = Date.now();
939
+ try {
940
+ client.destroy();
941
+ } catch {}
942
+ this.#markDown(error);
943
+ const translated = this.#translate(error, "connect");
944
+ throw translated instanceof StrutvaneError ? translated : redisUnavailable("connect", error);
945
+ }
946
+ if (this.#closed) {
947
+ client.destroy();
948
+ throw redisUnavailable("closed");
949
+ }
950
+ this.#client = client;
951
+ this.#everReady = true;
952
+ this.#failedAt = void 0;
953
+ if (this.#down) this.#logger?.info("redis.reconnected", describeSettings(this.settings));
954
+ else this.#logger?.debug("redis.connected", describeSettings(this.settings));
955
+ this.#down = false;
956
+ return client;
957
+ }
958
+ #clientOptions() {
959
+ const s = this.settings;
960
+ const socket = {
961
+ host: s.host,
962
+ port: s.port,
963
+ connectTimeout: s.connectTimeoutMs,
964
+ reconnectStrategy: (retries, cause) => this.#everReady && !this.#closed ? Math.min(2e3, 50 * 2 ** Math.min(retries, 6)) + Math.floor(Math.random() * 50) : cause
965
+ };
966
+ if (s.tls) {
967
+ socket["tls"] = true;
968
+ socket["rejectUnauthorized"] = true;
969
+ if (s.tlsServername !== void 0) socket["servername"] = s.tlsServername;
970
+ if (s.tlsCaFile !== void 0) socket["ca"] = readCa(s.tlsCaFile);
971
+ }
972
+ return {
973
+ socket,
974
+ ...s.username === void 0 ? {} : { username: s.username },
975
+ ...s.password === void 0 ? {} : { password: s.password },
976
+ database: s.database,
977
+ disableOfflineQueue: true
978
+ };
979
+ }
980
+ #onError(error) {
981
+ this.#markDown(error);
982
+ }
983
+ #markDown(error) {
984
+ if (this.#down) return;
985
+ this.#down = true;
986
+ this.#logger?.error("redis.unavailable", {
987
+ ...describeSettings(this.settings),
988
+ reason: reasonOf(error)
989
+ });
990
+ }
991
+ #translate(error, operation) {
992
+ if (!(error instanceof Error)) return redisUnavailable(operation, error);
993
+ if (AUTH_ERRORS.test(error.message)) {
994
+ this.#logger?.error("redis.access_denied", {
995
+ ...describeSettings(this.settings),
996
+ reason: error.message.split(" ")[0]
997
+ });
998
+ return redisUnavailable(operation, error);
999
+ }
1000
+ const code = error.code;
1001
+ if (UNREACHABLE.has(error.name) || typeof code === "string" && /^E[A-Z]+$/.test(code) || NETWORK_ERROR.test(error.message) || /certificate|self[- ]signed|TLS|SSL/i.test(error.message)) return redisUnavailable(operation, error);
1002
+ return error;
1003
+ }
1004
+ };
1005
+ function readCa(path) {
1006
+ try {
1007
+ return readFileSync(path);
1008
+ } catch {
1009
+ throw new BootError("invalid_redis_config", `REDIS_TLS_CA points to a file that can't be read (${path}).`, "Set REDIS_TLS_CA to the path of the PEM file with your CA certificate, or remove it to use the system CAs.");
1010
+ }
1011
+ }
1012
+ /** A short, secret-free reason for the log. */
1013
+ function reasonOf(error) {
1014
+ if (!(error instanceof Error)) return "unknown";
1015
+ const code = error.code;
1016
+ if (typeof code === "string") return code;
1017
+ return error.name === "Error" ? error.message.split(" ")[0] ?? "Error" : error.name;
1018
+ }
1019
+ // src/env.ts
1020
+ /**
1021
+ * The environment the connection settings are read from: `<app>/.env` merged under the process
1022
+ * environment (values set by the shell, Docker or CI win), the same rule the framework follows.
1023
+ *
1024
+ * **Why this package reads `.env` itself:** the framework keeps its merged environment private
1025
+ * (providers get the config tree, not the variables), and the Redis password must not be copied
1026
+ * into the config tree (see `config.ts`). Node's own `util.parseEnv` does the parsing, so there is
1027
+ * no hand-written parser here. Proposal in NEXT.md: the framework exposes the environment to
1028
+ * providers, and this file goes away.
1029
+ *
1030
+ * @module
1031
+ */
1032
+ /**
1033
+ * Read `<basePath>/.env` (when present) under `process.env`.
1034
+ *
1035
+ * @example
1036
+ * const env = loadRedisEnv('/srv/blog')
1037
+ * env['REDIS_HOST'] // from the process environment, else from .env
1038
+ */
1039
+ function loadRedisEnv(basePath, processEnv = process.env) {
1040
+ const file = join(basePath, ".env");
1041
+ return {
1042
+ ...existsSync(file) ? parseEnv(readFileSync(file, "utf8")) : {},
1043
+ ...processEnv
1044
+ };
1045
+ }
1046
+ // src/idempotency-store.ts
1047
+ /**
1048
+ * `Idempotency-Key` storage in Redis: the framework's `IdempotencyStore`, shared by every process
1049
+ * so a retried request is replayed (not run twice) whichever server it reaches.
1050
+ *
1051
+ * Each claim is a hash `{ f: fingerprint, r: stored response }`:
1052
+ * - `begin` is one Lua script (`HSETNX` + expiry, else read the hash), so two parallel first
1053
+ * requests with the same key can't both run;
1054
+ * - `complete` stores the response only while the claim still exists (a released or expired claim
1055
+ * is not resurrected) and restarts the 24-hour replay window;
1056
+ * - an unfinished claim expires too, so a crashed request can't block its key forever.
1057
+ *
1058
+ * The framework's key already scopes claims to the caller; it is hashed (SHA-256) before it
1059
+ * reaches Redis, so actor ids and keys don't show up in dumps.
1060
+ *
1061
+ * @module
1062
+ */
1063
+ const BEGIN = defineLua(`
1064
+ if redis.call('HSETNX', KEYS[1], 'f', ARGV[1]) == 1 then
1065
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
1066
+ return {}
1067
+ end
1068
+ return redis.call('HMGET', KEYS[1], 'f', 'r')
1069
+ `);
1070
+ const COMPLETE = defineLua(`
1071
+ if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
1072
+ redis.call('HSET', KEYS[1], 'r', ARGV[1])
1073
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
1074
+ return 1
1075
+ `);
1076
+ /**
1077
+ * The idempotency store in Redis.
1078
+ *
1079
+ * @example
1080
+ * app.container.value(IdempotencyStoreToken, new RedisIdempotencyStore({ driver: redis, space }))
1081
+ */
1082
+ var RedisIdempotencyStore = class {
1083
+ #driver;
1084
+ #space;
1085
+ #ttlMs;
1086
+ constructor(options) {
1087
+ const ttl = options.ttlMs ?? IDEMPOTENCY_TTL_MS;
1088
+ if (!Number.isSafeInteger(ttl) || ttl < 1) throw new RangeError("idempotency ttlMs must be a positive integer");
1089
+ this.#driver = options.driver;
1090
+ this.#space = options.space;
1091
+ this.#ttlMs = ttl;
1092
+ }
1093
+ async begin(key, fingerprint, _now) {
1094
+ const reply = asArray(await this.#driver.script(BEGIN, [this.#key(key)], [fingerprint, String(this.#ttlMs)]));
1095
+ if (reply.length === 0) return { kind: "new" };
1096
+ if (asNullableString(reply[0]) !== fingerprint) return { kind: "mismatch" };
1097
+ const response = parseResponse(asNullableString(reply[1] ?? null));
1098
+ return response === void 0 ? { kind: "in_progress" } : {
1099
+ kind: "replay",
1100
+ response
1101
+ };
1102
+ }
1103
+ async complete(key, response, _now) {
1104
+ await this.#driver.script(COMPLETE, [this.#key(key)], [JSON.stringify(response), String(this.#ttlMs)]);
1105
+ }
1106
+ async release(key) {
1107
+ await this.#driver.command(["UNLINK", this.#key(key)]);
1108
+ }
1109
+ #key(key) {
1110
+ return this.#space.key(createHash("sha256").update(key).digest("hex"));
1111
+ }
1112
+ };
1113
+ function parseResponse(raw) {
1114
+ if (raw === null) return void 0;
1115
+ try {
1116
+ const value = JSON.parse(raw);
1117
+ if (typeof value !== "object" || value === null) return void 0;
1118
+ const { status, headers, body } = value;
1119
+ if (typeof status !== "number" || typeof body !== "string" || !Array.isArray(headers)) return void 0;
1120
+ return {
1121
+ status,
1122
+ headers: headers.filter((pair) => Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "string"),
1123
+ body
1124
+ };
1125
+ } catch {
1126
+ return;
1127
+ }
1128
+ }
1129
+ // src/lock.ts
1130
+ /**
1131
+ * Atomic locks (Laravel's `Cache::lock`): only one process at a time may hold a named lock.
1132
+ *
1133
+ * **How:** acquiring is `SET key <owner> NX PX <ttl>`: Redis guarantees only one caller creates
1134
+ * the key. The owner is a random 128-bit token, and releasing or extending runs a Lua script that
1135
+ * checks the token first, so:
1136
+ *
1137
+ * - a process can never release a lock someone else holds (for example after its own lock expired
1138
+ * and another process took it), the classic "unsafe DEL" bug;
1139
+ * - a crashed holder never blocks forever: every lock expires after its TTL;
1140
+ * - a long job can {@link RedisLock.extend} its lock while it still owns it.
1141
+ *
1142
+ * Another process can release a lock it was handed the owner token of
1143
+ * (`locks.restore(name, owner)`), as Laravel does for queued jobs.
1144
+ *
1145
+ * This is a single-instance lock (one Redis primary). It is not Redlock: during a primary
1146
+ * failover, a lock written to the old primary may be lost before it replicated. Use it to avoid
1147
+ * duplicate work, not as the only guard for correctness-critical money movements; those belong in a
1148
+ * database transaction.
1149
+ *
1150
+ * @module
1151
+ */
1152
+ const RELEASE = defineLua(`
1153
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
1154
+ return redis.call('DEL', KEYS[1])
1155
+ end
1156
+ return 0
1157
+ `);
1158
+ const EXTEND = defineLua(`
1159
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
1160
+ return redis.call('PEXPIRE', KEYS[1], ARGV[2])
1161
+ end
1162
+ return 0
1163
+ `);
1164
+ const OWNER = /^[A-Za-z0-9_-]{16,128}$/;
1165
+ /**
1166
+ * Creates and restores locks in one key space.
1167
+ *
1168
+ * @example
1169
+ * const locks = new RedisLocks({ driver: redis, space: KeySpace.root('blog:').area('lock') })
1170
+ * await locks.create('reports:build', 120).block(10, () => buildReports())
1171
+ */
1172
+ var RedisLocks = class RedisLocks {
1173
+ #driver;
1174
+ #space;
1175
+ constructor(options) {
1176
+ this.#driver = options.driver;
1177
+ this.#space = options.space;
1178
+ }
1179
+ /**
1180
+ * The same locks, scoped to one tenant (tenant A's `import` lock never blocks tenant B's).
1181
+ *
1182
+ * @example
1183
+ * locks.forTenant('acme').create('import', 60)
1184
+ */
1185
+ forTenant(tenantId) {
1186
+ return new RedisLocks({
1187
+ driver: this.#driver,
1188
+ space: this.#space.tenant(tenantId)
1189
+ });
1190
+ }
1191
+ /**
1192
+ * A lock handle (not acquired yet) that expires `seconds` after it is acquired.
1193
+ *
1194
+ * @example
1195
+ * const lock = locks.create('invoices:send', 30)
1196
+ * if (await lock.acquire()) try { … } finally { await lock.release() }
1197
+ */
1198
+ create(name, seconds, owner) {
1199
+ if (!Number.isFinite(seconds) || seconds <= 0) throw new RangeError("A lock needs a lifetime in seconds above 0 (it expires if its holder crashes).");
1200
+ if (owner !== void 0 && !OWNER.test(owner)) throw new TypeError("A lock owner must be 16 to 128 characters of A-Z, a-z, 0-9, _ or -.");
1201
+ return new RedisLock(this.#driver, name, this.#space.key(name), Math.max(1, Math.round(seconds * 1e3)), owner ?? randomBytes(16).toString("base64url"));
1202
+ }
1203
+ /**
1204
+ * A handle for a lock acquired elsewhere (another process) with a known owner token, so it can
1205
+ * be released or extended here.
1206
+ *
1207
+ * @example
1208
+ * await locks.restore('invoices:send', job.lockOwner).release()
1209
+ */
1210
+ restore(name, owner) {
1211
+ return this.create(name, 1, owner);
1212
+ }
1213
+ };
1214
+ /**
1215
+ * One named lock and this handle's owner token.
1216
+ *
1217
+ * @example
1218
+ * const lock = locks.create('export', 60)
1219
+ * await lock.block(5, () => runExport())
1220
+ */
1221
+ var RedisLock = class {
1222
+ /** The lock's name (the caller's, without prefix). */
1223
+ name;
1224
+ /** This handle's owner token: pass it to another process to release the lock there. */
1225
+ owner;
1226
+ #driver;
1227
+ #key;
1228
+ #ttlMs;
1229
+ /** @internal Use {@link RedisLocks.create}. */
1230
+ constructor(driver, name, key, ttlMs, owner) {
1231
+ this.#driver = driver;
1232
+ this.name = name;
1233
+ this.#key = key;
1234
+ this.#ttlMs = ttlMs;
1235
+ this.owner = owner;
1236
+ }
1237
+ /**
1238
+ * Try once; `true` when this handle now holds the lock. Re-acquiring a lock this owner already
1239
+ * holds is `false` (locks are not re-entrant).
1240
+ *
1241
+ * @example
1242
+ * if (await lock.acquire()) { … }
1243
+ */
1244
+ async acquire() {
1245
+ const reply = await this.#driver.command([
1246
+ "SET",
1247
+ this.#key,
1248
+ this.owner,
1249
+ "NX",
1250
+ "PX",
1251
+ String(this.#ttlMs)
1252
+ ]);
1253
+ return reply !== null && reply !== void 0;
1254
+ }
1255
+ /**
1256
+ * Wait up to `seconds` for the lock (polling with jittered backoff), then, when `work` is given,
1257
+ * run it and always release afterwards. Throws the 503 `lock_timeout` problem when the wait
1258
+ * runs out.
1259
+ *
1260
+ * @example
1261
+ * const total = await lock.block(5, () => recalculate())
1262
+ */
1263
+ async block(seconds, work) {
1264
+ const deadline = Date.now() + Math.max(0, seconds) * 1e3;
1265
+ for (let attempt = 0;; attempt++) {
1266
+ if (await this.acquire()) break;
1267
+ const left = deadline - Date.now();
1268
+ if (left <= 0) throw lockTimeout(this.name, seconds);
1269
+ await setTimeout$1(Math.min(left, Math.min(250, 10 * 2 ** Math.min(attempt, 5)) + Math.random() * 10));
1270
+ }
1271
+ if (work === void 0) return void 0;
1272
+ try {
1273
+ return await work();
1274
+ } finally {
1275
+ await this.release();
1276
+ }
1277
+ }
1278
+ /**
1279
+ * Run `work` only if the lock is free right now (no waiting); `undefined` when it was taken.
1280
+ *
1281
+ * @example
1282
+ * await lock.run(() => sendDigest()) // skipped if another worker is sending it
1283
+ */
1284
+ async run(work) {
1285
+ if (!await this.acquire()) return void 0;
1286
+ try {
1287
+ return await work();
1288
+ } finally {
1289
+ await this.release();
1290
+ }
1291
+ }
1292
+ /**
1293
+ * Release the lock if this owner still holds it; `false` when it had expired or belongs to
1294
+ * someone else (nothing is removed then).
1295
+ *
1296
+ * @example
1297
+ * await lock.release()
1298
+ */
1299
+ async release() {
1300
+ return asInteger(await this.#driver.script(RELEASE, [this.#key], [this.owner])) === 1;
1301
+ }
1302
+ /**
1303
+ * Reset the lifetime to `seconds` from now if this owner still holds the lock.
1304
+ *
1305
+ * @example
1306
+ * await lock.extend(60) // a long import keeps its lock
1307
+ */
1308
+ async extend(seconds) {
1309
+ if (!Number.isFinite(seconds) || seconds <= 0) throw new RangeError("extend() needs seconds above 0.");
1310
+ const ms = String(Math.max(1, Math.round(seconds * 1e3)));
1311
+ return asInteger(await this.#driver.script(EXTEND, [this.#key], [this.owner, ms])) === 1;
1312
+ }
1313
+ /**
1314
+ * Remove the lock whoever holds it (an operator's escape hatch).
1315
+ *
1316
+ * @example
1317
+ * await locks.create('stuck-job', 1).forceRelease()
1318
+ */
1319
+ async forceRelease() {
1320
+ await this.#driver.command(["UNLINK", this.#key]);
1321
+ }
1322
+ /**
1323
+ * Whether this owner holds the lock right now.
1324
+ *
1325
+ * @example
1326
+ * if (!(await lock.isOwned())) throw new Error('lost the lock')
1327
+ */
1328
+ async isOwned() {
1329
+ return await this.#driver.command(["GET", this.#key]) === this.owner;
1330
+ }
1331
+ };
1332
+ // src/rate-limiter.ts
1333
+ /**
1334
+ * Rate limiting in Redis: fixed and sliding windows, each one atomic Lua script, so limits hold
1335
+ * across every process and server of the app even under bursts of parallel requests.
1336
+ *
1337
+ * - **Fixed window** (`algorithm: 'fixed'`, the default; what the framework's `throttle` does):
1338
+ * one counter per window. Cheap (one key, one integer), but a client can send `2 × max` around
1339
+ * a window boundary.
1340
+ * - **Sliding window** (`'sliding'`): a sorted set of the accepted hits in the last window.
1341
+ * Exact: never more than `max` hits in any `windowSeconds` span. Costs one entry per accepted
1342
+ * hit (bounded by `max`); refused hits are not recorded, so a client hammering a closed limit
1343
+ * can't grow memory.
1344
+ *
1345
+ * Time comes from the Redis server (`TIME` inside the script), so app servers with skewed clocks
1346
+ * still share one window.
1347
+ *
1348
+ * The framework's `throttle` middleware counts in the default cache store, so with
1349
+ * `CACHE_STORE=redis` it already uses Redis (fixed windows). This class is for limits in your own
1350
+ * code (`await limiter.hit(\`export:${user.id}\`, { max: 5, windowSeconds: 3600 })`).
1351
+ *
1352
+ * @module
1353
+ */
1354
+ const FIXED = defineLua(`
1355
+ local count = redis.call('INCR', KEYS[1])
1356
+ local ttl = redis.call('PTTL', KEYS[1])
1357
+ if count == 1 or ttl < 0 then
1358
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
1359
+ ttl = tonumber(ARGV[1])
1360
+ end
1361
+ return {count, ttl}
1362
+ `);
1363
+ const SLIDING = defineLua(`
1364
+ local t = redis.call('TIME')
1365
+ local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
1366
+ local window = tonumber(ARGV[2])
1367
+ local limit = tonumber(ARGV[1])
1368
+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - window)
1369
+ local count = redis.call('ZCARD', KEYS[1])
1370
+ if count < limit then
1371
+ redis.call('ZADD', KEYS[1], now, ARGV[3])
1372
+ redis.call('PEXPIRE', KEYS[1], window)
1373
+ return {1, count + 1, 0}
1374
+ end
1375
+ local oldest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
1376
+ local retry = window
1377
+ if oldest[2] then retry = tonumber(oldest[2]) + window - now end
1378
+ if retry < 1 then retry = 1 end
1379
+ return {0, count, retry}
1380
+ `);
1381
+ /**
1382
+ * A rate limiter in one key space.
1383
+ *
1384
+ * @example
1385
+ * const limiter = new RedisRateLimiter({ driver: redis, space: KeySpace.root('blog:').area('rate') })
1386
+ * const result = await limiter.hit(`login:${email}`, { max: 5, windowSeconds: 60, algorithm: 'sliding' })
1387
+ */
1388
+ var RedisRateLimiter = class RedisRateLimiter {
1389
+ #driver;
1390
+ #space;
1391
+ constructor(options) {
1392
+ this.#driver = options.driver;
1393
+ this.#space = options.space;
1394
+ }
1395
+ /**
1396
+ * The same limiter, scoped to one tenant.
1397
+ *
1398
+ * @example
1399
+ * limiter.forTenant('acme').hit('exports', { max: 10, windowSeconds: 3600 })
1400
+ */
1401
+ forTenant(tenantId) {
1402
+ return new RedisRateLimiter({
1403
+ driver: this.#driver,
1404
+ space: this.#space.tenant(tenantId)
1405
+ });
1406
+ }
1407
+ /**
1408
+ * Count one hit and say whether it is within the limit.
1409
+ *
1410
+ * @example
1411
+ * const { allowed, retryAfterSeconds } = await limiter.hit('api:42', { max: 60, windowSeconds: 60 })
1412
+ */
1413
+ async hit(key, limit) {
1414
+ const { max, windowMs } = check(limit);
1415
+ if (limit.algorithm === "sliding") {
1416
+ const [allowed, count, retry] = asArray(await this.#driver.script(SLIDING, [this.#space.key(`s:${key}`)], [
1417
+ String(max),
1418
+ String(windowMs),
1419
+ randomBytes(9).toString("base64url")
1420
+ ])).map(asInteger);
1421
+ const ok = allowed === 1;
1422
+ return {
1423
+ allowed: ok,
1424
+ limit: max,
1425
+ remaining: ok ? Math.max(0, max - (count ?? max)) : 0,
1426
+ retryAfterSeconds: ok ? 0 : Math.max(1, Math.ceil((retry ?? windowMs) / 1e3))
1427
+ };
1428
+ }
1429
+ const [count, ttl] = asArray(await this.#driver.script(FIXED, [this.#space.key(`f:${key}`)], [String(windowMs)])).map(asInteger);
1430
+ const hits = count ?? max + 1;
1431
+ const ok = hits <= max;
1432
+ return {
1433
+ allowed: ok,
1434
+ limit: max,
1435
+ remaining: Math.max(0, max - hits),
1436
+ retryAfterSeconds: ok ? 0 : Math.max(1, Math.ceil((ttl ?? windowMs) / 1e3))
1437
+ };
1438
+ }
1439
+ /**
1440
+ * Run `work` only when the hit is allowed; returns the result, or `undefined` when limited.
1441
+ *
1442
+ * @example
1443
+ * await limiter.attempt(`digest:${user.id}`, { max: 1, windowSeconds: 3600 }, () => sendDigest(user))
1444
+ */
1445
+ async attempt(key, limit, work) {
1446
+ return (await this.hit(key, limit)).allowed ? work() : void 0;
1447
+ }
1448
+ /**
1449
+ * Reset a key's counters (both algorithms), for example after a successful login.
1450
+ *
1451
+ * @example
1452
+ * await limiter.clear(`login:${email}`)
1453
+ */
1454
+ async clear(key) {
1455
+ await this.#driver.command([
1456
+ "UNLINK",
1457
+ this.#space.key(`f:${key}`),
1458
+ this.#space.key(`s:${key}`)
1459
+ ]);
1460
+ }
1461
+ };
1462
+ function check(limit) {
1463
+ if (!Number.isSafeInteger(limit.max) || limit.max < 1) throw new RangeError("A rate limit needs max to be a whole number of at least 1.");
1464
+ if (!Number.isFinite(limit.windowSeconds) || limit.windowSeconds <= 0) throw new RangeError("A rate limit needs windowSeconds above 0.");
1465
+ if (limit.algorithm !== void 0 && limit.algorithm !== "fixed" && limit.algorithm !== "sliding") throw new RangeError("A rate limit algorithm is \"fixed\" or \"sliding\".");
1466
+ return {
1467
+ max: limit.max,
1468
+ windowMs: Math.max(1, Math.round(limit.windowSeconds * 1e3))
1469
+ };
1470
+ }
1471
+ // src/session-store.ts
1472
+ /**
1473
+ * Sessions in Redis: the framework's `SessionStore` (`flush`, for `node strut session:flush`) plus
1474
+ * the read / write / touch / destroy operations a session driver needs.
1475
+ *
1476
+ * - **Session ids never reach Redis in clear text.** The key is the SHA-256 of the id, so a dump,
1477
+ * a replica, `MONITOR` or a slow log never reveals a usable session cookie.
1478
+ * - **Ids are checked:** 22 to 256 characters of `A-Z a-z 0-9 _ -` (at least 128 bits of a
1479
+ * base64url id). Anything else is refused before Redis is asked, so a forged cookie can't
1480
+ * probe keys.
1481
+ * - **Bounded:** a session over `maxBytes` (default 256 KiB) is refused instead of stored, so a
1482
+ * bug or an attacker can't fill the server through one session.
1483
+ * - **Idle expiry** is Redis's TTL: `write` and `touch` reset it to `SESSION_LIFETIME`.
1484
+ *
1485
+ * Sessions belong to `@strutvane/auth`. It can use this store through the framework's session
1486
+ * contract once that contract has these operations (see NEXT.md, framework proposals); until then
1487
+ * the provider binds it under the framework's `SessionStoreToken` (`flush`) when
1488
+ * `SESSION_DRIVER=redis`.
1489
+ *
1490
+ * @module
1491
+ */
1492
+ const SESSION_ID = /^[A-Za-z0-9_-]{22,256}$/;
1493
+ /**
1494
+ * A session store in Redis.
1495
+ *
1496
+ * @example
1497
+ * await sessions.write(id, { userId: 7 })
1498
+ * const data = await sessions.read(id) // { userId: 7 }
1499
+ */
1500
+ var RedisSessionStore = class {
1501
+ #driver;
1502
+ #space;
1503
+ #lifetimeMs;
1504
+ #maxBytes;
1505
+ constructor(options) {
1506
+ const lifetime = options.lifetimeSeconds ?? 7200;
1507
+ const maxBytes = options.maxBytes ?? 262144;
1508
+ if (!Number.isSafeInteger(lifetime) || lifetime < 1) throw new RangeError("The session lifetime must be a whole number of seconds, at least 1.");
1509
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError("The session size limit must be a whole number of bytes, at least 1.");
1510
+ this.#driver = options.driver;
1511
+ this.#space = options.space;
1512
+ this.#lifetimeMs = lifetime * 1e3;
1513
+ this.#maxBytes = maxBytes;
1514
+ }
1515
+ /**
1516
+ * The session's data, or `undefined` when it doesn't exist, expired, or the id is malformed.
1517
+ *
1518
+ * @example
1519
+ * const data = await sessions.read(cookieValue)
1520
+ */
1521
+ async read(id) {
1522
+ const key = this.#key(id);
1523
+ if (key === void 0) return void 0;
1524
+ const raw = asNullableString(await this.#driver.command(["GET", key]));
1525
+ if (raw === null) return void 0;
1526
+ try {
1527
+ const parsed = JSON.parse(raw);
1528
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
1529
+ } catch {
1530
+ return;
1531
+ }
1532
+ }
1533
+ /**
1534
+ * Store the session's data and reset its idle expiry. Throws a `TypeError` for a malformed id and
1535
+ * a `RangeError` for data over the size limit.
1536
+ *
1537
+ * @example
1538
+ * await sessions.write(id, { userId: 7, csrf: token })
1539
+ */
1540
+ async write(id, data) {
1541
+ const key = this.#key(id);
1542
+ if (key === void 0) throw new TypeError("Refusing to write a session with a malformed id.");
1543
+ const encoded = JSON.stringify(data);
1544
+ if (Buffer.byteLength(encoded, "utf8") > this.#maxBytes) throw new RangeError(`The session is larger than ${this.#maxBytes} bytes; keep large data in the database and its id in the session.`);
1545
+ await this.#driver.command([
1546
+ "SET",
1547
+ key,
1548
+ encoded,
1549
+ "PX",
1550
+ String(this.#lifetimeMs)
1551
+ ]);
1552
+ }
1553
+ /**
1554
+ * Reset the idle expiry without rewriting the data; `false` when the session is gone.
1555
+ *
1556
+ * @example
1557
+ * await sessions.touch(id)
1558
+ */
1559
+ async touch(id) {
1560
+ const key = this.#key(id);
1561
+ if (key === void 0) return false;
1562
+ return asInteger(await this.#driver.command([
1563
+ "PEXPIRE",
1564
+ key,
1565
+ String(this.#lifetimeMs)
1566
+ ])) === 1;
1567
+ }
1568
+ /**
1569
+ * Remove one session (sign-out, id rotation); `true` when it existed.
1570
+ *
1571
+ * @example
1572
+ * await sessions.destroy(oldId)
1573
+ */
1574
+ async destroy(id) {
1575
+ const key = this.#key(id);
1576
+ if (key === void 0) return false;
1577
+ return asInteger(await this.#driver.command(["UNLINK", key])) > 0;
1578
+ }
1579
+ /** Remove every session of this app; returns how many were removed. */
1580
+ async flush() {
1581
+ return deleteMatching(this.#driver, this.#space.pattern());
1582
+ }
1583
+ #key(id) {
1584
+ if (typeof id !== "string" || !SESSION_ID.test(id)) return void 0;
1585
+ return this.#space.key(createHash("sha256").update(id).digest("hex"));
1586
+ }
1587
+ };
1588
+ // src/tokens.ts
1589
+ /**
1590
+ * Container tokens this package binds (integration-map connection 2: container tokens). Other
1591
+ * packages and apps resolve the Redis services through these, never by importing this package's
1592
+ * classes directly.
1593
+ *
1594
+ * @module
1595
+ */
1596
+ /**
1597
+ * The app's shared Redis connection (lazily connected; closed on shutdown).
1598
+ *
1599
+ * @example
1600
+ * const health = await app.make(RedisConnectionToken).health()
1601
+ */
1602
+ const RedisConnectionToken = token("strutvane.redis.connection");
1603
+ /**
1604
+ * The app's root key space (`REDIS_PREFIX`).
1605
+ *
1606
+ * @example
1607
+ * app.make(RedisKeySpaceToken).area('reports').key('daily')
1608
+ */
1609
+ const RedisKeySpaceToken = token("strutvane.redis.keys");
1610
+ /**
1611
+ * Atomic locks (`<prefix>lock:…`).
1612
+ *
1613
+ * @example
1614
+ * await app.make(RedisLocksToken).create('reports:build', 120).block(10, build)
1615
+ */
1616
+ const RedisLocksToken = token("strutvane.redis.locks");
1617
+ /**
1618
+ * The rate limiter (`<prefix>rate:…`).
1619
+ *
1620
+ * @example
1621
+ * await app.make(RedisRateLimiterToken).hit(`export:${user.id}`, { max: 5, windowSeconds: 3600 })
1622
+ */
1623
+ const RedisRateLimiterToken = token("strutvane.redis.rateLimiter");
1624
+ export { isValidTenantId as C, RedisCacheStore as E, globEscape as S, createRedisCacheManager as T, defaultPrefix as _, RedisSessionStore as a, KeySpace as b, RedisLocks as c, RedisConnection as d, PACKAGE_NAME as f, redisUnavailable as g, lockTimeout as h, RedisRateLimiterToken as i, RedisIdempotencyStore as l, REDIS_MESSAGES_EN as m, RedisKeySpaceToken as n, RedisRateLimiter as o, REDIS_ERRORS as p, RedisLocksToken as r, RedisLock as s, RedisConnectionToken as t, loadRedisEnv as u, describeSettings as v, prefixProblem as w, MAX_KEY_BYTES as x, resolveRedisSettings as y };
1625
+
1626
+ //# sourceMappingURL=tokens-CnThleYU.mjs.map