@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 @@
1
+ {"version":3,"file":"tokens-CnThleYU.mjs","names":["invalid","sleep"],"sources":["../src/cache-store.ts","../src/cache-manager.ts","../src/keys.ts","../src/config.ts","../src/errors.ts","../src/connection.ts","../src/env.ts","../src/idempotency-store.ts","../src/lock.ts","../src/rate-limiter.ts","../src/session-store.ts","../src/tokens.ts"],"sourcesContent":["/**\n * The Redis cache store: the framework's `CacheStore` contract (what `Cache`, `throttle` and\n * `node strut cache:clear` use) plus Laravel's extras: `many`, `putMany`, `forever`, `decrement`,\n * `remember` and `flexible` (stale-while-revalidate).\n *\n * - **Values are JSON.** `undefined`, functions and symbols can't be stored (a `TypeError`, not a\n * silent `null`); a stored value that isn't JSON (written by something else) reads as a miss.\n * - **Atomic:** `add` is `SET NX`, `increment` is one Lua script, `putMany` is one script, so\n * concurrent workers never lose an update.\n * - **Expiry is Redis's clock**, not the app's: every process agrees on it. A `ttlSeconds` of 0\n * or less removes the key (Laravel's behaviour); omitted means forever.\n * - **`flush` only removes this store's keys** (by prefix, with `SCAN` + `UNLINK`), never the\n * whole database: other apps and this app's sessions, locks and queues are untouched.\n * - **Tenants:** `store.forTenant(id)` is a store whose keys live under that tenant's namespace;\n * its `flush` clears only that tenant (see `keys.ts`).\n *\n * @module\n */\nimport type { CacheStore } from '@strutvane/framework'\nimport type { Logger } from '@strutvane/framework/contracts'\nimport {\n asArray,\n asInteger,\n asNullableString,\n defineLua,\n deleteMatching,\n type RedisDriver,\n} from './driver.ts'\nimport type { KeySpace } from './keys.ts'\n\n/**\n * Options for {@link RedisCacheStore}.\n *\n * @example\n * new RedisCacheStore({ driver: redis, space: KeySpace.root('blog:').area('cache') })\n */\nexport interface RedisCacheStoreOptions {\n readonly driver: RedisDriver\n /** The key space (`<prefix>cache:` for the default store). */\n readonly space: KeySpace\n /** Where failed background refreshes (`flexible`) are reported. */\n readonly logger?: Logger\n}\n\n// A counter starts at `by` when missing or not an integer; an existing one keeps its expiry.\nconst INCREMENT = defineLua(`\nlocal current = redis.call('GET', KEYS[1])\nif current and string.match(current, '^%-?%d+$') then\n return redis.call('INCRBY', KEYS[1], ARGV[1])\nend\nif ARGV[2] == '' then\n redis.call('SET', KEYS[1], ARGV[1])\nelse\n redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])\nend\nreturn tonumber(ARGV[1])\n`)\n\n// ARGV[1] = ttl in ms ('' = forever), then one value per key.\nconst PUT_MANY = defineLua(`\nfor i, key in ipairs(KEYS) do\n if ARGV[1] == '' then\n redis.call('SET', key, ARGV[i + 1])\n else\n redis.call('SET', key, ARGV[i + 1], 'PX', ARGV[1])\n end\nend\nreturn #KEYS\n`)\n\n/** A value stored by `flexible`: the value and when it was computed (ms since the epoch). */\ninterface FlexibleEntry {\n readonly v: unknown\n readonly t: number\n}\n\n/**\n * A cache store in Redis or Valkey.\n *\n * @example\n * const cache = new RedisCacheStore({ driver: redis, space: KeySpace.root('blog:').area('cache') })\n * await cache.put('stats', { posts: 3 }, 60)\n * await cache.forTenant('acme').get('stats') // undefined: another namespace\n */\nexport class RedisCacheStore implements CacheStore {\n readonly #driver: RedisDriver\n readonly #space: KeySpace\n readonly #logger: Logger | undefined\n\n constructor(options: RedisCacheStoreOptions) {\n this.#driver = options.driver\n this.#space = options.space\n this.#logger = options.logger\n }\n\n /** The key prefix of this store (for diagnostics). */\n get prefix(): string {\n return this.#space.prefix\n }\n\n /**\n * The same store, scoped to one tenant.\n *\n * @example\n * await Cache.store('redis').forTenant(tenant.id).remember('dashboard', 60, build)\n */\n forTenant(tenantId: string): RedisCacheStore {\n return new RedisCacheStore({\n driver: this.#driver,\n space: this.#space.tenant(tenantId),\n ...(this.#logger === undefined ? {} : { logger: this.#logger }),\n })\n }\n\n async get(key: string): Promise<unknown> {\n return decode(asNullableString(await this.#driver.command(['GET', this.#space.key(key)])))\n }\n\n async has(key: string): Promise<boolean> {\n return (await this.get(key)) !== undefined\n }\n\n async put(key: string, value: unknown, ttlSeconds?: number): Promise<void> {\n const full = this.#space.key(key)\n const encoded = encode(value)\n const px = expiry(ttlSeconds)\n if (px === 'expired') {\n await this.#driver.command(['UNLINK', full])\n return\n }\n await this.#driver.command(\n px === undefined ? ['SET', full, encoded] : ['SET', full, encoded, 'PX', px],\n )\n }\n\n async add(key: string, value: unknown, ttlSeconds?: number): Promise<boolean> {\n const full = this.#space.key(key)\n const encoded = encode(value)\n const px = expiry(ttlSeconds)\n if (px === 'expired') return false\n const reply = await this.#driver.command(\n px === undefined ? ['SET', full, encoded, 'NX'] : ['SET', full, encoded, 'NX', 'PX', px],\n )\n return reply !== null && reply !== undefined\n }\n\n async increment(key: string, by = 1, ttlSeconds?: number): Promise<number> {\n if (!Number.isSafeInteger(by))\n throw new TypeError('increment() takes a whole number (Redis counters are integers).')\n const px = expiry(ttlSeconds)\n if (px === 'expired') throw new RangeError('increment() needs a ttlSeconds above 0, or none.')\n return asInteger(\n await this.#driver.script(INCREMENT, [this.#space.key(key)], [String(by), px ?? '']),\n )\n }\n\n /**\n * Subtract from a counter (see {@link RedisCacheStore.increment}).\n *\n * @example\n * await cache.decrement('seats', 1)\n */\n async decrement(key: string, by = 1, ttlSeconds?: number): Promise<number> {\n return this.increment(key, -by, ttlSeconds)\n }\n\n async ttl(key: string): Promise<number | undefined> {\n const ms = asInteger(await this.#driver.command(['PTTL', this.#space.key(key)]))\n return ms < 0 ? undefined : Math.ceil(ms / 1000)\n }\n\n async forget(key: string): Promise<boolean> {\n return asInteger(await this.#driver.command(['UNLINK', this.#space.key(key)])) > 0\n }\n\n async flush(): Promise<void> {\n await deleteMatching(this.#driver, this.#space.pattern())\n }\n\n /**\n * Several values at once (`MGET`); missing keys are `undefined`.\n *\n * @example\n * const { a, b } = await cache.many(['a', 'b'])\n */\n async many(keys: readonly string[]): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {}\n if (keys.length === 0) return result\n const replies = asArray(\n await this.#driver.command(['MGET', ...keys.map((key) => this.#space.key(key))]),\n )\n keys.forEach((key, index) => {\n result[key] = decode(asNullableString(replies[index]))\n })\n return result\n }\n\n /**\n * Store several values atomically with one expiry.\n *\n * @example\n * await cache.putMany({ a: 1, b: 2 }, 60)\n */\n async putMany(values: Readonly<Record<string, unknown>>, ttlSeconds?: number): Promise<void> {\n const entries = Object.entries(values)\n if (entries.length === 0) return\n const keys = entries.map(([key]) => this.#space.key(key))\n const encoded = entries.map(([, value]) => encode(value))\n const px = expiry(ttlSeconds)\n if (px === 'expired') {\n await this.#driver.command(['UNLINK', ...keys])\n return\n }\n await this.#driver.script(PUT_MANY, keys, [px ?? '', ...encoded])\n }\n\n /**\n * Store a value with no expiry.\n *\n * @example\n * await cache.forever('settings', { theme: 'dark' })\n */\n async forever(key: string, value: unknown): Promise<void> {\n await this.put(key, value)\n }\n\n /**\n * The cached value, or compute, store and return it. `undefined` results are not cached.\n *\n * @example\n * const posts = await cache.remember('posts:count', 60, () => Post.query().count())\n */\n async remember<TValue>(\n key: string,\n ttlSeconds: number | undefined,\n compute: () => TValue | Promise<TValue>,\n ): Promise<TValue> {\n const cached = await this.get(key)\n if (cached !== undefined) return cached as TValue\n const value = await compute()\n if (value !== undefined) await this.put(key, value, ttlSeconds)\n return value\n }\n\n /**\n * Stale-while-revalidate (Laravel's `Cache::flexible`): a value younger than `freshSeconds` is\n * returned as is; one younger than `staleSeconds` is returned at once and refreshed in the\n * background (one refresher at a time, across processes); an older or missing one is computed\n * now.\n *\n * @example\n * const stats = await cache.flexible('stats', [5, 60], () => computeStats())\n */\n async flexible<TValue>(\n key: string,\n [freshSeconds, staleSeconds]: readonly [number, number],\n compute: () => TValue | Promise<TValue>,\n ): Promise<TValue> {\n if (!(freshSeconds > 0 && staleSeconds > freshSeconds))\n throw new RangeError('flexible() needs [fresh, stale] seconds with 0 < fresh < stale.')\n const entry = asFlexible(await this.get(key))\n const now = Date.now()\n if (entry !== undefined) {\n const age = now - entry.t\n if (age < freshSeconds * 1000) return entry.v as TValue\n if (age < staleSeconds * 1000) {\n void this.#refresh(key, staleSeconds, compute)\n return entry.v as TValue\n }\n }\n const value = await compute()\n await this.put(key, { v: value, t: Date.now() } satisfies FlexibleEntry, staleSeconds)\n return value\n }\n\n async #refresh<TValue>(\n key: string,\n staleSeconds: number,\n compute: () => TValue | Promise<TValue>,\n ): Promise<void> {\n const guard = `${key}:refreshing`\n try {\n if (!(await this.add(guard, 1, Math.min(staleSeconds, 30)))) return\n try {\n const value = await compute()\n await this.put(key, { v: value, t: Date.now() } satisfies FlexibleEntry, staleSeconds)\n } finally {\n await this.forget(guard)\n }\n } catch (error) {\n // A background refresh must never crash the process; the stale value keeps being served.\n this.#logger?.warn('redis.cache.refresh_failed', { key, error })\n }\n }\n}\n\n/** Milliseconds for `PX`, `undefined` for \"forever\", or `'expired'` for a ttl of 0 or less. */\nfunction expiry(ttlSeconds: number | undefined): string | 'expired' | undefined {\n if (ttlSeconds === undefined) return undefined\n if (!Number.isFinite(ttlSeconds)) throw new RangeError('ttlSeconds must be a finite number.')\n if (ttlSeconds <= 0) return 'expired'\n return String(Math.max(1, Math.round(ttlSeconds * 1000)))\n}\n\nfunction encode(value: unknown): string {\n const encoded = JSON.stringify(value)\n if (encoded === undefined)\n throw new TypeError(\n 'Cache values must be JSON-serialisable (not undefined, a function or a symbol).',\n )\n return encoded\n}\n\nfunction decode(raw: string | null): unknown {\n if (raw === null) return undefined\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return undefined\n }\n}\n\nfunction asFlexible(value: unknown): FlexibleEntry | undefined {\n if (typeof value !== 'object' || value === null || !('t' in value) || !('v' in value))\n return undefined\n const t = (value as { t: unknown }).t\n return typeof t === 'number' ? (value as FlexibleEntry) : undefined\n}\n","/**\n * The cache manager with Redis stores: the framework's manager (memory and file stores, from\n * `config/cache.ts`) plus every store whose driver is `redis`. The provider binds it as\n * `CacheManagerToken`, so `Cache`, `node strut cache:clear --store=redis` and (with\n * `CACHE_STORE=redis`) the `throttle` middleware all use Redis.\n *\n * ```ts\n * // config/cache.ts\n * stores: {\n * file: { driver: 'file', path: 'storage/framework/cache' },\n * redis: { driver: 'redis' }, // keys: <prefix>cache:…\n * reports: { driver: 'redis', area: 'reports' }, // keys: <prefix>reports:…\n * }\n * ```\n *\n * A `redis` store always exists (like `memory` and `file`), so `CACHE_STORE=redis` works without\n * editing `config/cache.ts`. A bad store entry stops boot with a friendly error.\n *\n * @module\n */\nimport {\n BootError,\n type CacheManager,\n type CacheStore,\n createCacheManager,\n} from '@strutvane/framework'\nimport type { Logger } from '@strutvane/framework/contracts'\nimport type { Clock } from '@strutvane/framework/core'\nimport { RedisCacheStore } from './cache-store.ts'\nimport type { RedisDriver } from './driver.ts'\nimport type { KeySpace } from './keys.ts'\n\n/**\n * One Redis store in `config/cache.ts`.\n *\n * @example\n * const store: RedisCacheStoreConfig = { driver: 'redis', area: 'reports' }\n */\nexport interface RedisCacheStoreConfig {\n readonly driver: 'redis'\n /** The key area after the app prefix. Default `cache`. */\n readonly area?: string\n}\n\n/**\n * What {@link createRedisCacheManager} needs.\n *\n * @example\n * createRedisCacheManager({ basePath, clock, config: app.config('cache'), driver: () => redis, root })\n */\nexport interface RedisCacheManagerOptions {\n readonly basePath: string\n readonly clock: Clock\n /** The `cache` config tree (unchecked). */\n readonly config?: unknown\n /** The shared connection (resolved on first use of a Redis store). */\n readonly driver: () => RedisDriver\n /** The app's root key space (`REDIS_PREFIX`). */\n readonly root: KeySpace\n readonly logger?: Logger\n}\n\n/**\n * Build the cache manager with Redis stores.\n *\n * @example\n * const cache = createRedisCacheManager(options)\n * await cache.store('redis').put('k', 1, 60)\n */\nexport function createRedisCacheManager(options: RedisCacheManagerOptions): CacheManager {\n const { defaultStore, frameworkStores, redisStores } = split(options.config)\n const framework = createCacheManager({\n basePath: options.basePath,\n clock: options.clock,\n config: { default: 'memory', stores: frameworkStores },\n })\n const names = [...new Set([...framework.storeNames, ...redisStores.keys()])].sort()\n if (!names.includes(defaultStore)) throw unknownStore(defaultStore, names)\n const created = new Map<string, CacheStore>()\n return {\n defaultStore,\n storeNames: names,\n store(name: string = defaultStore): CacheStore {\n const area = redisStores.get(name)\n if (area === undefined) {\n if (!names.includes(name)) throw unknownStore(name, names)\n return framework.store(name)\n }\n let store = created.get(name)\n if (store === undefined) {\n store = new RedisCacheStore({\n driver: options.driver(),\n space: options.root.area(area),\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n })\n created.set(name, store)\n }\n return store\n },\n }\n}\n\ninterface Split {\n readonly defaultStore: string\n readonly frameworkStores: Record<string, unknown>\n readonly redisStores: ReadonlyMap<string, string>\n}\n\nfunction split(value: unknown): Split {\n if (value === undefined || value === null)\n return {\n defaultStore: 'memory',\n frameworkStores: {},\n redisStores: new Map([['redis', 'cache']]),\n }\n if (typeof value !== 'object' || Array.isArray(value))\n throw invalid('config/cache.ts must export an object such as { default, stores }.')\n const record = value as Record<string, unknown>\n const name = record['default']\n if (name !== undefined && typeof name !== 'string')\n throw invalid('cache.default must be a store name.')\n const raw = record['stores'] ?? {}\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw))\n throw invalid('cache.stores must map store names to { driver }.')\n const frameworkStores: Record<string, unknown> = {}\n const redisStores = new Map<string, string>([['redis', 'cache']])\n for (const [store, entry] of Object.entries(raw as Record<string, unknown>)) {\n const driver =\n typeof entry === 'object' && entry !== null ? (entry as { driver?: unknown }).driver : entry\n if (driver !== 'redis') {\n redisStores.delete(store)\n frameworkStores[store] = entry\n continue\n }\n // `{ driver: 'redis', area? }`, or just the driver name (the framework accepts both).\n const options: object = typeof entry === 'object' && entry !== null ? entry : {}\n const area = (options as { area?: unknown }).area ?? 'cache'\n if (typeof area !== 'string' || !/^[a-z][a-z0-9_-]{0,31}$/.test(area))\n throw invalid(\n `cache.stores.${store}.area must be a short lowercase name (letters, digits, _ and -, starting with a letter).`,\n )\n for (const key of Object.keys(options))\n if (key !== 'driver' && key !== 'area')\n throw invalid(\n `cache.stores.${store} has an unknown key \"${key}\" (a redis store takes driver and area).`,\n )\n redisStores.set(store, area)\n }\n return { defaultStore: name ?? 'memory', frameworkStores, redisStores }\n}\n\nfunction invalid(message: string): BootError {\n return new BootError(\n 'invalid_cache_config',\n message,\n \"Example: stores: { redis: { driver: 'redis' }, file: { driver: 'file' } } and CACHE_STORE=redis in .env.\",\n )\n}\n\nfunction unknownStore(name: string, names: readonly string[]): BootError {\n return new BootError(\n 'unknown_cache_store',\n `There is no \"${name}\" cache store.`,\n `The stores are: ${names.join(', ')} (config/cache.ts).`,\n )\n}\n","/**\n * Key spaces: every key this package writes is `<app prefix><area>:<key>`, optionally with a\n * tenant segment, `<app prefix><area>:t:<tenant>:<key>`.\n *\n * **Why:** one Redis is often shared by several apps (and several environments of one app), and a\n * multi-tenant app must never let tenant A read, overwrite or flush tenant B's entries. Prefixes\n * are how Redis users isolate data; this module makes them impossible to get wrong:\n *\n * - **Tenant ids are validated, not escaped.** A tenant id may only contain letters, digits, `_`\n * and `-` (UUIDs, ULIDs, slugs and numbers fit). A tenant called `a:t:b` could otherwise reach\n * into another tenant's namespace, so anything else is refused (fail closed).\n * - **The tenant marker can't be forged from a key.** The tenant segment is `t:<id>:`, and a\n * global (non-tenant) key may not start with `t:`, so a global key can never alias a tenant key.\n * - **Flushing matches the prefix literally.** `SCAN MATCH` takes a glob, so `*`, `?`, `[`, `]`\n * and `\\` in a prefix are escaped; an app prefixed `a*` can't flush app `ab`'s keys.\n * - **Keys are bounded.** Empty keys and keys over 1 KiB are refused: long keys are almost always\n * a bug (a whole payload used as a key) and cost memory on every lookup.\n *\n * Keys travel as RESP bulk strings (length-prefixed), so a key containing CR/LF or spaces cannot\n * inject a command; such keys are stored literally.\n *\n * @module\n */\n\n/** The longest key (in UTF-8 bytes) this package accepts from callers. */\nexport const MAX_KEY_BYTES = 1024\n\nconst TENANT_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst SEGMENT = /^[a-z][a-z0-9_-]{0,31}$/\nconst PREFIX = /^[A-Za-z0-9_.:-]{0,128}$/\nconst TENANT_MARKER = 't:'\n\n/**\n * Check an app prefix (`REDIS_PREFIX`): letters, digits and `_ . : -`, at most 128 characters.\n * Returns an error message, or `undefined` when it is fine.\n *\n * @example\n * prefixProblem('blog:') // undefined\n * prefixProblem('a b') // 'may only contain …'\n */\nexport function prefixProblem(prefix: string): string | undefined {\n return PREFIX.test(prefix)\n ? undefined\n : 'may only contain letters, digits and _ . : - (at most 128 characters)'\n}\n\n/**\n * Whether a tenant id can be used in a key (letters, digits, `_` and `-`; 1 to 128 characters).\n *\n * @example\n * isValidTenantId('acme-1') // true\n * isValidTenantId('a:t:b') // false\n */\nexport function isValidTenantId(id: string): boolean {\n return TENANT_ID.test(id)\n}\n\n/**\n * Escape a literal string for a Redis glob pattern (`SCAN MATCH`, `KEYS`).\n *\n * @example\n * globEscape('app*[1]') // 'app\\\\*\\\\[1\\\\]'\n */\nexport function globEscape(literal: string): string {\n return literal.replace(/[*?[\\]\\\\]/g, (char) => `\\\\${char}`)\n}\n\n/**\n * A namespace of keys. Immutable: {@link KeySpace.area} and {@link KeySpace.tenant} return new\n * spaces.\n *\n * @example\n * const cache = KeySpace.root('blog:').area('cache')\n * cache.key('posts') // 'blog:cache:posts'\n * cache.tenant('acme').key('posts') // 'blog:cache:t:acme:posts'\n */\nexport class KeySpace {\n /** The full prefix every key of this space starts with. */\n readonly prefix: string\n /** The tenant this space is scoped to, if any. */\n readonly tenantId: string | undefined\n readonly #areaPrefix: string\n\n private constructor(areaPrefix: string, tenantId: string | undefined) {\n this.#areaPrefix = areaPrefix\n this.tenantId = tenantId\n this.prefix = tenantId === undefined ? areaPrefix : `${areaPrefix}${TENANT_MARKER}${tenantId}:`\n }\n\n /**\n * The app-wide root (no area yet). Throws a `TypeError` for an invalid prefix.\n *\n * @example\n * KeySpace.root('blog:')\n */\n static root(appPrefix: string): KeySpace {\n const problem = prefixProblem(appPrefix)\n if (problem !== undefined) throw new TypeError(`The Redis key prefix ${problem}.`)\n return new KeySpace(appPrefix, undefined)\n }\n\n /**\n * A sub-area (`cache`, `lock`, `session`, …): lowercase, starting with a letter.\n *\n * @example\n * KeySpace.root('blog:').area('lock').key('reports') // 'blog:lock:reports'\n */\n area(name: string): KeySpace {\n if (!SEGMENT.test(name))\n throw new TypeError(\n `\"${name}\" is not a valid key area: use lowercase letters, digits, _ and - (starting with a letter).`,\n )\n if (this.tenantId !== undefined)\n throw new TypeError('Choose the area before the tenant: space.area(name).tenant(id).')\n return new KeySpace(`${this.#areaPrefix}${name}:`, undefined)\n }\n\n /**\n * The same area scoped to one tenant. Throws a `TypeError` for an id that could escape its\n * namespace (see the module notes); re-scoping a tenant space is refused too.\n *\n * @example\n * space.tenant('acme').key('stats') // '<prefix>t:acme:stats'\n */\n tenant(id: string): KeySpace {\n if (this.tenantId !== undefined)\n throw new TypeError('This key space is already scoped to a tenant.')\n if (!isValidTenantId(id))\n throw new TypeError(\n 'A tenant id used in Redis keys may only contain letters, digits, _ and - (1 to 128 characters).',\n )\n return new KeySpace(this.#areaPrefix, id)\n }\n\n /**\n * The full key for `key`. Throws a `TypeError` for an empty or over-long key, or (in the global\n * space) a key that starts with the tenant marker `t:`.\n *\n * @example\n * KeySpace.root('blog:').area('cache').key('posts:1') // 'blog:cache:posts:1'\n */\n key(key: string): string {\n if (typeof key !== 'string' || key.length === 0)\n throw new TypeError('A Redis key must be a non-empty string.')\n if (Buffer.byteLength(key, 'utf8') > MAX_KEY_BYTES)\n throw new TypeError(`A Redis key may be at most ${MAX_KEY_BYTES} bytes.`)\n if (this.tenantId === undefined && key.startsWith(TENANT_MARKER))\n throw new TypeError(\n 'Keys starting with \"t:\" are reserved for tenant scopes; use space.tenant(id).key(...).',\n )\n return `${this.prefix}${key}`\n }\n\n /**\n * The `SCAN MATCH` pattern for every key in this space (and, for a global space, every tenant's\n * keys under it too: flushing an area clears it for all tenants).\n *\n * @example\n * KeySpace.root('a*:').area('cache').pattern() // 'a\\\\*:cache:*'\n */\n pattern(): string {\n return `${globEscape(this.prefix)}*`\n }\n}\n","/**\n * Connection settings: `config/redis.ts` (or Laravel's spot, `config/database.ts` → `redis`) plus\n * the `REDIS_*` variables in `.env`.\n *\n * | Setting | Config key | Variable | Default |\n * |---|---|---|---|\n * | Full URL (`redis://` or `rediss://`) | none (secret) | `REDIS_URL` | not set |\n * | Host | `host` | `REDIS_HOST` | `127.0.0.1` |\n * | Port | `port` | `REDIS_PORT` | `6379` |\n * | ACL user | `username` | `REDIS_USERNAME` | not set (the `default` user) |\n * | Password | none (secret) | `REDIS_PASSWORD` | not set |\n * | Database number | `database` | `REDIS_DB` | `0` |\n * | TLS | `tls` | `REDIS_TLS` | `false` (`true` for `rediss://`) |\n * | CA file for TLS | `tls_ca` | `REDIS_TLS_CA` | the system CAs |\n * | TLS server name | `tls_servername` | `REDIS_TLS_SERVERNAME` | the host |\n * | Key prefix | `prefix` | `REDIS_PREFIX` | the app name as a slug, then `:` |\n * | Connect timeout | `connect_timeout` | `REDIS_CONNECT_TIMEOUT` | `5000` ms |\n * | Command timeout | `command_timeout` | `REDIS_COMMAND_TIMEOUT` | `5000` ms |\n *\n * **Why the password and URL are never config keys:** the config tree is kept for every request,\n * written to `bootstrap/cache` by `node strut config:cache` and easy to dump while debugging (the\n * same reason `config/database.ts` leaves out `DB_PASSWORD`). They are read from the environment\n * only when the connection opens.\n *\n * **Fail closed:** a bad value (a port of `abc`, an unknown URL scheme, `REDIS_TLS=false` with a\n * `rediss://` URL) stops boot with `invalid_redis_config` instead of connecting somewhere\n * unexpected or in plain text. TLS always verifies the server certificate; there is no switch to\n * turn verification off.\n *\n * @module\n */\nimport { BootError } from '@strutvane/framework'\nimport { prefixProblem } from './keys.ts'\n\n/**\n * The resolved connection settings. `password` and `url` came from the environment and must never\n * be logged; use {@link describeSettings} for logs.\n *\n * @example\n * const settings = resolveRedisSettings({ env: { REDIS_HOST: 'cache.internal' } })\n */\nexport interface RedisSettings {\n readonly host: string\n readonly port: number\n readonly username: string | undefined\n readonly password: string | undefined\n readonly database: number\n readonly tls: boolean\n readonly tlsCaFile: string | undefined\n readonly tlsServername: string | undefined\n readonly prefix: string\n readonly connectTimeoutMs: number\n readonly commandTimeoutMs: number\n}\n\n/**\n * The non-secret settings an app may keep in `config/redis.ts`.\n *\n * @example\n * export default defineConfig((env) => ({ host: env.string('REDIS_HOST', '127.0.0.1') }) satisfies RedisConfig)\n */\nexport interface RedisConfig {\n readonly host?: string\n readonly port?: number | string\n readonly username?: string\n readonly database?: number | string\n readonly tls?: boolean | string\n readonly tls_ca?: string\n readonly tls_servername?: string\n readonly prefix?: string\n readonly connect_timeout?: number | string\n readonly command_timeout?: number | string\n}\n\n/**\n * What {@link resolveRedisSettings} reads.\n *\n * @example\n * resolveRedisSettings({ config: app.config('redis'), env, appName: 'Blog' })\n */\nexport interface ResolveOptions {\n /** The `redis` config tree (unchecked: it is validated here). */\n readonly config?: unknown\n /** The environment (`.env` merged under the process environment). */\n readonly env: Readonly<Record<string, string | undefined>>\n /** The app's name, for the default prefix. */\n readonly appName?: string\n}\n\nconst DEFAULT_TIMEOUT_MS = 5000\nconst MAX_TIMEOUT_MS = 600_000\nconst CONFIG_KEYS: ReadonlySet<string> = new Set([\n 'host',\n 'port',\n 'username',\n 'database',\n 'tls',\n 'tls_ca',\n 'tls_servername',\n 'prefix',\n 'connect_timeout',\n 'command_timeout',\n])\nconst SECRET_CONFIG_KEYS: ReadonlySet<string> = new Set(['password', 'url'])\n\n/**\n * Resolve and check the settings. Config keys win over variables (the config file usually reads\n * the same variables); `REDIS_URL` wins over the separate host, port, user, password and database.\n *\n * @example\n * resolveRedisSettings({ env: { REDIS_URL: 'rediss://app:secret@cache.example.com:6380/2' } })\n * // { host: 'cache.example.com', port: 6380, username: 'app', database: 2, tls: true, … }\n */\nexport function resolveRedisSettings(options: ResolveOptions): RedisSettings {\n const config = readConfig(options.config)\n const env = options.env\n const pick = (key: keyof RedisConfig, variable: string): string | undefined => {\n const fromConfig = config[key]\n if (fromConfig !== undefined && String(fromConfig).trim() !== '') return String(fromConfig)\n const fromEnv = env[variable]\n return fromEnv === undefined || fromEnv.trim() === '' ? undefined : fromEnv.trim()\n }\n\n let host = pick('host', 'REDIS_HOST') ?? '127.0.0.1'\n let port = integer(pick('port', 'REDIS_PORT'), 'REDIS_PORT', 6379, 1, 65_535)\n let username = pick('username', 'REDIS_USERNAME')\n let password = nonEmpty(env['REDIS_PASSWORD'])\n let database = integer(pick('database', 'REDIS_DB'), 'REDIS_DB', 0, 0, 1023)\n const tlsSetting = pick('tls', 'REDIS_TLS')\n let tls = tlsSetting === undefined ? false : flag(tlsSetting, 'REDIS_TLS')\n\n const url = nonEmpty(env['REDIS_URL'])\n if (url !== undefined) {\n const parsed = parseUrl(url)\n if (parsed.tls === true && tlsSetting !== undefined && !tls)\n throw invalid(\n 'REDIS_TLS is false but REDIS_URL uses rediss:// (TLS).',\n 'Remove REDIS_TLS, or set it to true. A TLS URL is never downgraded to plain text.',\n )\n host = parsed.host\n port = parsed.port\n username = parsed.username ?? username\n password = parsed.password ?? password\n database = parsed.database ?? database\n tls = tls || parsed.tls\n }\n\n const prefix = pick('prefix', 'REDIS_PREFIX') ?? defaultPrefix(options.appName ?? env['APP_NAME'])\n const problem = prefixProblem(prefix)\n if (problem !== undefined)\n throw invalid(`REDIS_PREFIX ${problem}.`, 'Example: REDIS_PREFIX=blog: (one prefix per app).')\n\n return Object.freeze({\n host,\n port,\n username,\n password,\n database,\n tls,\n tlsCaFile: pick('tls_ca', 'REDIS_TLS_CA'),\n tlsServername: pick('tls_servername', 'REDIS_TLS_SERVERNAME'),\n prefix,\n connectTimeoutMs: integer(\n pick('connect_timeout', 'REDIS_CONNECT_TIMEOUT'),\n 'REDIS_CONNECT_TIMEOUT',\n DEFAULT_TIMEOUT_MS,\n 1,\n MAX_TIMEOUT_MS,\n ),\n commandTimeoutMs: integer(\n pick('command_timeout', 'REDIS_COMMAND_TIMEOUT'),\n 'REDIS_COMMAND_TIMEOUT',\n DEFAULT_TIMEOUT_MS,\n 1,\n MAX_TIMEOUT_MS,\n ),\n })\n}\n\n/**\n * A log-safe description of the settings: no password, no URL.\n *\n * @example\n * logger.info('redis.connecting', describeSettings(settings))\n */\nexport function describeSettings(settings: RedisSettings): Readonly<Record<string, unknown>> {\n return {\n host: settings.host,\n port: settings.port,\n database: settings.database,\n tls: settings.tls,\n acl_user: settings.username ?? 'default',\n authenticated: settings.password !== undefined,\n prefix: settings.prefix,\n }\n}\n\n/**\n * The default key prefix: the app name as a lowercase slug, then `:` (`My Blog` → `my_blog:`).\n *\n * @example\n * defaultPrefix('My Blog') // 'my_blog:'\n */\nexport function defaultPrefix(appName: string | undefined): string {\n const slug = (appName ?? '')\n .normalize('NFKD')\n .replace(/\\p{M}/gu, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 64)\n return `${slug === '' ? 'strutvane' : slug}:`\n}\n\ninterface ParsedUrl {\n readonly host: string\n readonly port: number\n readonly username: string | undefined\n readonly password: string | undefined\n readonly database: number | undefined\n readonly tls: boolean\n}\n\nfunction parseUrl(text: string): ParsedUrl {\n let url: URL\n try {\n url = new URL(text)\n } catch {\n // Never echo the value: it may hold the password.\n throw invalid(\n 'REDIS_URL is not a valid URL.',\n 'Example: REDIS_URL=redis://user:pass@host:6379/0',\n )\n }\n if (url.protocol !== 'redis:' && url.protocol !== 'rediss:')\n throw invalid(\n `REDIS_URL must start with redis:// or rediss:// (it starts with ${url.protocol}//).`,\n 'Use rediss:// for TLS. Unix sockets and Sentinel/cluster URLs are not supported yet.',\n )\n if (url.hostname === '')\n throw invalid('REDIS_URL has no host.', 'Example: REDIS_URL=redis://127.0.0.1:6379/0')\n const path = url.pathname.replace(/^\\//, '')\n const database =\n path === '' ? undefined : integer(path, 'the database number in REDIS_URL', 0, 0, 1023)\n return {\n host: url.hostname.replace(/^\\[|\\]$/g, ''),\n port: integer(url.port === '' ? undefined : url.port, 'the port in REDIS_URL', 6379, 1, 65_535),\n username: url.username === '' ? undefined : safeDecode(url.username),\n password: url.password === '' ? undefined : safeDecode(url.password),\n database,\n tls: url.protocol === 'rediss:',\n }\n}\n\nfunction safeDecode(value: string): string {\n try {\n return decodeURIComponent(value)\n } catch {\n throw invalid(\n 'REDIS_URL has a badly encoded user name or password.',\n 'Percent-encode special characters in the user name and password (encodeURIComponent).',\n )\n }\n}\n\nfunction readConfig(value: unknown): RedisConfig {\n if (value === undefined || value === null) return {}\n if (typeof value !== 'object' || Array.isArray(value))\n throw invalid(\n 'The redis config must be an object such as { host, port, prefix }.',\n \"Example: defineConfig((env) => ({ host: env.string('REDIS_HOST', '127.0.0.1') }))\",\n )\n const record = value as Record<string, unknown>\n for (const key of Object.keys(record)) {\n if (SECRET_CONFIG_KEYS.has(key))\n throw invalid(\n `The redis config must not contain \"${key}\".`,\n `Keep secrets out of the config tree: set ${key === 'url' ? 'REDIS_URL' : 'REDIS_PASSWORD'} in .env; it is read when the connection opens.`,\n )\n if (!CONFIG_KEYS.has(key))\n throw invalid(\n `The redis config has an unknown key \"${key}\".`,\n `Known keys: ${[...CONFIG_KEYS].join(', ')}.`,\n )\n const item = record[key]\n if (item !== undefined && !['string', 'number', 'boolean'].includes(typeof item))\n throw invalid(\n `redis.${key} must be a string, number or boolean.`,\n 'Read it with env.string(...).',\n )\n }\n return record as RedisConfig\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n return value === undefined || value === '' ? undefined : value\n}\n\nfunction integer(\n value: string | undefined,\n name: string,\n fallback: number,\n min: number,\n max: number,\n): number {\n if (value === undefined) return fallback\n const trimmed = value.trim()\n const parsed = /^\\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN\n if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max)\n throw invalid(\n `${name} must be a whole number from ${min} to ${max}.`,\n `It is ${JSON.stringify(trimmed.slice(0, 20))}.`,\n )\n return parsed\n}\n\nfunction flag(value: string, name: string): boolean {\n const normalised = value.trim().toLowerCase()\n if (['true', '1', 'yes', 'on'].includes(normalised)) return true\n if (['false', '0', 'no', 'off'].includes(normalised)) return false\n throw invalid(`${name} must be true or false.`, `It is ${JSON.stringify(value.slice(0, 10))}.`)\n}\n\nfunction invalid(message: string, hint: string): BootError {\n return new BootError('invalid_redis_config', message, hint)\n}\n","/**\n * The error codes this package raises, in the framework's one error model (RFC 9457 `Problem`\n * with a stable lowercase `code`, RFC-0003). The provider registers them with the app's error\n * registry at boot, and the English catalog below gives clients a friendly title and detail.\n *\n * - `redis_unavailable` (503): the server can't be reached, timed out, or refused the login. The\n * caller learns nothing about the server (no host, no reply text); the log has the details.\n * - `lock_timeout` (503): `lock.block()` waited the full time and someone else still holds it.\n *\n * Boot-time problems (a bad `REDIS_*` value) are `BootError`s with the code `invalid_redis_config`,\n * because they stop the app before it serves anything.\n *\n * @module\n */\n\nimport type { ErrorDefinition } from '@strutvane/framework/core'\nimport { StrutvaneError } from '@strutvane/framework/core'\n\n/** The package name, recorded as the owner of each error code. */\nexport const PACKAGE_NAME = '@strutvane/redis'\n\n/**\n * The error definitions the provider registers.\n *\n * @example\n * for (const definition of REDIS_ERRORS) registry.register(definition)\n */\nexport const REDIS_ERRORS: readonly ErrorDefinition[] = Object.freeze([\n Object.freeze({\n code: 'redis_unavailable',\n status: 503,\n title: 'Service temporarily unavailable',\n owner: PACKAGE_NAME,\n }),\n Object.freeze({\n code: 'lock_timeout',\n status: 503,\n title: 'Resource busy',\n owner: PACKAGE_NAME,\n }),\n])\n\n/**\n * The English message catalog for the codes above (RFC-0003 keys).\n *\n * @example\n * REDIS_MESSAGES_EN['errors.lock_timeout.detail']\n */\nexport const REDIS_MESSAGES_EN: Readonly<Record<string, string>> = Object.freeze({\n 'errors.redis_unavailable.title': 'Service temporarily unavailable',\n 'errors.redis_unavailable.detail': 'The server is busy. Please try again in a moment.',\n 'errors.lock_timeout.title': 'Resource busy',\n 'errors.lock_timeout.detail': 'Someone else is working on this right now. Please try again.',\n})\n\n/**\n * A 503 `redis_unavailable` error. The cause stays on the error for the log, never for the client.\n *\n * @example\n * throw redisUnavailable('connect', cause)\n */\nexport function redisUnavailable(operation: string, cause?: unknown): StrutvaneError {\n return new StrutvaneError('redis_unavailable', {\n status: 503,\n params: { operation },\n headers: { 'Retry-After': '1' },\n ...(cause === undefined ? {} : { cause }),\n })\n}\n\n/**\n * A 503 `lock_timeout` error for the lock `name` (the name is the app's own key, never a secret).\n *\n * @example\n * throw lockTimeout('reports:build', 10)\n */\nexport function lockTimeout(name: string, waitedSeconds: number): StrutvaneError {\n return new StrutvaneError('lock_timeout', {\n status: 503,\n params: { lock: name, waited_seconds: waitedSeconds },\n headers: { 'Retry-After': '1' },\n })\n}\n","/**\n * The Redis connection: node-redis (`@redis/client`) behind the {@link RedisDriver} seam.\n *\n * **Why `@redis/client`:** it is the official, MIT-licensed client maintained by Redis Inc., works\n * with Valkey (same protocol), supports TLS, ACL users, RESP3, Sentinel and cluster, and has **no\n * runtime dependencies** (its two peers, OpenTelemetry and a hash library, are optional), so it\n * adds nothing to the supply chain beyond itself. `ioredis` is in maintenance mode and pulls six\n * dependencies.\n *\n * **Behaviour (and the failure scenarios it handles):**\n * - **Lazy:** nothing connects until the first command, so `node strut make:*` and other commands\n * that never touch Redis work while it is down.\n * - **Fails fast while down:** the offline queue is off, so a command during an outage fails at\n * once with the 503 `redis_unavailable` problem instead of piling up in memory. After a failed\n * connect, new attempts wait `retryAfterMs` (a small circuit breaker), so a dead server doesn't\n * make every request wait the full connect timeout.\n * - **Reconnects:** once connected, a dropped socket reconnects with capped, jittered backoff.\n * - **Bounded commands:** every command has a timeout (`REDIS_COMMAND_TIMEOUT`).\n * - **Login failures fail closed:** a wrong password or a missing ACL permission is\n * `redis_unavailable` for the caller and an error in the log (never the password).\n * - **Graceful shutdown:** {@link RedisConnection.close} waits for pending replies, at most\n * `closeTimeoutMs`, then drops the socket. Commands after close fail with `redis_unavailable`.\n * - **TLS** always verifies the certificate (system CAs, or `REDIS_TLS_CA`).\n *\n * Sentinel and cluster are not wired yet (see README, \"Not built yet\"): node-redis supports both,\n * and they will plug in behind the same {@link RedisDriver}.\n *\n * @module\n */\nimport { readFileSync } from 'node:fs'\nimport { createClient } from '@redis/client'\nimport { BootError } from '@strutvane/framework'\nimport type { Logger } from '@strutvane/framework/contracts'\nimport { StrutvaneError } from '@strutvane/framework/core'\nimport { describeSettings, type RedisSettings } from './config.ts'\nimport type { LuaScript, RedisDriver } from './driver.ts'\nimport { redisUnavailable } from './errors.ts'\n\n/**\n * The parts of a node-redis client this module uses (a seam for tests).\n *\n * @example\n * const client: RedisClientLike = createClient({ url })\n */\nexport interface RedisClientLike {\n connect(): Promise<unknown>\n sendCommand(args: readonly string[], options?: { readonly timeout?: number }): Promise<unknown>\n close(): Promise<void>\n destroy(): void\n readonly isOpen: boolean\n readonly isReady: boolean\n on(event: 'error', listener: (error: unknown) => void): unknown\n}\n\n/** The options node-redis gets (a subset of its `RedisClientOptions`). */\nexport interface RedisClientOptionsLike {\n readonly socket: Readonly<Record<string, unknown>>\n readonly username?: string\n readonly password?: string\n readonly database: number\n readonly disableOfflineQueue: boolean\n}\n\n/**\n * Options for {@link RedisConnection}.\n *\n * @example\n * new RedisConnection(settings, { logger: app.make(LoggerToken).child({ component: 'redis' }) })\n */\nexport interface RedisConnectionOptions {\n /** Where connection events go (never `console`). Omitted: silent. */\n readonly logger?: Logger\n /** How long {@link RedisConnection.close} waits for pending replies. Default 2000 ms. */\n readonly closeTimeoutMs?: number\n /** After a failed connect, fail fast for this long before trying again. Default 1000 ms. */\n readonly retryAfterMs?: number\n /** Build the client (tests). Default: node-redis `createClient`. */\n readonly createClient?: (options: RedisClientOptionsLike) => RedisClientLike\n}\n\n/** Server error prefixes that mean \"you may not\": wrong login or missing ACL permission. */\nconst AUTH_ERRORS = /^(WRONGPASS|NOAUTH|NOPERM)\\b/\n/** Socket error codes that may only appear in the message (node-redis wraps some errors). */\nconst NETWORK_ERROR =\n /\\bE(?:CONNREFUSED|CONNRESET|TIMEDOUT|NOTFOUND|PIPE|HOSTUNREACH|NETUNREACH|AI_AGAIN)\\b/\n/** Client-side error names that mean \"the server is not reachable right now\". */\nconst UNREACHABLE = new Set([\n 'ClientClosedError',\n 'ClientOfflineError',\n 'ConnectionTimeoutError',\n 'SocketTimeoutError',\n 'TimeoutError',\n 'SocketClosedUnexpectedlyError',\n 'DisconnectsClientError',\n 'ReconnectStrategyError',\n 'AbortError',\n])\n\n/**\n * One lazily opened connection, shared by every store of an app.\n *\n * @example\n * const redis = new RedisConnection(resolveRedisSettings({ env: process.env }))\n * await redis.command(['SET', 'k', 'v'])\n * await redis.close()\n */\nexport class RedisConnection implements RedisDriver {\n readonly settings: RedisSettings\n readonly #logger: Logger | undefined\n readonly #closeTimeoutMs: number\n readonly #retryAfterMs: number\n readonly #createClient: (options: RedisClientOptionsLike) => RedisClientLike\n #client: RedisClientLike | undefined\n #connecting: Promise<RedisClientLike> | undefined\n #everReady = false\n #closed = false\n #failedAt: number | undefined\n #down = false\n\n constructor(settings: RedisSettings, options: RedisConnectionOptions = {}) {\n this.settings = settings\n this.#logger = options.logger\n this.#closeTimeoutMs = options.closeTimeoutMs ?? 2000\n this.#retryAfterMs = options.retryAfterMs ?? 1000\n this.#createClient =\n options.createClient ?? ((clientOptions) => createClient(clientOptions) as RedisClientLike)\n }\n\n /** Whether {@link RedisConnection.close} has been called. */\n get closed(): boolean {\n return this.#closed\n }\n\n async command(args: readonly string[]): Promise<unknown> {\n const client = await this.#ready()\n try {\n return await client.sendCommand(args, { timeout: this.settings.commandTimeoutMs })\n } catch (error) {\n throw this.#translate(error, args[0] ?? 'command')\n }\n }\n\n async script(\n script: LuaScript,\n keys: readonly string[],\n args: readonly string[],\n ): Promise<unknown> {\n const tail = [String(keys.length), ...keys, ...args]\n try {\n return await this.command(['EVALSHA', script.sha1, ...tail])\n } catch (error) {\n // First use on this server (or after SCRIPT FLUSH / a failover): send the body once.\n if (error instanceof Error && error.message.startsWith('NOSCRIPT'))\n return this.command(['EVAL', script.source, ...tail])\n throw error\n }\n }\n\n async ping(): Promise<number> {\n const started = performance.now()\n await this.command(['PING'])\n return Math.max(0, Math.round((performance.now() - started) * 100) / 100)\n }\n\n /**\n * A health check for readiness probes: never throws.\n *\n * @example\n * const health = await redis.health() // { status: 'up', latency_ms: 0.4 }\n */\n async health(): Promise<\n | { readonly status: 'up'; readonly latency_ms: number }\n | { readonly status: 'down'; readonly error: string }\n > {\n try {\n return { status: 'up', latency_ms: await this.ping() }\n } catch (error) {\n const code = (error as { code?: unknown }).code\n return { status: 'down', error: typeof code === 'string' ? code : 'redis_unavailable' }\n }\n }\n\n async close(): Promise<void> {\n if (this.#closed) return\n this.#closed = true\n const pending = this.#connecting\n let client = this.#client\n if (client === undefined && pending !== undefined) client = await pending.catch(() => undefined)\n this.#client = undefined\n if (client === undefined || !client.isOpen) return\n let timer: NodeJS.Timeout | undefined\n const timedOut = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), this.#closeTimeoutMs)\n })\n try {\n const outcome = await Promise.race([client.close().then(() => 'closed' as const), timedOut])\n if (outcome === 'timeout') {\n this.#logger?.warn('redis.close_timeout', { timeout_ms: this.#closeTimeoutMs })\n client.destroy()\n }\n } catch {\n client.destroy()\n } finally {\n clearTimeout(timer)\n }\n this.#logger?.debug('redis.closed')\n }\n\n async #ready(): Promise<RedisClientLike> {\n if (this.#closed) throw redisUnavailable('closed')\n const client = this.#client\n if (client?.isReady === true) return client\n if (client?.isOpen === true) {\n // Open but reconnecting: fail fast instead of queueing (the offline queue is off).\n throw redisUnavailable('reconnecting')\n }\n if (this.#connecting !== undefined) return this.#connecting\n if (this.#failedAt !== undefined && Date.now() - this.#failedAt < this.#retryAfterMs)\n throw redisUnavailable('connect')\n this.#connecting = this.#open().finally(() => {\n this.#connecting = undefined\n })\n return this.#connecting\n }\n\n async #open(): Promise<RedisClientLike> {\n const client = this.#createClient(this.#clientOptions())\n client.on('error', (error) => this.#onError(error))\n try {\n await client.connect()\n } catch (error) {\n this.#failedAt = Date.now()\n try {\n client.destroy()\n } catch {\n // Already closed by the failed connect; nothing left to release.\n }\n this.#markDown(error)\n // Whatever stopped the connect (refused, timeout, TLS, a wrong login), the caller gets the\n // same fail-closed 503; the log has the reason.\n const translated = this.#translate(error, 'connect')\n throw translated instanceof StrutvaneError ? translated : redisUnavailable('connect', error)\n }\n if (this.#closed) {\n // close() ran while we were connecting: don't leak the socket.\n client.destroy()\n throw redisUnavailable('closed')\n }\n this.#client = client\n this.#everReady = true\n this.#failedAt = undefined\n if (this.#down) this.#logger?.info('redis.reconnected', describeSettings(this.settings))\n else this.#logger?.debug('redis.connected', describeSettings(this.settings))\n this.#down = false\n return client\n }\n\n #clientOptions(): RedisClientOptionsLike {\n const s = this.settings\n const socket: Record<string, unknown> = {\n host: s.host,\n port: s.port,\n connectTimeout: s.connectTimeoutMs,\n // Before the first successful connect, don't retry inside node-redis: the caller gets a\n // fast 503 and the next call tries again (after retryAfterMs). Once connected, a dropped\n // socket reconnects with capped, jittered backoff.\n reconnectStrategy: (retries: number, cause: Error): number | Error =>\n this.#everReady && !this.#closed\n ? Math.min(2000, 50 * 2 ** Math.min(retries, 6)) + Math.floor(Math.random() * 50)\n : cause,\n }\n if (s.tls) {\n socket['tls'] = true\n socket['rejectUnauthorized'] = true\n if (s.tlsServername !== undefined) socket['servername'] = s.tlsServername\n if (s.tlsCaFile !== undefined) socket['ca'] = readCa(s.tlsCaFile)\n }\n return {\n socket,\n ...(s.username === undefined ? {} : { username: s.username }),\n ...(s.password === undefined ? {} : { password: s.password }),\n database: s.database,\n disableOfflineQueue: true,\n }\n }\n\n #onError(error: unknown): void {\n // node-redis emits every socket problem here; without a listener it would crash the process.\n this.#markDown(error)\n }\n\n #markDown(error: unknown): void {\n if (this.#down) return\n this.#down = true\n this.#logger?.error('redis.unavailable', {\n ...describeSettings(this.settings),\n reason: reasonOf(error),\n })\n }\n\n #translate(error: unknown, operation: string): unknown {\n if (!(error instanceof Error)) return redisUnavailable(operation, error)\n if (AUTH_ERRORS.test(error.message)) {\n this.#logger?.error('redis.access_denied', {\n ...describeSettings(this.settings),\n reason: error.message.split(' ')[0],\n })\n return redisUnavailable(operation, error)\n }\n const code = (error as { code?: unknown }).code\n if (\n UNREACHABLE.has(error.name) ||\n (typeof code === 'string' && /^E[A-Z]+$/.test(code)) ||\n NETWORK_ERROR.test(error.message) ||\n /certificate|self[- ]signed|TLS|SSL/i.test(error.message)\n )\n return redisUnavailable(operation, error)\n // A server error reply (WRONGTYPE, a script error): a bug in the caller, so it stays loud.\n return error\n }\n}\n\nfunction readCa(path: string): Buffer {\n try {\n return readFileSync(path)\n } catch {\n throw new BootError(\n 'invalid_redis_config',\n `REDIS_TLS_CA points to a file that can't be read (${path}).`,\n 'Set REDIS_TLS_CA to the path of the PEM file with your CA certificate, or remove it to use the system CAs.',\n )\n }\n}\n\n/** A short, secret-free reason for the log. */\nfunction reasonOf(error: unknown): string {\n if (!(error instanceof Error)) return 'unknown'\n const code = (error as { code?: unknown }).code\n if (typeof code === 'string') return code\n return error.name === 'Error' ? (error.message.split(' ')[0] ?? 'Error') : error.name\n}\n","/**\n * The environment the connection settings are read from: `<app>/.env` merged under the process\n * environment (values set by the shell, Docker or CI win), the same rule the framework follows.\n *\n * **Why this package reads `.env` itself:** the framework keeps its merged environment private\n * (providers get the config tree, not the variables), and the Redis password must not be copied\n * into the config tree (see `config.ts`). Node's own `util.parseEnv` does the parsing, so there is\n * no hand-written parser here. Proposal in NEXT.md: the framework exposes the environment to\n * providers, and this file goes away.\n *\n * @module\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parseEnv } from 'node:util'\n\n/**\n * Read `<basePath>/.env` (when present) under `process.env`.\n *\n * @example\n * const env = loadRedisEnv('/srv/blog')\n * env['REDIS_HOST'] // from the process environment, else from .env\n */\nexport function loadRedisEnv(\n basePath: string,\n processEnv: Readonly<Record<string, string | undefined>> = process.env,\n): Readonly<Record<string, string | undefined>> {\n const file = join(basePath, '.env')\n const fromFile = existsSync(file) ? parseEnv(readFileSync(file, 'utf8')) : {}\n return { ...fromFile, ...processEnv }\n}\n","/**\n * `Idempotency-Key` storage in Redis: the framework's `IdempotencyStore`, shared by every process\n * so a retried request is replayed (not run twice) whichever server it reaches.\n *\n * Each claim is a hash `{ f: fingerprint, r: stored response }`:\n * - `begin` is one Lua script (`HSETNX` + expiry, else read the hash), so two parallel first\n * requests with the same key can't both run;\n * - `complete` stores the response only while the claim still exists (a released or expired claim\n * is not resurrected) and restarts the 24-hour replay window;\n * - an unfinished claim expires too, so a crashed request can't block its key forever.\n *\n * The framework's key already scopes claims to the caller; it is hashed (SHA-256) before it\n * reaches Redis, so actor ids and keys don't show up in dumps.\n *\n * @module\n */\nimport { createHash } from 'node:crypto'\nimport {\n type BeginOutcome,\n IDEMPOTENCY_TTL_MS,\n type IdempotencyStore,\n type StoredResponse,\n} from '@strutvane/framework'\nimport { asArray, asNullableString, defineLua, type RedisDriver } from './driver.ts'\nimport type { KeySpace } from './keys.ts'\n\nconst BEGIN = defineLua(`\nif redis.call('HSETNX', KEYS[1], 'f', ARGV[1]) == 1 then\n redis.call('PEXPIRE', KEYS[1], ARGV[2])\n return {}\nend\nreturn redis.call('HMGET', KEYS[1], 'f', 'r')\n`)\n\nconst COMPLETE = defineLua(`\nif redis.call('EXISTS', KEYS[1]) == 0 then return 0 end\nredis.call('HSET', KEYS[1], 'r', ARGV[1])\nredis.call('PEXPIRE', KEYS[1], ARGV[2])\nreturn 1\n`)\n\n/**\n * The idempotency store in Redis.\n *\n * @example\n * app.container.value(IdempotencyStoreToken, new RedisIdempotencyStore({ driver: redis, space }))\n */\nexport class RedisIdempotencyStore implements IdempotencyStore {\n readonly #driver: RedisDriver\n readonly #space: KeySpace\n readonly #ttlMs: number\n\n constructor(options: {\n readonly driver: RedisDriver\n readonly space: KeySpace\n /** How long a claim and its response live. Default 24 h (the framework's). */\n readonly ttlMs?: number\n }) {\n const ttl = options.ttlMs ?? IDEMPOTENCY_TTL_MS\n if (!Number.isSafeInteger(ttl) || ttl < 1)\n throw new RangeError('idempotency ttlMs must be a positive integer')\n this.#driver = options.driver\n this.#space = options.space\n this.#ttlMs = ttl\n }\n\n async begin(key: string, fingerprint: string, _now: number): Promise<BeginOutcome> {\n const reply = asArray(\n await this.#driver.script(BEGIN, [this.#key(key)], [fingerprint, String(this.#ttlMs)]),\n )\n if (reply.length === 0) return { kind: 'new' }\n const stored = asNullableString(reply[0])\n if (stored !== fingerprint) return { kind: 'mismatch' }\n const response = parseResponse(asNullableString(reply[1] ?? null))\n return response === undefined ? { kind: 'in_progress' } : { kind: 'replay', response }\n }\n\n async complete(key: string, response: StoredResponse, _now: number): Promise<void> {\n await this.#driver.script(\n COMPLETE,\n [this.#key(key)],\n [JSON.stringify(response), String(this.#ttlMs)],\n )\n }\n\n async release(key: string): Promise<void> {\n await this.#driver.command(['UNLINK', this.#key(key)])\n }\n\n #key(key: string): string {\n return this.#space.key(createHash('sha256').update(key).digest('hex'))\n }\n}\n\nfunction parseResponse(raw: string | null): StoredResponse | undefined {\n if (raw === null) return undefined\n try {\n const value: unknown = JSON.parse(raw)\n if (typeof value !== 'object' || value === null) return undefined\n const { status, headers, body } = value as Record<string, unknown>\n if (typeof status !== 'number' || typeof body !== 'string' || !Array.isArray(headers))\n return undefined\n const pairs = headers.filter(\n (pair): pair is [string, string] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n return { status, headers: pairs, body }\n } catch {\n return undefined\n }\n}\n","/**\n * Atomic locks (Laravel's `Cache::lock`): only one process at a time may hold a named lock.\n *\n * **How:** acquiring is `SET key <owner> NX PX <ttl>`: Redis guarantees only one caller creates\n * the key. The owner is a random 128-bit token, and releasing or extending runs a Lua script that\n * checks the token first, so:\n *\n * - a process can never release a lock someone else holds (for example after its own lock expired\n * and another process took it), the classic \"unsafe DEL\" bug;\n * - a crashed holder never blocks forever: every lock expires after its TTL;\n * - a long job can {@link RedisLock.extend} its lock while it still owns it.\n *\n * Another process can release a lock it was handed the owner token of\n * (`locks.restore(name, owner)`), as Laravel does for queued jobs.\n *\n * This is a single-instance lock (one Redis primary). It is not Redlock: during a primary\n * failover, a lock written to the old primary may be lost before it replicated. Use it to avoid\n * duplicate work, not as the only guard for correctness-critical money movements; those belong in a\n * database transaction.\n *\n * @module\n */\nimport { randomBytes } from 'node:crypto'\nimport { setTimeout as sleep } from 'node:timers/promises'\nimport { asInteger, defineLua, type RedisDriver } from './driver.ts'\nimport { lockTimeout } from './errors.ts'\nimport type { KeySpace } from './keys.ts'\n\nconst RELEASE = defineLua(`\nif redis.call('GET', KEYS[1]) == ARGV[1] then\n return redis.call('DEL', KEYS[1])\nend\nreturn 0\n`)\n\nconst EXTEND = defineLua(`\nif redis.call('GET', KEYS[1]) == ARGV[1] then\n return redis.call('PEXPIRE', KEYS[1], ARGV[2])\nend\nreturn 0\n`)\n\nconst OWNER = /^[A-Za-z0-9_-]{16,128}$/\n\n/**\n * Creates and restores locks in one key space.\n *\n * @example\n * const locks = new RedisLocks({ driver: redis, space: KeySpace.root('blog:').area('lock') })\n * await locks.create('reports:build', 120).block(10, () => buildReports())\n */\nexport class RedisLocks {\n readonly #driver: RedisDriver\n readonly #space: KeySpace\n\n constructor(options: { readonly driver: RedisDriver; readonly space: KeySpace }) {\n this.#driver = options.driver\n this.#space = options.space\n }\n\n /**\n * The same locks, scoped to one tenant (tenant A's `import` lock never blocks tenant B's).\n *\n * @example\n * locks.forTenant('acme').create('import', 60)\n */\n forTenant(tenantId: string): RedisLocks {\n return new RedisLocks({ driver: this.#driver, space: this.#space.tenant(tenantId) })\n }\n\n /**\n * A lock handle (not acquired yet) that expires `seconds` after it is acquired.\n *\n * @example\n * const lock = locks.create('invoices:send', 30)\n * if (await lock.acquire()) try { … } finally { await lock.release() }\n */\n create(name: string, seconds: number, owner?: string): RedisLock {\n if (!Number.isFinite(seconds) || seconds <= 0)\n throw new RangeError(\n 'A lock needs a lifetime in seconds above 0 (it expires if its holder crashes).',\n )\n if (owner !== undefined && !OWNER.test(owner))\n throw new TypeError('A lock owner must be 16 to 128 characters of A-Z, a-z, 0-9, _ or -.')\n return new RedisLock(\n this.#driver,\n name,\n this.#space.key(name),\n Math.max(1, Math.round(seconds * 1000)),\n owner ?? randomBytes(16).toString('base64url'),\n )\n }\n\n /**\n * A handle for a lock acquired elsewhere (another process) with a known owner token, so it can\n * be released or extended here.\n *\n * @example\n * await locks.restore('invoices:send', job.lockOwner).release()\n */\n restore(name: string, owner: string): RedisLock {\n return this.create(name, 1, owner)\n }\n}\n\n/**\n * One named lock and this handle's owner token.\n *\n * @example\n * const lock = locks.create('export', 60)\n * await lock.block(5, () => runExport())\n */\nexport class RedisLock {\n /** The lock's name (the caller's, without prefix). */\n readonly name: string\n /** This handle's owner token: pass it to another process to release the lock there. */\n readonly owner: string\n readonly #driver: RedisDriver\n readonly #key: string\n readonly #ttlMs: number\n\n /** @internal Use {@link RedisLocks.create}. */\n constructor(driver: RedisDriver, name: string, key: string, ttlMs: number, owner: string) {\n this.#driver = driver\n this.name = name\n this.#key = key\n this.#ttlMs = ttlMs\n this.owner = owner\n }\n\n /**\n * Try once; `true` when this handle now holds the lock. Re-acquiring a lock this owner already\n * holds is `false` (locks are not re-entrant).\n *\n * @example\n * if (await lock.acquire()) { … }\n */\n async acquire(): Promise<boolean> {\n const reply = await this.#driver.command([\n 'SET',\n this.#key,\n this.owner,\n 'NX',\n 'PX',\n String(this.#ttlMs),\n ])\n return reply !== null && reply !== undefined\n }\n\n /**\n * Wait up to `seconds` for the lock (polling with jittered backoff), then, when `work` is given,\n * run it and always release afterwards. Throws the 503 `lock_timeout` problem when the wait\n * runs out.\n *\n * @example\n * const total = await lock.block(5, () => recalculate())\n */\n async block<TResult>(\n seconds: number,\n work?: () => TResult | Promise<TResult>,\n ): Promise<TResult | undefined> {\n const deadline = Date.now() + Math.max(0, seconds) * 1000\n for (let attempt = 0; ; attempt++) {\n if (await this.acquire()) break\n const left = deadline - Date.now()\n if (left <= 0) throw lockTimeout(this.name, seconds)\n await sleep(\n Math.min(left, Math.min(250, 10 * 2 ** Math.min(attempt, 5)) + Math.random() * 10),\n )\n }\n if (work === undefined) return undefined\n try {\n return await work()\n } finally {\n await this.release()\n }\n }\n\n /**\n * Run `work` only if the lock is free right now (no waiting); `undefined` when it was taken.\n *\n * @example\n * await lock.run(() => sendDigest()) // skipped if another worker is sending it\n */\n async run<TResult>(work: () => TResult | Promise<TResult>): Promise<TResult | undefined> {\n if (!(await this.acquire())) return undefined\n try {\n return await work()\n } finally {\n await this.release()\n }\n }\n\n /**\n * Release the lock if this owner still holds it; `false` when it had expired or belongs to\n * someone else (nothing is removed then).\n *\n * @example\n * await lock.release()\n */\n async release(): Promise<boolean> {\n return asInteger(await this.#driver.script(RELEASE, [this.#key], [this.owner])) === 1\n }\n\n /**\n * Reset the lifetime to `seconds` from now if this owner still holds the lock.\n *\n * @example\n * await lock.extend(60) // a long import keeps its lock\n */\n async extend(seconds: number): Promise<boolean> {\n if (!Number.isFinite(seconds) || seconds <= 0)\n throw new RangeError('extend() needs seconds above 0.')\n const ms = String(Math.max(1, Math.round(seconds * 1000)))\n return asInteger(await this.#driver.script(EXTEND, [this.#key], [this.owner, ms])) === 1\n }\n\n /**\n * Remove the lock whoever holds it (an operator's escape hatch).\n *\n * @example\n * await locks.create('stuck-job', 1).forceRelease()\n */\n async forceRelease(): Promise<void> {\n await this.#driver.command(['UNLINK', this.#key])\n }\n\n /**\n * Whether this owner holds the lock right now.\n *\n * @example\n * if (!(await lock.isOwned())) throw new Error('lost the lock')\n */\n async isOwned(): Promise<boolean> {\n return (await this.#driver.command(['GET', this.#key])) === this.owner\n }\n}\n","/**\n * Rate limiting in Redis: fixed and sliding windows, each one atomic Lua script, so limits hold\n * across every process and server of the app even under bursts of parallel requests.\n *\n * - **Fixed window** (`algorithm: 'fixed'`, the default; what the framework's `throttle` does):\n * one counter per window. Cheap (one key, one integer), but a client can send `2 × max` around\n * a window boundary.\n * - **Sliding window** (`'sliding'`): a sorted set of the accepted hits in the last window.\n * Exact: never more than `max` hits in any `windowSeconds` span. Costs one entry per accepted\n * hit (bounded by `max`); refused hits are not recorded, so a client hammering a closed limit\n * can't grow memory.\n *\n * Time comes from the Redis server (`TIME` inside the script), so app servers with skewed clocks\n * still share one window.\n *\n * The framework's `throttle` middleware counts in the default cache store, so with\n * `CACHE_STORE=redis` it already uses Redis (fixed windows). This class is for limits in your own\n * code (`await limiter.hit(\\`export:${user.id}\\`, { max: 5, windowSeconds: 3600 })`).\n *\n * @module\n */\nimport { randomBytes } from 'node:crypto'\nimport { asArray, asInteger, defineLua, type RedisDriver } from './driver.ts'\nimport type { KeySpace } from './keys.ts'\n\n/**\n * A limit: at most `max` hits per `windowSeconds`.\n *\n * @example\n * const limit: RateLimit = { max: 60, windowSeconds: 60, algorithm: 'sliding' }\n */\nexport interface RateLimit {\n readonly max: number\n readonly windowSeconds: number\n /** Default `fixed`. */\n readonly algorithm?: 'fixed' | 'sliding'\n}\n\n/**\n * The outcome of one hit.\n *\n * @example\n * if (!result.allowed) throw new RateLimitedError({ retryAfter: result.retryAfterSeconds })\n */\nexport interface RateLimitResult {\n readonly allowed: boolean\n readonly limit: number\n /** Hits left in the current window (0 when refused). */\n readonly remaining: number\n /** Seconds until a hit can succeed again (0 when allowed). */\n readonly retryAfterSeconds: number\n}\n\n// Returns {count, pttl}. A key that somehow lost its expiry gets it back (never a permanent ban).\nconst FIXED = defineLua(`\nlocal count = redis.call('INCR', KEYS[1])\nlocal ttl = redis.call('PTTL', KEYS[1])\nif count == 1 or ttl < 0 then\n redis.call('PEXPIRE', KEYS[1], ARGV[1])\n ttl = tonumber(ARGV[1])\nend\nreturn {count, ttl}\n`)\n\n// Returns {allowed (1/0), count after, retry ms}.\nconst SLIDING = defineLua(`\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal window = tonumber(ARGV[2])\nlocal limit = tonumber(ARGV[1])\nredis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - window)\nlocal count = redis.call('ZCARD', KEYS[1])\nif count < limit then\n redis.call('ZADD', KEYS[1], now, ARGV[3])\n redis.call('PEXPIRE', KEYS[1], window)\n return {1, count + 1, 0}\nend\nlocal oldest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')\nlocal retry = window\nif oldest[2] then retry = tonumber(oldest[2]) + window - now end\nif retry < 1 then retry = 1 end\nreturn {0, count, retry}\n`)\n\n/**\n * A rate limiter in one key space.\n *\n * @example\n * const limiter = new RedisRateLimiter({ driver: redis, space: KeySpace.root('blog:').area('rate') })\n * const result = await limiter.hit(`login:${email}`, { max: 5, windowSeconds: 60, algorithm: 'sliding' })\n */\nexport class RedisRateLimiter {\n readonly #driver: RedisDriver\n readonly #space: KeySpace\n\n constructor(options: { readonly driver: RedisDriver; readonly space: KeySpace }) {\n this.#driver = options.driver\n this.#space = options.space\n }\n\n /**\n * The same limiter, scoped to one tenant.\n *\n * @example\n * limiter.forTenant('acme').hit('exports', { max: 10, windowSeconds: 3600 })\n */\n forTenant(tenantId: string): RedisRateLimiter {\n return new RedisRateLimiter({ driver: this.#driver, space: this.#space.tenant(tenantId) })\n }\n\n /**\n * Count one hit and say whether it is within the limit.\n *\n * @example\n * const { allowed, retryAfterSeconds } = await limiter.hit('api:42', { max: 60, windowSeconds: 60 })\n */\n async hit(key: string, limit: RateLimit): Promise<RateLimitResult> {\n const { max, windowMs } = check(limit)\n if (limit.algorithm === 'sliding') {\n const [allowed, count, retry] = asArray(\n await this.#driver.script(\n SLIDING,\n [this.#space.key(`s:${key}`)],\n [String(max), String(windowMs), randomBytes(9).toString('base64url')],\n ),\n ).map(asInteger)\n const ok = allowed === 1\n return {\n allowed: ok,\n limit: max,\n remaining: ok ? Math.max(0, max - (count ?? max)) : 0,\n retryAfterSeconds: ok ? 0 : Math.max(1, Math.ceil((retry ?? windowMs) / 1000)),\n }\n }\n const [count, ttl] = asArray(\n await this.#driver.script(FIXED, [this.#space.key(`f:${key}`)], [String(windowMs)]),\n ).map(asInteger)\n const hits = count ?? max + 1\n const ok = hits <= max\n return {\n allowed: ok,\n limit: max,\n remaining: Math.max(0, max - hits),\n retryAfterSeconds: ok ? 0 : Math.max(1, Math.ceil((ttl ?? windowMs) / 1000)),\n }\n }\n\n /**\n * Run `work` only when the hit is allowed; returns the result, or `undefined` when limited.\n *\n * @example\n * await limiter.attempt(`digest:${user.id}`, { max: 1, windowSeconds: 3600 }, () => sendDigest(user))\n */\n async attempt<TResult>(\n key: string,\n limit: RateLimit,\n work: () => TResult | Promise<TResult>,\n ): Promise<TResult | undefined> {\n return (await this.hit(key, limit)).allowed ? work() : undefined\n }\n\n /**\n * Reset a key's counters (both algorithms), for example after a successful login.\n *\n * @example\n * await limiter.clear(`login:${email}`)\n */\n async clear(key: string): Promise<void> {\n await this.#driver.command(['UNLINK', this.#space.key(`f:${key}`), this.#space.key(`s:${key}`)])\n }\n}\n\nfunction check(limit: RateLimit): { readonly max: number; readonly windowMs: number } {\n if (!Number.isSafeInteger(limit.max) || limit.max < 1)\n throw new RangeError('A rate limit needs max to be a whole number of at least 1.')\n if (!Number.isFinite(limit.windowSeconds) || limit.windowSeconds <= 0)\n throw new RangeError('A rate limit needs windowSeconds above 0.')\n if (limit.algorithm !== undefined && limit.algorithm !== 'fixed' && limit.algorithm !== 'sliding')\n throw new RangeError('A rate limit algorithm is \"fixed\" or \"sliding\".')\n return { max: limit.max, windowMs: Math.max(1, Math.round(limit.windowSeconds * 1000)) }\n}\n","/**\n * Sessions in Redis: the framework's `SessionStore` (`flush`, for `node strut session:flush`) plus\n * the read / write / touch / destroy operations a session driver needs.\n *\n * - **Session ids never reach Redis in clear text.** The key is the SHA-256 of the id, so a dump,\n * a replica, `MONITOR` or a slow log never reveals a usable session cookie.\n * - **Ids are checked:** 22 to 256 characters of `A-Z a-z 0-9 _ -` (at least 128 bits of a\n * base64url id). Anything else is refused before Redis is asked, so a forged cookie can't\n * probe keys.\n * - **Bounded:** a session over `maxBytes` (default 256 KiB) is refused instead of stored, so a\n * bug or an attacker can't fill the server through one session.\n * - **Idle expiry** is Redis's TTL: `write` and `touch` reset it to `SESSION_LIFETIME`.\n *\n * Sessions belong to `@strutvane/auth`. It can use this store through the framework's session\n * contract once that contract has these operations (see NEXT.md, framework proposals); until then\n * the provider binds it under the framework's `SessionStoreToken` (`flush`) when\n * `SESSION_DRIVER=redis`.\n *\n * @module\n */\nimport { createHash } from 'node:crypto'\nimport type { SessionStore } from '@strutvane/framework'\nimport { asInteger, asNullableString, deleteMatching, type RedisDriver } from './driver.ts'\nimport type { KeySpace } from './keys.ts'\n\nconst SESSION_ID = /^[A-Za-z0-9_-]{22,256}$/\n\n/**\n * Options for {@link RedisSessionStore}.\n *\n * @example\n * new RedisSessionStore({ driver: redis, space: KeySpace.root('blog:').area('session'), lifetimeSeconds: 7200 })\n */\nexport interface RedisSessionStoreOptions {\n readonly driver: RedisDriver\n readonly space: KeySpace\n /** Idle lifetime (`SESSION_LIFETIME` minutes × 60). Default 7200 s. */\n readonly lifetimeSeconds?: number\n /** The largest session accepted, in bytes of JSON. Default 256 KiB. */\n readonly maxBytes?: number\n}\n\n/**\n * A session store in Redis.\n *\n * @example\n * await sessions.write(id, { userId: 7 })\n * const data = await sessions.read(id) // { userId: 7 }\n */\nexport class RedisSessionStore implements SessionStore {\n readonly #driver: RedisDriver\n readonly #space: KeySpace\n readonly #lifetimeMs: number\n readonly #maxBytes: number\n\n constructor(options: RedisSessionStoreOptions) {\n const lifetime = options.lifetimeSeconds ?? 7200\n const maxBytes = options.maxBytes ?? 256 * 1024\n if (!Number.isSafeInteger(lifetime) || lifetime < 1)\n throw new RangeError('The session lifetime must be a whole number of seconds, at least 1.')\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)\n throw new RangeError('The session size limit must be a whole number of bytes, at least 1.')\n this.#driver = options.driver\n this.#space = options.space\n this.#lifetimeMs = lifetime * 1000\n this.#maxBytes = maxBytes\n }\n\n /**\n * The session's data, or `undefined` when it doesn't exist, expired, or the id is malformed.\n *\n * @example\n * const data = await sessions.read(cookieValue)\n */\n async read(id: string): Promise<Record<string, unknown> | undefined> {\n const key = this.#key(id)\n if (key === undefined) return undefined\n const raw = asNullableString(await this.#driver.command(['GET', key]))\n if (raw === null) return undefined\n try {\n const parsed: unknown = JSON.parse(raw)\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n }\n\n /**\n * Store the session's data and reset its idle expiry. Throws a `TypeError` for a malformed id and\n * a `RangeError` for data over the size limit.\n *\n * @example\n * await sessions.write(id, { userId: 7, csrf: token })\n */\n async write(id: string, data: Readonly<Record<string, unknown>>): Promise<void> {\n const key = this.#key(id)\n if (key === undefined) throw new TypeError('Refusing to write a session with a malformed id.')\n const encoded = JSON.stringify(data)\n if (Buffer.byteLength(encoded, 'utf8') > this.#maxBytes)\n throw new RangeError(\n `The session is larger than ${this.#maxBytes} bytes; keep large data in the database and its id in the session.`,\n )\n await this.#driver.command(['SET', key, encoded, 'PX', String(this.#lifetimeMs)])\n }\n\n /**\n * Reset the idle expiry without rewriting the data; `false` when the session is gone.\n *\n * @example\n * await sessions.touch(id)\n */\n async touch(id: string): Promise<boolean> {\n const key = this.#key(id)\n if (key === undefined) return false\n return asInteger(await this.#driver.command(['PEXPIRE', key, String(this.#lifetimeMs)])) === 1\n }\n\n /**\n * Remove one session (sign-out, id rotation); `true` when it existed.\n *\n * @example\n * await sessions.destroy(oldId)\n */\n async destroy(id: string): Promise<boolean> {\n const key = this.#key(id)\n if (key === undefined) return false\n return asInteger(await this.#driver.command(['UNLINK', key])) > 0\n }\n\n /** Remove every session of this app; returns how many were removed. */\n async flush(): Promise<number> {\n return deleteMatching(this.#driver, this.#space.pattern())\n }\n\n #key(id: string): string | undefined {\n if (typeof id !== 'string' || !SESSION_ID.test(id)) return undefined\n return this.#space.key(createHash('sha256').update(id).digest('hex'))\n }\n}\n","/**\n * Container tokens this package binds (integration-map connection 2: container tokens). Other\n * packages and apps resolve the Redis services through these, never by importing this package's\n * classes directly.\n *\n * @module\n */\nimport { type Token, token } from '@strutvane/framework/core'\nimport type { RedisConnection } from './connection.ts'\nimport type { KeySpace } from './keys.ts'\nimport type { RedisLocks } from './lock.ts'\nimport type { RedisRateLimiter } from './rate-limiter.ts'\n\n/**\n * The app's shared Redis connection (lazily connected; closed on shutdown).\n *\n * @example\n * const health = await app.make(RedisConnectionToken).health()\n */\nexport const RedisConnectionToken: Token<RedisConnection> = token<RedisConnection>(\n 'strutvane.redis.connection',\n)\n\n/**\n * The app's root key space (`REDIS_PREFIX`).\n *\n * @example\n * app.make(RedisKeySpaceToken).area('reports').key('daily')\n */\nexport const RedisKeySpaceToken: Token<KeySpace> = token<KeySpace>('strutvane.redis.keys')\n\n/**\n * Atomic locks (`<prefix>lock:…`).\n *\n * @example\n * await app.make(RedisLocksToken).create('reports:build', 120).block(10, build)\n */\nexport const RedisLocksToken: Token<RedisLocks> = token<RedisLocks>('strutvane.redis.locks')\n\n/**\n * The rate limiter (`<prefix>rate:…`).\n *\n * @example\n * await app.make(RedisRateLimiterToken).hit(`export:${user.id}`, { max: 5, windowSeconds: 3600 })\n */\nexport const RedisRateLimiterToken: Token<RedisRateLimiter> = token<RedisRateLimiter>(\n 'strutvane.redis.rateLimiter',\n)\n"],"mappings":";;;;;;;;;;AA6CA,MAAM,YAAY,UAAU;;;;;;;;;;;CAW3B;AAGD,MAAM,WAAW,UAAU;;;;;;;;;CAS1B;;;;;;;;;AAgBD,IAAa,kBAAb,MAAa,gBAAsC;CACxC;CACA;CACA;CAET,YAAY,SAAiC;EAC3C,KAAK,UAAU,QAAQ;EACvB,KAAK,SAAS,QAAQ;EACtB,KAAK,UAAU,QAAQ;CACzB;;CAGA,IAAI,SAAiB;EACnB,OAAO,KAAK,OAA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AAU,MAAM,KAAK,QAAQ,QAAQ;GAAC;GAAW;GAAK,OAAO,KAAK,WAAW;EAAC,CAAC,CAAC,MAAM;CAC/F;;;;;;;CAQA,MAAM,QAAQ,IAA8B;EAC1C,MAAM,MAAM,KAAK,KAAK,EAAE;EACxB,IAAI,QAAQ,KAAA,GAAW,OAAO;EAC9B,OAAO,UAAU,MAAM,KAAK,QAAQ,QAAQ,CAAC,UAAU,GAAG,CAAC,CAAC,IAAI;CAClE;;CAGA,MAAM,QAAyB;EAC7B,OAAO,eAAe,KAAK,SAAS,KAAK,OAAO,QAAQ,CAAC;CAC3D;CAEA,KAAK,IAAgC;EACnC,IAAI,OAAO,OAAO,YAAY,CAAC,WAAW,KAAK,EAAE,GAAG,OAAO,KAAA;EAC3D,OAAO,KAAK,OAAO,IAAI,WAAW,QAAQ,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,OAAO,KAAK,CAAC;CACtE;AACF;;;;;;;;;;;;;;;ACzHA,MAAa,uBAA+C,MAC1D,4BACF;;;;;;;AAQA,MAAa,qBAAsC,MAAgB,sBAAsB;;;;;;;AAQzF,MAAa,kBAAqC,MAAkB,uBAAuB;;;;;;;AAQ3F,MAAa,wBAAiD,MAC5D,6BACF"}
package/package.json CHANGED
@@ -1,6 +1,107 @@
1
1
  {
2
2
  "name": "@strutvane/redis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-next.0",
4
+ "description": "Redis and Valkey for Strutvane apps: a cache store, atomic locks, a session store, rate limiting, an idempotency store and an experimental queue driver, with per-app and per-tenant key prefixes.",
5
+ "keywords": [
6
+ "strutvane",
7
+ "typescript",
8
+ "redis",
9
+ "valkey",
10
+ "cache",
11
+ "locks",
12
+ "sessions",
13
+ "rate-limit",
14
+ "queue"
15
+ ],
16
+ "homepage": "https://github.com/vishwajit-vm/strutvane-redis#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/vishwajit-vm/strutvane-redis/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/vishwajit-vm/strutvane-redis.git"
23
+ },
24
+ "license": "MIT",
25
+ "author": "The Strutvane Authors",
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.mts",
31
+ "default": "./dist/index.mjs"
32
+ },
33
+ "./provider": {
34
+ "types": "./dist/provider.d.mts",
35
+ "default": "./dist/provider.mjs"
36
+ },
37
+ "./installer": {
38
+ "types": "./dist/installer.d.mts",
39
+ "default": "./dist/installer.mjs"
40
+ },
41
+ "./queue": {
42
+ "types": "./dist/queue.d.mts",
43
+ "default": "./dist/queue.mjs"
44
+ },
45
+ "./package.json": "./package.json"
46
+ },
47
+ "files": [
48
+ "dist",
49
+ "README.md",
50
+ "LICENSE"
51
+ ],
52
+ "engines": {
53
+ "node": ">=24.3"
54
+ },
55
+ "devEngines": {
56
+ "packageManager": {
57
+ "name": "npm",
58
+ "version": ">=11.19.0",
59
+ "onFail": "error"
60
+ }
61
+ },
62
+ "publishConfig": {
63
+ "access": "public",
64
+ "provenance": true
65
+ },
66
+ "scripts": {
67
+ "lint": "biome check .",
68
+ "format": "biome check --write .",
69
+ "typecheck": "tsc --noEmit",
70
+ "test": "vitest run",
71
+ "test:coverage": "vitest run --coverage",
72
+ "test:integration": "vitest run --config vitest.integration.config.ts --coverage",
73
+ "build": "tsdown",
74
+ "ci": "biome check . && tsc --noEmit && vitest run --coverage && tsdown",
75
+ "changeset": "changeset",
76
+ "version-packages": "changeset version",
77
+ "release": "changeset publish",
78
+ "test:perf": "vitest run --config vitest.perf.config.ts"
79
+ },
80
+ "strutvane": {
81
+ "compat": "^0.2.0-next.0",
82
+ "installer": "./dist/installer.mjs"
83
+ },
84
+ "dependencies": {
85
+ "@redis/client": "6.3.1"
86
+ },
87
+ "peerDependencies": {
88
+ "@strutvane/framework": "^0.2.0-next.0"
89
+ },
90
+ "devDependencies": {
91
+ "@biomejs/biome": "2.6.7",
92
+ "@changesets/cli": "3.0.3",
93
+ "@strutvane/framework": "0.2.0-next.1",
94
+ "@types/node": "24.19.2",
95
+ "@vitest/coverage-v8": "5.1.0",
96
+ "fast-check": "4.10.2",
97
+ "tsdown": "0.23.7",
98
+ "typescript": "6.0.3",
99
+ "vitest": "5.1.0"
100
+ },
101
+ "allowScripts": {
102
+ "esbuild@0.18.20": true,
103
+ "esbuild@0.25.12": true,
104
+ "esbuild@0.28.2": true,
105
+ "fsevents@2.3.3": false
106
+ }
107
+ }