@idempotix/redis 1.0.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.
package/LICENSE ADDED
@@ -0,0 +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.
package/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # @idempotix/redis
2
+
3
+ Redis storage adapter for Idempotix using ioredis.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@idempotix/redis.svg)](https://www.npmjs.com/package/@idempotix/redis)
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @idempotix/core @idempotix/redis ioredis
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import { redis } from '@idempotix/redis';
17
+ import { express as idempotent } from '@idempotix/express';
18
+
19
+ // From environment variable (Idempotix_REDIS_URL)
20
+ app.post('/orders', idempotent({ storage: redis() }), handler);
21
+ ```
22
+
23
+ ## Configuration
24
+
25
+ ```typescript
26
+ import { redis } from '@idempotix/redis';
27
+
28
+ // From environment variable
29
+ const storage = redis();
30
+
31
+ // From URL (password in URL)
32
+ const storage = redis('redis://:password@localhost:6379');
33
+
34
+ // With options
35
+ const storage = redis({
36
+ url: 'redis://localhost:6379',
37
+ keyPrefix: 'myapp:idem:',
38
+ });
39
+
40
+ // With existing ioredis client
41
+ import Redis from 'ioredis';
42
+ const client = new Redis({ host: 'localhost', password: 'secret' });
43
+ const storage = redis({ client });
44
+ ```
45
+
46
+ ## Environment Variables
47
+
48
+ | Variable | Description |
49
+ | --------------------- | ---------------------------------------------------------- |
50
+ | `Idempotix_REDIS_URL` | Redis connection URL (e.g., `redis://:password@host:6379`) |
51
+
52
+ ## Redis Cluster
53
+
54
+ ```typescript
55
+ import Redis from 'ioredis';
56
+ import { redis } from '@idempotix/redis';
57
+
58
+ const cluster = new Redis.Cluster([
59
+ { host: 'node1.example.com', port: 6379 },
60
+ { host: 'node2.example.com', port: 6379 },
61
+ ]);
62
+
63
+ const storage = redis({ client: cluster });
64
+ ```
65
+
66
+ ## AWS ElastiCache
67
+
68
+ ```typescript
69
+ const storage = redis('redis://your-cluster.cache.amazonaws.com:6379');
70
+ ```
71
+
72
+ ## Usage with Express
73
+
74
+ ```typescript
75
+ import { express as idempotent, configure } from '@idempotix/express';
76
+ import { redis } from '@idempotix/redis';
77
+
78
+ const idempotent = configure({
79
+ storage: redis(),
80
+ ttl: '1h',
81
+ });
82
+
83
+ app.post('/orders', idempotent(), orderHandler);
84
+ app.post('/payments', idempotent({ required: true }), paymentHandler);
85
+ ```
86
+
87
+ ## Usage with Next.js
88
+
89
+ ```typescript
90
+ import { next } from '@idempotix/next';
91
+ import { redis } from '@idempotix/redis';
92
+
93
+ export const POST = next({ storage: redis() })(handler);
94
+ ```
95
+
96
+ ## Key Prefix
97
+
98
+ All keys are prefixed with `Idempotix:` by default. Customize with:
99
+
100
+ ```typescript
101
+ const storage = redis({ keyPrefix: 'myapp:idem:' });
102
+ ```
103
+
104
+ ## License
105
+
106
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,156 @@
1
+ 'use strict';
2
+
3
+ var Redis = require('ioredis');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var Redis__default = /*#__PURE__*/_interopDefault(Redis);
8
+
9
+ // src/index.ts
10
+ var ENV_REDIS_URL = "Idempotix_REDIS_URL";
11
+ var ACQUIRE_SCRIPT = `
12
+ local key = KEYS[1]
13
+ local hash = ARGV[1]
14
+ local ttl = tonumber(ARGV[2])
15
+ local now = tonumber(ARGV[3])
16
+
17
+ local existing = redis.call('GET', key)
18
+ if existing then
19
+ return existing
20
+ end
21
+
22
+ local record = cjson.encode({
23
+ status = 'in_progress',
24
+ hash = hash ~= '' and hash or nil,
25
+ startedAt = now
26
+ })
27
+ redis.call('SET', key, record, 'PX', ttl)
28
+ return nil
29
+ `;
30
+ var RedisStorage = class {
31
+ client;
32
+ keyPrefix;
33
+ ownsClient;
34
+ /**
35
+ * Maximum payload size in bytes (default: 10MB).
36
+ * Prevents excessively large values from being stored in Redis.
37
+ */
38
+ maxPayloadSize;
39
+ constructor(options) {
40
+ this.client = options._client;
41
+ this.keyPrefix = options.keyPrefix ?? "Idempotix:";
42
+ this.ownsClient = options._ownsClient;
43
+ this.maxPayloadSize = options.maxPayloadSize ?? 10 * 1024 * 1024;
44
+ }
45
+ prefixKey(key) {
46
+ return `${this.keyPrefix}${key}`;
47
+ }
48
+ async acquire(key, hash, ttl) {
49
+ const prefixedKey = this.prefixKey(key);
50
+ const now = Date.now();
51
+ const result = await this.client.eval(
52
+ ACQUIRE_SCRIPT,
53
+ 1,
54
+ prefixedKey,
55
+ hash ?? "",
56
+ ttl.toString(),
57
+ now.toString()
58
+ );
59
+ if (result === null) {
60
+ return { status: "acquired" };
61
+ }
62
+ let existing;
63
+ try {
64
+ existing = JSON.parse(result);
65
+ } catch {
66
+ await this.client.del(prefixedKey);
67
+ return { status: "acquired" };
68
+ }
69
+ if (hash && existing.hash && existing.hash !== hash) {
70
+ return {
71
+ status: "mismatch",
72
+ existingHash: existing.hash,
73
+ providedHash: hash
74
+ };
75
+ }
76
+ if (existing.status === "completed") {
77
+ return {
78
+ status: "hit",
79
+ response: {
80
+ data: existing.data,
81
+ createdAt: existing.createdAt,
82
+ hash: existing.hash
83
+ }
84
+ };
85
+ }
86
+ return { status: "conflict", startedAt: existing.startedAt };
87
+ }
88
+ async save(key, response) {
89
+ const prefixedKey = this.prefixKey(key);
90
+ const existing = await this.client.get(prefixedKey);
91
+ if (!existing) return;
92
+ const ttl = await this.client.pttl(prefixedKey);
93
+ if (ttl <= 0) return;
94
+ const record = {
95
+ status: "completed",
96
+ hash: response.hash,
97
+ data: response.data,
98
+ createdAt: response.createdAt,
99
+ startedAt: Date.now()
100
+ };
101
+ await this.client.set(prefixedKey, JSON.stringify(record), "PX", ttl);
102
+ }
103
+ async release(key) {
104
+ await this.client.del(this.prefixKey(key));
105
+ }
106
+ async delete(key) {
107
+ await this.client.del(this.prefixKey(key));
108
+ }
109
+ async clear() {
110
+ const keys = await this.client.keys(`${this.keyPrefix}*`);
111
+ if (keys.length > 0) {
112
+ await this.client.del(...keys);
113
+ }
114
+ }
115
+ /**
116
+ * Disconnect the Redis client if we own it.
117
+ * Call this during shutdown if using auto-created client.
118
+ */
119
+ async disconnect() {
120
+ if (this.ownsClient) {
121
+ await this.client.quit();
122
+ }
123
+ }
124
+ };
125
+ function redis(urlOrOptions) {
126
+ if (typeof urlOrOptions === "string") {
127
+ return createRedisStorage({ url: urlOrOptions });
128
+ }
129
+ return createRedisStorage(urlOrOptions ?? {});
130
+ }
131
+ function createRedisStorage(options) {
132
+ let client;
133
+ let ownsClient = false;
134
+ if (options.client) {
135
+ client = options.client;
136
+ } else {
137
+ const url = options.url ?? process.env[ENV_REDIS_URL];
138
+ if (!url) {
139
+ throw new Error(
140
+ `Redis URL not provided. Either pass a URL, provide a client, or set ${ENV_REDIS_URL} environment variable.`
141
+ );
142
+ }
143
+ client = new Redis__default.default(url);
144
+ ownsClient = true;
145
+ }
146
+ return new RedisStorage({
147
+ ...options,
148
+ _client: client,
149
+ _ownsClient: ownsClient
150
+ });
151
+ }
152
+
153
+ exports.RedisStorage = RedisStorage;
154
+ exports.redis = redis;
155
+ //# sourceMappingURL=index.cjs.map
156
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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,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,GA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C,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,MAAM,IAAA,CAAK,OAAO,IAAA,EAAK;AAAA,IACzB;AAAA,EACF;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,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"]}
@@ -0,0 +1,121 @@
1
+ import { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';
2
+ export { AcquireResult, StorageAdapter, StoredResponse } from '@idempotix/core';
3
+ import Redis, { Cluster } from 'ioredis';
4
+
5
+ /**
6
+ * @idempotix/redis - Redis storage adapter for Idempotix
7
+ *
8
+ * Uses ioredis for standard Redis connections (TCP-based).
9
+ * For HTTP-based Redis (Upstash, Vercel KV), use @idempotix/upstash.
10
+ */
11
+
12
+ /**
13
+ * Options for the Redis storage adapter.
14
+ */
15
+ interface RedisOptions {
16
+ /**
17
+ * Redis connection URL.
18
+ * If not provided, uses Idempotix_REDIS_URL environment variable.
19
+ */
20
+ url?: string;
21
+ /**
22
+ * Existing ioredis client instance.
23
+ * Takes precedence over url if provided.
24
+ */
25
+ client?: Redis | Cluster;
26
+ /**
27
+ * Key prefix for namespacing.
28
+ * @default 'Idempotix:'
29
+ */
30
+ keyPrefix?: string;
31
+ /**
32
+ * Maximum payload size in bytes.
33
+ * Responses exceeding this limit will skip caching.
34
+ * Set to 0 to disable size checking.
35
+ * @default 10485760 (10MB)
36
+ */
37
+ maxPayloadSize?: number;
38
+ }
39
+ /**
40
+ * Redis storage adapter using ioredis.
41
+ *
42
+ * Works with:
43
+ * - Self-hosted Redis
44
+ * - AWS ElastiCache
45
+ * - Redis Cloud
46
+ * - Azure Cache for Redis
47
+ * - DigitalOcean Managed Redis
48
+ * - Any Redis-compatible service via TCP
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * import { redis } from '@idempotix/redis';
53
+ *
54
+ * // From environment (Idempotix_REDIS_URL)
55
+ * const storage = redis();
56
+ *
57
+ * // From URL
58
+ * const storage = redis('redis://localhost:6379');
59
+ *
60
+ * // With existing client
61
+ * import Redis from 'ioredis';
62
+ * const storage = redis({ client: new Redis() });
63
+ * ```
64
+ */
65
+ declare class RedisStorage implements StorageAdapter {
66
+ private readonly client;
67
+ private readonly keyPrefix;
68
+ private readonly ownsClient;
69
+ /**
70
+ * Maximum payload size in bytes (default: 10MB).
71
+ * Prevents excessively large values from being stored in Redis.
72
+ */
73
+ readonly maxPayloadSize: number;
74
+ constructor(options: RedisOptions & {
75
+ _client: Redis | Cluster;
76
+ _ownsClient: boolean;
77
+ });
78
+ private prefixKey;
79
+ acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult>;
80
+ save(key: string, response: StoredResponse): Promise<void>;
81
+ release(key: string): Promise<void>;
82
+ delete(key: string): Promise<void>;
83
+ clear(): Promise<void>;
84
+ /**
85
+ * Disconnect the Redis client if we own it.
86
+ * Call this during shutdown if using auto-created client.
87
+ */
88
+ disconnect(): Promise<void>;
89
+ }
90
+ /**
91
+ * Create a Redis storage adapter.
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * import { idempotix } from '@idempotix/core';
96
+ * import { redis } from '@idempotix/redis';
97
+ *
98
+ * // Auto-detect from Idempotix_REDIS_URL
99
+ * idempotix.configure({ storage: redis() });
100
+ *
101
+ * // With explicit URL
102
+ * idempotix.configure({ storage: redis('redis://localhost:6379') });
103
+ *
104
+ * // With options
105
+ * idempotix.configure({
106
+ * storage: redis({
107
+ * url: 'redis://localhost:6379',
108
+ * keyPrefix: 'myapp:',
109
+ * }),
110
+ * });
111
+ *
112
+ * // With existing client
113
+ * import Redis from 'ioredis';
114
+ * idempotix.configure({
115
+ * storage: redis({ client: new Redis() }),
116
+ * });
117
+ * ```
118
+ */
119
+ declare function redis(urlOrOptions?: string | RedisOptions): RedisStorage;
120
+
121
+ export { type RedisOptions, RedisStorage, redis };
@@ -0,0 +1,121 @@
1
+ import { StorageAdapter, AcquireResult, StoredResponse } from '@idempotix/core';
2
+ export { AcquireResult, StorageAdapter, StoredResponse } from '@idempotix/core';
3
+ import Redis, { Cluster } from 'ioredis';
4
+
5
+ /**
6
+ * @idempotix/redis - Redis storage adapter for Idempotix
7
+ *
8
+ * Uses ioredis for standard Redis connections (TCP-based).
9
+ * For HTTP-based Redis (Upstash, Vercel KV), use @idempotix/upstash.
10
+ */
11
+
12
+ /**
13
+ * Options for the Redis storage adapter.
14
+ */
15
+ interface RedisOptions {
16
+ /**
17
+ * Redis connection URL.
18
+ * If not provided, uses Idempotix_REDIS_URL environment variable.
19
+ */
20
+ url?: string;
21
+ /**
22
+ * Existing ioredis client instance.
23
+ * Takes precedence over url if provided.
24
+ */
25
+ client?: Redis | Cluster;
26
+ /**
27
+ * Key prefix for namespacing.
28
+ * @default 'Idempotix:'
29
+ */
30
+ keyPrefix?: string;
31
+ /**
32
+ * Maximum payload size in bytes.
33
+ * Responses exceeding this limit will skip caching.
34
+ * Set to 0 to disable size checking.
35
+ * @default 10485760 (10MB)
36
+ */
37
+ maxPayloadSize?: number;
38
+ }
39
+ /**
40
+ * Redis storage adapter using ioredis.
41
+ *
42
+ * Works with:
43
+ * - Self-hosted Redis
44
+ * - AWS ElastiCache
45
+ * - Redis Cloud
46
+ * - Azure Cache for Redis
47
+ * - DigitalOcean Managed Redis
48
+ * - Any Redis-compatible service via TCP
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * import { redis } from '@idempotix/redis';
53
+ *
54
+ * // From environment (Idempotix_REDIS_URL)
55
+ * const storage = redis();
56
+ *
57
+ * // From URL
58
+ * const storage = redis('redis://localhost:6379');
59
+ *
60
+ * // With existing client
61
+ * import Redis from 'ioredis';
62
+ * const storage = redis({ client: new Redis() });
63
+ * ```
64
+ */
65
+ declare class RedisStorage implements StorageAdapter {
66
+ private readonly client;
67
+ private readonly keyPrefix;
68
+ private readonly ownsClient;
69
+ /**
70
+ * Maximum payload size in bytes (default: 10MB).
71
+ * Prevents excessively large values from being stored in Redis.
72
+ */
73
+ readonly maxPayloadSize: number;
74
+ constructor(options: RedisOptions & {
75
+ _client: Redis | Cluster;
76
+ _ownsClient: boolean;
77
+ });
78
+ private prefixKey;
79
+ acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult>;
80
+ save(key: string, response: StoredResponse): Promise<void>;
81
+ release(key: string): Promise<void>;
82
+ delete(key: string): Promise<void>;
83
+ clear(): Promise<void>;
84
+ /**
85
+ * Disconnect the Redis client if we own it.
86
+ * Call this during shutdown if using auto-created client.
87
+ */
88
+ disconnect(): Promise<void>;
89
+ }
90
+ /**
91
+ * Create a Redis storage adapter.
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * import { idempotix } from '@idempotix/core';
96
+ * import { redis } from '@idempotix/redis';
97
+ *
98
+ * // Auto-detect from Idempotix_REDIS_URL
99
+ * idempotix.configure({ storage: redis() });
100
+ *
101
+ * // With explicit URL
102
+ * idempotix.configure({ storage: redis('redis://localhost:6379') });
103
+ *
104
+ * // With options
105
+ * idempotix.configure({
106
+ * storage: redis({
107
+ * url: 'redis://localhost:6379',
108
+ * keyPrefix: 'myapp:',
109
+ * }),
110
+ * });
111
+ *
112
+ * // With existing client
113
+ * import Redis from 'ioredis';
114
+ * idempotix.configure({
115
+ * storage: redis({ client: new Redis() }),
116
+ * });
117
+ * ```
118
+ */
119
+ declare function redis(urlOrOptions?: string | RedisOptions): RedisStorage;
120
+
121
+ export { type RedisOptions, RedisStorage, redis };
package/dist/index.js ADDED
@@ -0,0 +1,149 @@
1
+ import Redis from 'ioredis';
2
+
3
+ // src/index.ts
4
+ var ENV_REDIS_URL = "Idempotix_REDIS_URL";
5
+ var ACQUIRE_SCRIPT = `
6
+ local key = KEYS[1]
7
+ local hash = ARGV[1]
8
+ local ttl = tonumber(ARGV[2])
9
+ local now = tonumber(ARGV[3])
10
+
11
+ local existing = redis.call('GET', key)
12
+ if existing then
13
+ return existing
14
+ end
15
+
16
+ local record = cjson.encode({
17
+ status = 'in_progress',
18
+ hash = hash ~= '' and hash or nil,
19
+ startedAt = now
20
+ })
21
+ redis.call('SET', key, record, 'PX', ttl)
22
+ return nil
23
+ `;
24
+ var RedisStorage = class {
25
+ client;
26
+ keyPrefix;
27
+ ownsClient;
28
+ /**
29
+ * Maximum payload size in bytes (default: 10MB).
30
+ * Prevents excessively large values from being stored in Redis.
31
+ */
32
+ maxPayloadSize;
33
+ constructor(options) {
34
+ this.client = options._client;
35
+ this.keyPrefix = options.keyPrefix ?? "Idempotix:";
36
+ this.ownsClient = options._ownsClient;
37
+ this.maxPayloadSize = options.maxPayloadSize ?? 10 * 1024 * 1024;
38
+ }
39
+ prefixKey(key) {
40
+ return `${this.keyPrefix}${key}`;
41
+ }
42
+ async acquire(key, hash, ttl) {
43
+ const prefixedKey = this.prefixKey(key);
44
+ const now = Date.now();
45
+ const result = await this.client.eval(
46
+ ACQUIRE_SCRIPT,
47
+ 1,
48
+ prefixedKey,
49
+ hash ?? "",
50
+ ttl.toString(),
51
+ now.toString()
52
+ );
53
+ if (result === null) {
54
+ return { status: "acquired" };
55
+ }
56
+ let existing;
57
+ try {
58
+ existing = JSON.parse(result);
59
+ } catch {
60
+ await this.client.del(prefixedKey);
61
+ return { status: "acquired" };
62
+ }
63
+ if (hash && existing.hash && existing.hash !== hash) {
64
+ return {
65
+ status: "mismatch",
66
+ existingHash: existing.hash,
67
+ providedHash: hash
68
+ };
69
+ }
70
+ if (existing.status === "completed") {
71
+ return {
72
+ status: "hit",
73
+ response: {
74
+ data: existing.data,
75
+ createdAt: existing.createdAt,
76
+ hash: existing.hash
77
+ }
78
+ };
79
+ }
80
+ return { status: "conflict", startedAt: existing.startedAt };
81
+ }
82
+ async save(key, response) {
83
+ const prefixedKey = this.prefixKey(key);
84
+ const existing = await this.client.get(prefixedKey);
85
+ if (!existing) return;
86
+ const ttl = await this.client.pttl(prefixedKey);
87
+ if (ttl <= 0) return;
88
+ const record = {
89
+ status: "completed",
90
+ hash: response.hash,
91
+ data: response.data,
92
+ createdAt: response.createdAt,
93
+ startedAt: Date.now()
94
+ };
95
+ await this.client.set(prefixedKey, JSON.stringify(record), "PX", ttl);
96
+ }
97
+ async release(key) {
98
+ await this.client.del(this.prefixKey(key));
99
+ }
100
+ async delete(key) {
101
+ await this.client.del(this.prefixKey(key));
102
+ }
103
+ async clear() {
104
+ const keys = await this.client.keys(`${this.keyPrefix}*`);
105
+ if (keys.length > 0) {
106
+ await this.client.del(...keys);
107
+ }
108
+ }
109
+ /**
110
+ * Disconnect the Redis client if we own it.
111
+ * Call this during shutdown if using auto-created client.
112
+ */
113
+ async disconnect() {
114
+ if (this.ownsClient) {
115
+ await this.client.quit();
116
+ }
117
+ }
118
+ };
119
+ function redis(urlOrOptions) {
120
+ if (typeof urlOrOptions === "string") {
121
+ return createRedisStorage({ url: urlOrOptions });
122
+ }
123
+ return createRedisStorage(urlOrOptions ?? {});
124
+ }
125
+ function createRedisStorage(options) {
126
+ let client;
127
+ let ownsClient = false;
128
+ if (options.client) {
129
+ client = options.client;
130
+ } else {
131
+ const url = options.url ?? process.env[ENV_REDIS_URL];
132
+ if (!url) {
133
+ throw new Error(
134
+ `Redis URL not provided. Either pass a URL, provide a client, or set ${ENV_REDIS_URL} environment variable.`
135
+ );
136
+ }
137
+ client = new Redis(url);
138
+ ownsClient = true;
139
+ }
140
+ return new RedisStorage({
141
+ ...options,
142
+ _client: client,
143
+ _ownsClient: ownsClient
144
+ });
145
+ }
146
+
147
+ export { RedisStorage, redis };
148
+ //# sourceMappingURL=index.js.map
149
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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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EA,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"]}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@idempotix/redis",
3
+ "version": "1.0.0",
4
+ "description": "Redis storage adapter for Idempotix idempotency - works with ioredis",
5
+ "author": "stacks0x",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/stacks0x/idempotix.git",
10
+ "directory": "packages/redis"
11
+ },
12
+ "keywords": [
13
+ "idempotency",
14
+ "idempotent",
15
+ "redis",
16
+ "ioredis",
17
+ "storage",
18
+ "cache",
19
+ "elasticache",
20
+ "redis-cloud"
21
+ ],
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js",
27
+ "require": "./dist/index.cjs"
28
+ }
29
+ },
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "files": [
34
+ "dist",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "dependencies": {
39
+ "@idempotix/core": "1.0.0"
40
+ },
41
+ "peerDependencies": {
42
+ "ioredis": "^5.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "ioredis": "^5.3.2",
46
+ "tsup": "^8.0.1",
47
+ "typescript": "^5.3.3"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "engines": {
53
+ "node": ">=20.0.0"
54
+ },
55
+ "scripts": {
56
+ "build": "tsup",
57
+ "dev": "tsup --watch",
58
+ "typecheck": "tsc --noEmit",
59
+ "clean": "rm -rf dist"
60
+ }
61
+ }