@idempotix/redis 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 stacks0x
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 stacks0x
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ npm install @idempotix/core @idempotix/redis ioredis
|
|
|
16
16
|
import { redis } from '@idempotix/redis';
|
|
17
17
|
import { express as idempotent } from '@idempotix/express';
|
|
18
18
|
|
|
19
|
-
// From environment variable (
|
|
19
|
+
// From environment variable (IDEMPOTIX_REDIS_URL)
|
|
20
20
|
app.post('/orders', idempotent({ storage: redis() }), handler);
|
|
21
21
|
```
|
|
22
22
|
|
|
@@ -47,7 +47,7 @@ const storage = redis({ client });
|
|
|
47
47
|
|
|
48
48
|
| Variable | Description |
|
|
49
49
|
| --------------------- | ---------------------------------------------------------- |
|
|
50
|
-
| `
|
|
50
|
+
| `IDEMPOTIX_REDIS_URL` | Redis connection URL (e.g., `redis://:password@host:6379`) |
|
|
51
51
|
|
|
52
52
|
## Redis Cluster
|
|
53
53
|
|
package/dist/index.cjs
CHANGED
|
@@ -7,7 +7,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
7
7
|
var Redis__default = /*#__PURE__*/_interopDefault(Redis);
|
|
8
8
|
|
|
9
9
|
// src/index.ts
|
|
10
|
-
var ENV_REDIS_URL = "
|
|
10
|
+
var ENV_REDIS_URL = "IDEMPOTIX_REDIS_URL";
|
|
11
11
|
var ACQUIRE_SCRIPT = `
|
|
12
12
|
local key = KEYS[1]
|
|
13
13
|
local hash = ARGV[1]
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["Redis"],"mappings":";;;;;;;;;AAcA,IAAM,aAAA,GAAgB,qBAAA;AAgDtB,IAAM,cAAA,GAAiB;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA8ChB,IAAM,eAAN,MAA6C;AAAA,EACjC,MAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,cAAA;AAAA,EAET,YAAY,OAAA,EAA4E;AACtF,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,OAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,YAAA;AACtC,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,WAAA;AAC1B,IAAA,IAAA,CAAK,cAAA,GAAiB,OAAA,CAAQ,cAAA,IAAkB,EAAA,GAAK,IAAA,GAAO,IAAA;AAAA,EAC9D;AAAA,EAEQ,UAAU,GAAA,EAAqB;AACrC,IAAA,OAAO,CAAA,EAAG,IAAA,CAAK,SAAS,CAAA,EAAG,GAA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n * Uses ioredis for standard Redis connections (TCP-based).\n * For HTTP-based Redis (Upstash, Vercel KV), use @idempotix/upstash.\n */\n\nimport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\nimport Redis, { type Cluster } from 'ioredis';\n\n/**\n * Environment variable for Redis URL.\n * Scoped to Idempotix to avoid accidental connections.\n */\nconst ENV_REDIS_URL = 'Idempotix_REDIS_URL';\n\n/**\n * Options for the Redis storage adapter.\n */\nexport interface RedisOptions {\n /**\n * Redis connection URL.\n * If not provided, uses Idempotix_REDIS_URL environment variable.\n */\n url?: string;\n\n /**\n * Existing ioredis client instance.\n * Takes precedence over url if provided.\n */\n client?: Redis | Cluster;\n\n /**\n * Key prefix for namespacing.\n * @default 'Idempotix:'\n */\n keyPrefix?: string;\n\n /**\n * Maximum payload size in bytes.\n * Responses exceeding this limit will skip caching.\n * Set to 0 to disable size checking.\n * @default 10485760 (10MB)\n */\n maxPayloadSize?: number;\n}\n\n/**\n * Internal record structure stored in Redis.\n */\ninterface RedisRecord {\n status: 'in_progress' | 'completed';\n hash: string | null;\n data?: unknown;\n createdAt: number;\n startedAt: number;\n}\n\n/**\n * Lua script for atomic acquire.\n * Returns: null if acquired, JSON string if exists\n */\nconst ACQUIRE_SCRIPT = `\nlocal key = KEYS[1]\nlocal hash = ARGV[1]\nlocal ttl = tonumber(ARGV[2])\nlocal now = tonumber(ARGV[3])\n\nlocal existing = redis.call('GET', key)\nif existing then\n return existing\nend\n\nlocal record = cjson.encode({\n status = 'in_progress',\n hash = hash ~= '' and hash or nil,\n startedAt = now\n})\nredis.call('SET', key, record, 'PX', ttl)\nreturn nil\n`;\n\n/**\n * Redis storage adapter using ioredis.\n *\n * Works with:\n * - Self-hosted Redis\n * - AWS ElastiCache\n * - Redis Cloud\n * - Azure Cache for Redis\n * - DigitalOcean Managed Redis\n * - Any Redis-compatible service via TCP\n *\n * @example\n * ```typescript\n * import { redis } from '@idempotix/redis';\n *\n * // From environment (Idempotix_REDIS_URL)\n * const storage = redis();\n *\n * // From URL\n * const storage = redis('redis://localhost:6379');\n *\n * // With existing client\n * import Redis from 'ioredis';\n * const storage = redis({ client: new Redis() });\n * ```\n */\nexport class RedisStorage implements StorageAdapter {\n private readonly client: Redis | Cluster;\n private readonly keyPrefix: string;\n private readonly ownsClient: boolean;\n\n /**\n * Maximum payload size in bytes (default: 10MB).\n * Prevents excessively large values from being stored in Redis.\n */\n readonly maxPayloadSize: number;\n\n constructor(options: RedisOptions & { _client: Redis | Cluster; _ownsClient: boolean }) {\n this.client = options._client;\n this.keyPrefix = options.keyPrefix ?? 'Idempotix:';\n this.ownsClient = options._ownsClient;\n this.maxPayloadSize = options.maxPayloadSize ?? 10 * 1024 * 1024;\n }\n\n private prefixKey(key: string): string {\n return `${this.keyPrefix}${key}`;\n }\n\n async acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult> {\n const prefixedKey = this.prefixKey(key);\n const now = Date.now();\n\n // Try to get existing or set new atomically\n const result = (await (this.client as Redis).eval(\n ACQUIRE_SCRIPT,\n 1,\n prefixedKey,\n hash ?? '',\n ttl.toString(),\n now.toString()\n )) as string | null;\n\n // Lock acquired\n if (result === null) {\n return { status: 'acquired' };\n }\n\n // Parse existing record\n let existing: RedisRecord;\n try {\n existing = JSON.parse(result);\n } catch {\n // Corrupted data, delete and try again\n await this.client.del(prefixedKey);\n return { status: 'acquired' };\n }\n\n // Check for hash mismatch\n if (hash && existing.hash && existing.hash !== hash) {\n return {\n status: 'mismatch',\n existingHash: existing.hash,\n providedHash: hash,\n };\n }\n\n // If completed, return cached response\n if (existing.status === 'completed') {\n return {\n status: 'hit',\n response: {\n data: existing.data,\n createdAt: existing.createdAt,\n hash: existing.hash,\n },\n };\n }\n\n // If in progress, return conflict\n return { status: 'conflict', startedAt: existing.startedAt };\n }\n\n async save(key: string, response: StoredResponse): Promise<void> {\n const prefixedKey = this.prefixKey(key);\n\n // Get existing record to preserve TTL\n const existing = await this.client.get(prefixedKey);\n if (!existing) return;\n\n const ttl = await this.client.pttl(prefixedKey);\n if (ttl <= 0) return;\n\n const record: RedisRecord = {\n status: 'completed',\n hash: response.hash,\n data: response.data,\n createdAt: response.createdAt,\n startedAt: Date.now(),\n };\n\n await this.client.set(prefixedKey, JSON.stringify(record), 'PX', ttl);\n }\n\n async release(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async delete(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async clear(): Promise<void> {\n const keys = await this.client.keys(`${this.keyPrefix}*`);\n if (keys.length > 0) {\n await this.client.del(...keys);\n }\n }\n\n /**\n * Disconnect the Redis client if we own it.\n * Call this during shutdown if using auto-created client.\n */\n async disconnect(): Promise<void> {\n if (this.ownsClient) {\n await this.client.quit();\n }\n }\n}\n\n/**\n * Create a Redis storage adapter.\n *\n * @example\n * ```typescript\n * import { idempotix } from '@idempotix/core';\n * import { redis } from '@idempotix/redis';\n *\n * // Auto-detect from Idempotix_REDIS_URL\n * idempotix.configure({ storage: redis() });\n *\n * // With explicit URL\n * idempotix.configure({ storage: redis('redis://localhost:6379') });\n *\n * // With options\n * idempotix.configure({\n * storage: redis({\n * url: 'redis://localhost:6379',\n * keyPrefix: 'myapp:',\n * }),\n * });\n *\n * // With existing client\n * import Redis from 'ioredis';\n * idempotix.configure({\n * storage: redis({ client: new Redis() }),\n * });\n * ```\n */\nexport function redis(urlOrOptions?: string | RedisOptions): RedisStorage {\n // Handle string URL\n if (typeof urlOrOptions === 'string') {\n return createRedisStorage({ url: urlOrOptions });\n }\n\n return createRedisStorage(urlOrOptions ?? {});\n}\n\n/**\n * Internal factory to create Redis storage.\n */\nfunction createRedisStorage(options: RedisOptions): RedisStorage {\n let client: Redis | Cluster;\n let ownsClient = false;\n\n if (options.client) {\n // Use provided client\n client = options.client;\n } else {\n // Create new client\n const url = options.url ?? process.env[ENV_REDIS_URL];\n\n if (!url) {\n throw new Error(\n `Redis URL not provided. Either pass a URL, provide a client, or set ${ENV_REDIS_URL} environment variable.`\n );\n }\n\n client = new Redis(url);\n ownsClient = true;\n }\n\n return new RedisStorage({\n ...options,\n _client: client,\n _ownsClient: ownsClient,\n });\n}\n\n// Re-export types\nexport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["Redis"],"mappings":";;;;;;;;;AAcA,IAAM,aAAA,GAAgB,qBAAA;AAgDtB,IAAM,cAAA,GAAiB;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA8ChB,IAAM,eAAN,MAA6C;AAAA,EACjC,MAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,cAAA;AAAA,EAET,YAAY,OAAA,EAA4E;AACtF,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,OAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,YAAA;AACtC,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,WAAA;AAC1B,IAAA,IAAA,CAAK,cAAA,GAAiB,OAAA,CAAQ,cAAA,IAAkB,EAAA,GAAK,IAAA,GAAO,IAAA;AAAA,EAC9D;AAAA,EAEQ,UAAU,GAAA,EAAqB;AACrC,IAAA,OAAO,CAAA,EAAG,IAAA,CAAK,SAAS,CAAA,EAAG,GAAG,CAAA,CAAA;AAAA,EAChC;AAAA,EAEA,MAAM,OAAA,CAAQ,GAAA,EAAa,IAAA,EAAqB,GAAA,EAAqC;AACnF,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,SAAA,CAAU,GAAG,CAAA;AACtC,IAAA,MAAM,GAAA,GAAM,KAAK,GAAA,EAAI;AAGrB,IAAA,MAAM,MAAA,GAAU,MAAO,IAAA,CAAK,MAAA,CAAiB,IAAA;AAAA,MAC3C,cAAA;AAAA,MACA,CAAA;AAAA,MACA,W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,YAAA,EAAoD;AAExE,EAAA,IAAI,OAAO,iBAAiB,QAAA,EAAU;AACpC,IAAA,OAAO,kBAAA,CAAmB,EAAE,GAAA,EAAK,YAAA,EAAc,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,kBAAA,CAAmB,YAAA,IAAgB,EAAE,CAAA;AAC9C;AAKA,SAAS,mBAAmB,OAAA,EAAqC;AAC/D,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI,UAAA,GAAa,KAAA;AAEjB,EAAA,IAAI,QAAQ,MAAA,EAAQ;AAElB,IAAA,MAAA,GAAS,OAAA,CAAQ,MAAA;AAAA,EACnB,CAAA,MAAO;AAEL,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAO,OAAA,CAAQ,IAAI,aAAa,CAAA;AAEpD,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,uEAAuE,aAAa,CAAA,sBAAA;AAAA,OACtF;AAAA,IACF;AAEA,IAAA,MAAA,GAAS,IAAIA,uBAAM,GAAG,CAAA;AACtB,IAAA,UAAA,GAAa,IAAA;AAAA,EACf;AAEA,EAAA,OAAO,IAAI,YAAA,CAAa;AAAA,IACtB,GAAG,OAAA;AAAA,IACH,OAAA,EAAS,MAAA;AAAA,IACT,WAAA,EAAa;AAAA,GACd,CAAA;AACH","file":"index.cjs","sourcesContent":["/**\n * @idempotix/redis - Redis storage adapter for Idempotix\n *\n * Uses ioredis for standard Redis connections (TCP-based).\n * For HTTP-based Redis (Upstash, Vercel KV), use @idempotix/upstash.\n */\n\nimport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\nimport Redis, { type Cluster } from 'ioredis';\n\n/**\n * Environment variable for Redis URL.\n * Scoped to Idempotix to avoid accidental connections.\n */\nconst ENV_REDIS_URL = 'IDEMPOTIX_REDIS_URL';\n\n/**\n * Options for the Redis storage adapter.\n */\nexport interface RedisOptions {\n /**\n * Redis connection URL.\n * If not provided, uses IDEMPOTIX_REDIS_URL environment variable.\n */\n url?: string;\n\n /**\n * Existing ioredis client instance.\n * Takes precedence over url if provided.\n */\n client?: Redis | Cluster;\n\n /**\n * Key prefix for namespacing.\n * @default 'Idempotix:'\n */\n keyPrefix?: string;\n\n /**\n * Maximum payload size in bytes.\n * Responses exceeding this limit will skip caching.\n * Set to 0 to disable size checking.\n * @default 10485760 (10MB)\n */\n maxPayloadSize?: number;\n}\n\n/**\n * Internal record structure stored in Redis.\n */\ninterface RedisRecord {\n status: 'in_progress' | 'completed';\n hash: string | null;\n data?: unknown;\n createdAt: number;\n startedAt: number;\n}\n\n/**\n * Lua script for atomic acquire.\n * Returns: null if acquired, JSON string if exists\n */\nconst ACQUIRE_SCRIPT = `\nlocal key = KEYS[1]\nlocal hash = ARGV[1]\nlocal ttl = tonumber(ARGV[2])\nlocal now = tonumber(ARGV[3])\n\nlocal existing = redis.call('GET', key)\nif existing then\n return existing\nend\n\nlocal record = cjson.encode({\n status = 'in_progress',\n hash = hash ~= '' and hash or nil,\n startedAt = now\n})\nredis.call('SET', key, record, 'PX', ttl)\nreturn nil\n`;\n\n/**\n * Redis storage adapter using ioredis.\n *\n * Works with:\n * - Self-hosted Redis\n * - AWS ElastiCache\n * - Redis Cloud\n * - Azure Cache for Redis\n * - DigitalOcean Managed Redis\n * - Any Redis-compatible service via TCP\n *\n * @example\n * ```typescript\n * import { redis } from '@idempotix/redis';\n *\n * // From environment (IDEMPOTIX_REDIS_URL)\n * const storage = redis();\n *\n * // From URL\n * const storage = redis('redis://localhost:6379');\n *\n * // With existing client\n * import Redis from 'ioredis';\n * const storage = redis({ client: new Redis() });\n * ```\n */\nexport class RedisStorage implements StorageAdapter {\n private readonly client: Redis | Cluster;\n private readonly keyPrefix: string;\n private readonly ownsClient: boolean;\n\n /**\n * Maximum payload size in bytes (default: 10MB).\n * Prevents excessively large values from being stored in Redis.\n */\n readonly maxPayloadSize: number;\n\n constructor(options: RedisOptions & { _client: Redis | Cluster; _ownsClient: boolean }) {\n this.client = options._client;\n this.keyPrefix = options.keyPrefix ?? 'Idempotix:';\n this.ownsClient = options._ownsClient;\n this.maxPayloadSize = options.maxPayloadSize ?? 10 * 1024 * 1024;\n }\n\n private prefixKey(key: string): string {\n return `${this.keyPrefix}${key}`;\n }\n\n async acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult> {\n const prefixedKey = this.prefixKey(key);\n const now = Date.now();\n\n // Try to get existing or set new atomically\n const result = (await (this.client as Redis).eval(\n ACQUIRE_SCRIPT,\n 1,\n prefixedKey,\n hash ?? '',\n ttl.toString(),\n now.toString()\n )) as string | null;\n\n // Lock acquired\n if (result === null) {\n return { status: 'acquired' };\n }\n\n // Parse existing record\n let existing: RedisRecord;\n try {\n existing = JSON.parse(result);\n } catch {\n // Corrupted data, delete and try again\n await this.client.del(prefixedKey);\n return { status: 'acquired' };\n }\n\n // Check for hash mismatch\n if (hash && existing.hash && existing.hash !== hash) {\n return {\n status: 'mismatch',\n existingHash: existing.hash,\n providedHash: hash,\n };\n }\n\n // If completed, return cached response\n if (existing.status === 'completed') {\n return {\n status: 'hit',\n response: {\n data: existing.data,\n createdAt: existing.createdAt,\n hash: existing.hash,\n },\n };\n }\n\n // If in progress, return conflict\n return { status: 'conflict', startedAt: existing.startedAt };\n }\n\n async save(key: string, response: StoredResponse): Promise<void> {\n const prefixedKey = this.prefixKey(key);\n\n // Get existing record to preserve TTL\n const existing = await this.client.get(prefixedKey);\n if (!existing) return;\n\n const ttl = await this.client.pttl(prefixedKey);\n if (ttl <= 0) return;\n\n const record: RedisRecord = {\n status: 'completed',\n hash: response.hash,\n data: response.data,\n createdAt: response.createdAt,\n startedAt: Date.now(),\n };\n\n await this.client.set(prefixedKey, JSON.stringify(record), 'PX', ttl);\n }\n\n async release(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async delete(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async clear(): Promise<void> {\n const keys = await this.client.keys(`${this.keyPrefix}*`);\n if (keys.length > 0) {\n await this.client.del(...keys);\n }\n }\n\n /**\n * Disconnect the Redis client if we own it.\n * Call this during shutdown if using auto-created client.\n */\n async disconnect(): Promise<void> {\n if (this.ownsClient) {\n await this.client.quit();\n }\n }\n}\n\n/**\n * Create a Redis storage adapter.\n *\n * @example\n * ```typescript\n * import { idempotix } from '@idempotix/core';\n * import { redis } from '@idempotix/redis';\n *\n * // Auto-detect from IDEMPOTIX_REDIS_URL\n * idempotix.configure({ storage: redis() });\n *\n * // With explicit URL\n * idempotix.configure({ storage: redis('redis://localhost:6379') });\n *\n * // With options\n * idempotix.configure({\n * storage: redis({\n * url: 'redis://localhost:6379',\n * keyPrefix: 'myapp:',\n * }),\n * });\n *\n * // With existing client\n * import Redis from 'ioredis';\n * idempotix.configure({\n * storage: redis({ client: new Redis() }),\n * });\n * ```\n */\nexport function redis(urlOrOptions?: string | RedisOptions): RedisStorage {\n // Handle string URL\n if (typeof urlOrOptions === 'string') {\n return createRedisStorage({ url: urlOrOptions });\n }\n\n return createRedisStorage(urlOrOptions ?? {});\n}\n\n/**\n * Internal factory to create Redis storage.\n */\nfunction createRedisStorage(options: RedisOptions): RedisStorage {\n let client: Redis | Cluster;\n let ownsClient = false;\n\n if (options.client) {\n // Use provided client\n client = options.client;\n } else {\n // Create new client\n const url = options.url ?? process.env[ENV_REDIS_URL];\n\n if (!url) {\n throw new Error(\n `Redis URL not provided. Either pass a URL, provide a client, or set ${ENV_REDIS_URL} environment variable.`\n );\n }\n\n client = new Redis(url);\n ownsClient = true;\n }\n\n return new RedisStorage({\n ...options,\n _client: client,\n _ownsClient: ownsClient,\n });\n}\n\n// Re-export types\nexport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -15,7 +15,7 @@ import Redis, { Cluster } from 'ioredis';
|
|
|
15
15
|
interface RedisOptions {
|
|
16
16
|
/**
|
|
17
17
|
* Redis connection URL.
|
|
18
|
-
* If not provided, uses
|
|
18
|
+
* If not provided, uses IDEMPOTIX_REDIS_URL environment variable.
|
|
19
19
|
*/
|
|
20
20
|
url?: string;
|
|
21
21
|
/**
|
|
@@ -51,7 +51,7 @@ interface RedisOptions {
|
|
|
51
51
|
* ```typescript
|
|
52
52
|
* import { redis } from '@idempotix/redis';
|
|
53
53
|
*
|
|
54
|
-
* // From environment (
|
|
54
|
+
* // From environment (IDEMPOTIX_REDIS_URL)
|
|
55
55
|
* const storage = redis();
|
|
56
56
|
*
|
|
57
57
|
* // From URL
|
|
@@ -95,7 +95,7 @@ declare class RedisStorage implements StorageAdapter {
|
|
|
95
95
|
* import { idempotix } from '@idempotix/core';
|
|
96
96
|
* import { redis } from '@idempotix/redis';
|
|
97
97
|
*
|
|
98
|
-
* // Auto-detect from
|
|
98
|
+
* // Auto-detect from IDEMPOTIX_REDIS_URL
|
|
99
99
|
* idempotix.configure({ storage: redis() });
|
|
100
100
|
*
|
|
101
101
|
* // With explicit URL
|
package/dist/index.d.ts
CHANGED
|
@@ -15,7 +15,7 @@ import Redis, { Cluster } from 'ioredis';
|
|
|
15
15
|
interface RedisOptions {
|
|
16
16
|
/**
|
|
17
17
|
* Redis connection URL.
|
|
18
|
-
* If not provided, uses
|
|
18
|
+
* If not provided, uses IDEMPOTIX_REDIS_URL environment variable.
|
|
19
19
|
*/
|
|
20
20
|
url?: string;
|
|
21
21
|
/**
|
|
@@ -51,7 +51,7 @@ interface RedisOptions {
|
|
|
51
51
|
* ```typescript
|
|
52
52
|
* import { redis } from '@idempotix/redis';
|
|
53
53
|
*
|
|
54
|
-
* // From environment (
|
|
54
|
+
* // From environment (IDEMPOTIX_REDIS_URL)
|
|
55
55
|
* const storage = redis();
|
|
56
56
|
*
|
|
57
57
|
* // From URL
|
|
@@ -95,7 +95,7 @@ declare class RedisStorage implements StorageAdapter {
|
|
|
95
95
|
* import { idempotix } from '@idempotix/core';
|
|
96
96
|
* import { redis } from '@idempotix/redis';
|
|
97
97
|
*
|
|
98
|
-
* // Auto-detect from
|
|
98
|
+
* // Auto-detect from IDEMPOTIX_REDIS_URL
|
|
99
99
|
* idempotix.configure({ storage: redis() });
|
|
100
100
|
*
|
|
101
101
|
* // With explicit URL
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAcA,IAAM,aAAA,GAAgB,qBAAA;AAgDtB,IAAM,cAAA,GAAiB;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA8ChB,IAAM,eAAN,MAA6C;AAAA,EACjC,MAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,cAAA;AAAA,EAET,YAAY,OAAA,EAA4E;AACtF,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,OAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,YAAA;AACtC,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,WAAA;AAC1B,IAAA,IAAA,CAAK,cAAA,GAAiB,OAAA,CAAQ,cAAA,IAAkB,EAAA,GAAK,IAAA,GAAO,IAAA;AAAA,EAC9D;AAAA,EAEQ,UAAU,GAAA,EAAqB;AACrC,IAAA,OAAO,CAAA,EAAG,IAAA,CAAK,SAAS,CAAA,EAAG,GAAG,CAAA,CAAA;AAAA,EAChC;AAAA,EAEA,MAAM,OAAA,CAAQ,GAAA,EAAa,IAAA,EAAqB,GAAA,EAAqC;AACnF,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,SAAA,CAAU,GAAG,CAAA;AACtC,IAAA,MAAM,GAAA,GAAM,KAAK,GAAA,EAAI;AAGrB,IAAA,MAAM,MAAA,GAAU,MAAO,IAAA,CAAK,MAAA,CAAiB,IAAA;AAAA,MAC3C,cAAA;AAAA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;AACF;AA+BO,SAAS,MAAM,YAAA,EAAoD;AAExE,EAAA,IAAI,OAAO,iBAAiB,QAAA,EAAU;AACpC,IAAA,OAAO,kBAAA,CAAmB,EAAE,GAAA,EAAK,YAAA,EAAc,CAAA;AAAA,EACjD;AAEA,EAAA,OAAO,kBAAA,CAAmB,YAAA,IAAgB,EAAE,CAAA;AAC9C;AAKA,SAAS,mBAAmB,OAAA,EAAqC;AAC/D,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI,UAAA,GAAa,KAAA;AAEjB,EAAA,IAAI,QAAQ,MAAA,EAAQ;AAElB,IAAA,MAAA,GAAS,OAAA,CAAQ,MAAA;AAAA,EACnB,CAAA,MAAO;AAEL,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAO,OAAA,CAAQ,IAAI,aAAa,CAAA;AAEpD,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,uEAAuE,aAAa,CAAA,sBAAA;AAAA,OACtF;AAAA,IACF;AAEA,IAAA,MAAA,GAAS,IAAI,MAAM,GAAG,CAAA;AACtB,IAAA,UAAA,GAAa,IAAA;AAAA,EACf;AAEA,EAAA,OAAO,IAAI,YAAA,CAAa;AAAA,IACtB,GAAG,OAAA;AAAA,IACH,OAAA,EAAS,MAAA;AAAA,IACT,WAAA,EAAa;AAAA,GACd,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * @idempotix/redis - Redis storage adapter for Idempotix\n *\n * Uses ioredis for standard Redis connections (TCP-based).\n * For HTTP-based Redis (Upstash, Vercel KV), use @idempotix/upstash.\n */\n\nimport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\nimport Redis, { type Cluster } from 'ioredis';\n\n/**\n * Environment variable for Redis URL.\n * Scoped to Idempotix to avoid accidental connections.\n */\nconst ENV_REDIS_URL = 'Idempotix_REDIS_URL';\n\n/**\n * Options for the Redis storage adapter.\n */\nexport interface RedisOptions {\n /**\n * Redis connection URL.\n * If not provided, uses Idempotix_REDIS_URL environment variable.\n */\n url?: string;\n\n /**\n * Existing ioredis client instance.\n * Takes precedence over url if provided.\n */\n client?: Redis | Cluster;\n\n /**\n * Key prefix for namespacing.\n * @default 'Idempotix:'\n */\n keyPrefix?: string;\n\n /**\n * Maximum payload size in bytes.\n * Responses exceeding this limit will skip caching.\n * Set to 0 to disable size checking.\n * @default 10485760 (10MB)\n */\n maxPayloadSize?: number;\n}\n\n/**\n * Internal record structure stored in Redis.\n */\ninterface RedisRecord {\n status: 'in_progress' | 'completed';\n hash: string | null;\n data?: unknown;\n createdAt: number;\n startedAt: number;\n}\n\n/**\n * Lua script for atomic acquire.\n * Returns: null if acquired, JSON string if exists\n */\nconst ACQUIRE_SCRIPT = `\nlocal key = KEYS[1]\nlocal hash = ARGV[1]\nlocal ttl = tonumber(ARGV[2])\nlocal now = tonumber(ARGV[3])\n\nlocal existing = redis.call('GET', key)\nif existing then\n return existing\nend\n\nlocal record = cjson.encode({\n status = 'in_progress',\n hash = hash ~= '' and hash or nil,\n startedAt = now\n})\nredis.call('SET', key, record, 'PX', ttl)\nreturn nil\n`;\n\n/**\n * Redis storage adapter using ioredis.\n *\n * Works with:\n * - Self-hosted Redis\n * - AWS ElastiCache\n * - Redis Cloud\n * - Azure Cache for Redis\n * - DigitalOcean Managed Redis\n * - Any Redis-compatible service via TCP\n *\n * @example\n * ```typescript\n * import { redis } from '@idempotix/redis';\n *\n * // From environment (Idempotix_REDIS_URL)\n * const storage = redis();\n *\n * // From URL\n * const storage = redis('redis://localhost:6379');\n *\n * // With existing client\n * import Redis from 'ioredis';\n * const storage = redis({ client: new Redis() });\n * ```\n */\nexport class RedisStorage implements StorageAdapter {\n private readonly client: Redis | Cluster;\n private readonly keyPrefix: string;\n private readonly ownsClient: boolean;\n\n /**\n * Maximum payload size in bytes (default: 10MB).\n * Prevents excessively large values from being stored in Redis.\n */\n readonly maxPayloadSize: number;\n\n constructor(options: RedisOptions & { _client: Redis | Cluster; _ownsClient: boolean }) {\n this.client = options._client;\n this.keyPrefix = options.keyPrefix ?? 'Idempotix:';\n this.ownsClient = options._ownsClient;\n this.maxPayloadSize = options.maxPayloadSize ?? 10 * 1024 * 1024;\n }\n\n private prefixKey(key: string): string {\n return `${this.keyPrefix}${key}`;\n }\n\n async acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult> {\n const prefixedKey = this.prefixKey(key);\n const now = Date.now();\n\n // Try to get existing or set new atomically\n const result = (await (this.client as Redis).eval(\n ACQUIRE_SCRIPT,\n 1,\n prefixedKey,\n hash ?? '',\n ttl.toString(),\n now.toString()\n )) as string | null;\n\n // Lock acquired\n if (result === null) {\n return { status: 'acquired' };\n }\n\n // Parse existing record\n let existing: RedisRecord;\n try {\n existing = JSON.parse(result);\n } catch {\n // Corrupted data, delete and try again\n await this.client.del(prefixedKey);\n return { status: 'acquired' };\n }\n\n // Check for hash mismatch\n if (hash && existing.hash && existing.hash !== hash) {\n return {\n status: 'mismatch',\n existingHash: existing.hash,\n providedHash: hash,\n };\n }\n\n // If completed, return cached response\n if (existing.status === 'completed') {\n return {\n status: 'hit',\n response: {\n data: existing.data,\n createdAt: existing.createdAt,\n hash: existing.hash,\n },\n };\n }\n\n // If in progress, return conflict\n return { status: 'conflict', startedAt: existing.startedAt };\n }\n\n async save(key: string, response: StoredResponse): Promise<void> {\n const prefixedKey = this.prefixKey(key);\n\n // Get existing record to preserve TTL\n const existing = await this.client.get(prefixedKey);\n if (!existing) return;\n\n const ttl = await this.client.pttl(prefixedKey);\n if (ttl <= 0) return;\n\n const record: RedisRecord = {\n status: 'completed',\n hash: response.hash,\n data: response.data,\n createdAt: response.createdAt,\n startedAt: Date.now(),\n };\n\n await this.client.set(prefixedKey, JSON.stringify(record), 'PX', ttl);\n }\n\n async release(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async delete(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async clear(): Promise<void> {\n const keys = await this.client.keys(`${this.keyPrefix}*`);\n if (keys.length > 0) {\n await this.client.del(...keys);\n }\n }\n\n /**\n * Disconnect the Redis client if we own it.\n * Call this during shutdown if using auto-created client.\n */\n async disconnect(): Promise<void> {\n if (this.ownsClient) {\n await this.client.quit();\n }\n }\n}\n\n/**\n * Create a Redis storage adapter.\n *\n * @example\n * ```typescript\n * import { idempotix } from '@idempotix/core';\n * import { redis } from '@idempotix/redis';\n *\n * // Auto-detect from Idempotix_REDIS_URL\n * idempotix.configure({ storage: redis() });\n *\n * // With explicit URL\n * idempotix.configure({ storage: redis('redis://localhost:6379') });\n *\n * // With options\n * idempotix.configure({\n * storage: redis({\n * url: 'redis://localhost:6379',\n * keyPrefix: 'myapp:',\n * }),\n * });\n *\n * // With existing client\n * import Redis from 'ioredis';\n * idempotix.configure({\n * storage: redis({ client: new Redis() }),\n * });\n * ```\n */\nexport function redis(urlOrOptions?: string | RedisOptions): RedisStorage {\n // Handle string URL\n if (typeof urlOrOptions === 'string') {\n return createRedisStorage({ url: urlOrOptions });\n }\n\n return createRedisStorage(urlOrOptions ?? {});\n}\n\n/**\n * Internal factory to create Redis storage.\n */\nfunction createRedisStorage(options: RedisOptions): RedisStorage {\n let client: Redis | Cluster;\n let ownsClient = false;\n\n if (options.client) {\n // Use provided client\n client = options.client;\n } else {\n // Create new client\n const url = options.url ?? process.env[ENV_REDIS_URL];\n\n if (!url) {\n throw new Error(\n `Redis URL not provided. Either pass a URL, provide a client, or set ${ENV_REDIS_URL} environment variable.`\n );\n }\n\n client = new Redis(url);\n ownsClient = true;\n }\n\n return new RedisStorage({\n ...options,\n _client: client,\n _ownsClient: ownsClient,\n });\n}\n\n// Re-export types\nexport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAcA,IAAM,aAAA,GAAgB,qBAAA;AAgDtB,IAAM,cAAA,GAAiB;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA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AAQ,MAAA,EAAQ;AAElB,IAAA,MAAA,GAAS,OAAA,CAAQ,MAAA;AAAA,EACnB,CAAA,MAAO;AAEL,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAO,OAAA,CAAQ,IAAI,aAAa,CAAA;AAEpD,IAAA,IAAI,CAAC,GAAA,EAAK;AACR,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,uEAAuE,aAAa,CAAA,sBAAA;AAAA,OACtF;AAAA,IACF;AAEA,IAAA,MAAA,GAAS,IAAI,MAAM,GAAG,CAAA;AACtB,IAAA,UAAA,GAAa,IAAA;AAAA,EACf;AAEA,EAAA,OAAO,IAAI,YAAA,CAAa;AAAA,IACtB,GAAG,OAAA;AAAA,IACH,OAAA,EAAS,MAAA;AAAA,IACT,WAAA,EAAa;AAAA,GACd,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * @idempotix/redis - Redis storage adapter for Idempotix\n *\n * Uses ioredis for standard Redis connections (TCP-based).\n * For HTTP-based Redis (Upstash, Vercel KV), use @idempotix/upstash.\n */\n\nimport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\nimport Redis, { type Cluster } from 'ioredis';\n\n/**\n * Environment variable for Redis URL.\n * Scoped to Idempotix to avoid accidental connections.\n */\nconst ENV_REDIS_URL = 'IDEMPOTIX_REDIS_URL';\n\n/**\n * Options for the Redis storage adapter.\n */\nexport interface RedisOptions {\n /**\n * Redis connection URL.\n * If not provided, uses IDEMPOTIX_REDIS_URL environment variable.\n */\n url?: string;\n\n /**\n * Existing ioredis client instance.\n * Takes precedence over url if provided.\n */\n client?: Redis | Cluster;\n\n /**\n * Key prefix for namespacing.\n * @default 'Idempotix:'\n */\n keyPrefix?: string;\n\n /**\n * Maximum payload size in bytes.\n * Responses exceeding this limit will skip caching.\n * Set to 0 to disable size checking.\n * @default 10485760 (10MB)\n */\n maxPayloadSize?: number;\n}\n\n/**\n * Internal record structure stored in Redis.\n */\ninterface RedisRecord {\n status: 'in_progress' | 'completed';\n hash: string | null;\n data?: unknown;\n createdAt: number;\n startedAt: number;\n}\n\n/**\n * Lua script for atomic acquire.\n * Returns: null if acquired, JSON string if exists\n */\nconst ACQUIRE_SCRIPT = `\nlocal key = KEYS[1]\nlocal hash = ARGV[1]\nlocal ttl = tonumber(ARGV[2])\nlocal now = tonumber(ARGV[3])\n\nlocal existing = redis.call('GET', key)\nif existing then\n return existing\nend\n\nlocal record = cjson.encode({\n status = 'in_progress',\n hash = hash ~= '' and hash or nil,\n startedAt = now\n})\nredis.call('SET', key, record, 'PX', ttl)\nreturn nil\n`;\n\n/**\n * Redis storage adapter using ioredis.\n *\n * Works with:\n * - Self-hosted Redis\n * - AWS ElastiCache\n * - Redis Cloud\n * - Azure Cache for Redis\n * - DigitalOcean Managed Redis\n * - Any Redis-compatible service via TCP\n *\n * @example\n * ```typescript\n * import { redis } from '@idempotix/redis';\n *\n * // From environment (IDEMPOTIX_REDIS_URL)\n * const storage = redis();\n *\n * // From URL\n * const storage = redis('redis://localhost:6379');\n *\n * // With existing client\n * import Redis from 'ioredis';\n * const storage = redis({ client: new Redis() });\n * ```\n */\nexport class RedisStorage implements StorageAdapter {\n private readonly client: Redis | Cluster;\n private readonly keyPrefix: string;\n private readonly ownsClient: boolean;\n\n /**\n * Maximum payload size in bytes (default: 10MB).\n * Prevents excessively large values from being stored in Redis.\n */\n readonly maxPayloadSize: number;\n\n constructor(options: RedisOptions & { _client: Redis | Cluster; _ownsClient: boolean }) {\n this.client = options._client;\n this.keyPrefix = options.keyPrefix ?? 'Idempotix:';\n this.ownsClient = options._ownsClient;\n this.maxPayloadSize = options.maxPayloadSize ?? 10 * 1024 * 1024;\n }\n\n private prefixKey(key: string): string {\n return `${this.keyPrefix}${key}`;\n }\n\n async acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult> {\n const prefixedKey = this.prefixKey(key);\n const now = Date.now();\n\n // Try to get existing or set new atomically\n const result = (await (this.client as Redis).eval(\n ACQUIRE_SCRIPT,\n 1,\n prefixedKey,\n hash ?? '',\n ttl.toString(),\n now.toString()\n )) as string | null;\n\n // Lock acquired\n if (result === null) {\n return { status: 'acquired' };\n }\n\n // Parse existing record\n let existing: RedisRecord;\n try {\n existing = JSON.parse(result);\n } catch {\n // Corrupted data, delete and try again\n await this.client.del(prefixedKey);\n return { status: 'acquired' };\n }\n\n // Check for hash mismatch\n if (hash && existing.hash && existing.hash !== hash) {\n return {\n status: 'mismatch',\n existingHash: existing.hash,\n providedHash: hash,\n };\n }\n\n // If completed, return cached response\n if (existing.status === 'completed') {\n return {\n status: 'hit',\n response: {\n data: existing.data,\n createdAt: existing.createdAt,\n hash: existing.hash,\n },\n };\n }\n\n // If in progress, return conflict\n return { status: 'conflict', startedAt: existing.startedAt };\n }\n\n async save(key: string, response: StoredResponse): Promise<void> {\n const prefixedKey = this.prefixKey(key);\n\n // Get existing record to preserve TTL\n const existing = await this.client.get(prefixedKey);\n if (!existing) return;\n\n const ttl = await this.client.pttl(prefixedKey);\n if (ttl <= 0) return;\n\n const record: RedisRecord = {\n status: 'completed',\n hash: response.hash,\n data: response.data,\n createdAt: response.createdAt,\n startedAt: Date.now(),\n };\n\n await this.client.set(prefixedKey, JSON.stringify(record), 'PX', ttl);\n }\n\n async release(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async delete(key: string): Promise<void> {\n await this.client.del(this.prefixKey(key));\n }\n\n async clear(): Promise<void> {\n const keys = await this.client.keys(`${this.keyPrefix}*`);\n if (keys.length > 0) {\n await this.client.del(...keys);\n }\n }\n\n /**\n * Disconnect the Redis client if we own it.\n * Call this during shutdown if using auto-created client.\n */\n async disconnect(): Promise<void> {\n if (this.ownsClient) {\n await this.client.quit();\n }\n }\n}\n\n/**\n * Create a Redis storage adapter.\n *\n * @example\n * ```typescript\n * import { idempotix } from '@idempotix/core';\n * import { redis } from '@idempotix/redis';\n *\n * // Auto-detect from IDEMPOTIX_REDIS_URL\n * idempotix.configure({ storage: redis() });\n *\n * // With explicit URL\n * idempotix.configure({ storage: redis('redis://localhost:6379') });\n *\n * // With options\n * idempotix.configure({\n * storage: redis({\n * url: 'redis://localhost:6379',\n * keyPrefix: 'myapp:',\n * }),\n * });\n *\n * // With existing client\n * import Redis from 'ioredis';\n * idempotix.configure({\n * storage: redis({ client: new Redis() }),\n * });\n * ```\n */\nexport function redis(urlOrOptions?: string | RedisOptions): RedisStorage {\n // Handle string URL\n if (typeof urlOrOptions === 'string') {\n return createRedisStorage({ url: urlOrOptions });\n }\n\n return createRedisStorage(urlOrOptions ?? {});\n}\n\n/**\n * Internal factory to create Redis storage.\n */\nfunction createRedisStorage(options: RedisOptions): RedisStorage {\n let client: Redis | Cluster;\n let ownsClient = false;\n\n if (options.client) {\n // Use provided client\n client = options.client;\n } else {\n // Create new client\n const url = options.url ?? process.env[ENV_REDIS_URL];\n\n if (!url) {\n throw new Error(\n `Redis URL not provided. Either pass a URL, provide a client, or set ${ENV_REDIS_URL} environment variable.`\n );\n }\n\n client = new Redis(url);\n ownsClient = true;\n }\n\n return new RedisStorage({\n ...options,\n _client: client,\n _ownsClient: ownsClient,\n });\n}\n\n// Re-export types\nexport type { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';\n"]}
|