@oncely/redis 0.2.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/README.md ADDED
@@ -0,0 +1,128 @@
1
+ # @oncely/redis
2
+
3
+ Redis storage adapter for oncely using ioredis.
4
+
5
+ ## Installation
6
+
7
+ npm install @oncely/core @oncely/redis ioredis
8
+
9
+ ## Usage
10
+
11
+ import { redis, RedisStorage } from '@oncely/redis';
12
+ import { express as idempotent } from '@oncely/express';
13
+
14
+ // From environment variable (ONCELY_REDIS_URL)
15
+ const storage = redis();
16
+
17
+ // From URL
18
+ const storage = redis('redis://localhost:6379');
19
+
20
+ // With options
21
+ const storage = redis('redis://localhost:6379', {
22
+ keyPrefix: 'idem:',
23
+ });
24
+
25
+ // From existing ioredis client
26
+ import Redis from 'ioredis';
27
+ const client = new Redis();
28
+ const storage = new RedisStorage(client, { keyPrefix: 'idem:' });
29
+
30
+ // Use with Express
31
+ app.post('/orders', idempotent({ storage: redis() }), handler);
32
+
33
+ ## Environment Variables
34
+
35
+ ONCELY_REDIS_URL - Redis connection URL
36
+
37
+ ## License
38
+
39
+ MIT
40
+ import { oncely } from '@oncely/core';
41
+ import { redis } from '@oncely/redis';
42
+
43
+ oncely.configure({
44
+ storage: redis(),
45
+ ttl: '1h',
46
+ });
47
+
48
+ const app = express();
49
+
50
+ app.post('/api/orders', async (req, res) => {
51
+ const instance = oncely.createInstance();
52
+
53
+ const result = await instance.run({
54
+ key: req.headers[oncely.HEADER] as string,
55
+ handler: async () => {
56
+ // Create order...
57
+ return { orderId: 'ord_123' };
58
+ },
59
+ });
60
+
61
+ res.json(result.data);
62
+ });
63
+
64
+ ````
65
+
66
+ ### With Next.js
67
+
68
+ ```typescript
69
+ import { oncely } from '@oncely/core';
70
+ import { redis } from '@oncely/redis';
71
+
72
+ // In your instrumentation.ts or api route
73
+ oncely.configure({
74
+ storage: redis(),
75
+ ttl: '24h',
76
+ });
77
+ ````
78
+
79
+ ### Redis Cluster
80
+
81
+ ```typescript
82
+ import Redis from 'ioredis';
83
+ import { redis } from '@oncely/redis';
84
+
85
+ const cluster = new Redis.Cluster([
86
+ { host: 'node1.example.com', port: 6379 },
87
+ { host: 'node2.example.com', port: 6379 },
88
+ ]);
89
+
90
+ oncely.configure({
91
+ storage: redis({ client: cluster }),
92
+ });
93
+ ```
94
+
95
+ ### AWS ElastiCache
96
+
97
+ ```typescript
98
+ import { redis } from '@oncely/redis';
99
+
100
+ // Using ElastiCache endpoint
101
+ oncely.configure({
102
+ storage: redis('redis://my-cluster.abc123.cache.amazonaws.com:6379'),
103
+ });
104
+
105
+ // Or with TLS
106
+ oncely.configure({
107
+ storage: redis('rediss://my-cluster.abc123.cache.amazonaws.com:6379'),
108
+ });
109
+ ```
110
+
111
+ ## Storage Behavior
112
+
113
+ - **Lock Acquisition**: Uses atomic Lua script to acquire locks
114
+ - **TTL**: Keys automatically expire based on configured TTL
115
+ - **Conflict Detection**: Returns conflict status for in-progress requests
116
+ - **Hash Validation**: Validates request fingerprint to detect mismatches
117
+
118
+ ## Related Packages
119
+
120
+ - [@oncely/core](../core) - Core idempotency engine
121
+ - [@oncely/upstash](../upstash) - Upstash Redis adapter (HTTP-based)
122
+ - [@oncely/client](../client) - Client-side helpers
123
+ - [@oncely/express](../express) - Express.js middleware
124
+ - [@oncely/next](../next) - Next.js API route handlers
125
+
126
+ ## License
127
+
128
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,150 @@
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 = "ONCELY_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
+ constructor(options) {
35
+ this.client = options._client;
36
+ this.keyPrefix = options.keyPrefix ?? "oncely:";
37
+ this.ownsClient = options._ownsClient;
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__default.default(url);
138
+ ownsClient = true;
139
+ }
140
+ return new RedisStorage({
141
+ ...options,
142
+ _client: client,
143
+ _ownsClient: ownsClient
144
+ });
145
+ }
146
+
147
+ exports.RedisStorage = RedisStorage;
148
+ exports.redis = redis;
149
+ //# sourceMappingURL=index.cjs.map
150
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":["Redis"],"mappings":";;;;;;;;;AAcA,IAAM,aAAA,GAAgB,kBAAA;AAwCtB,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,SA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a,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 * @oncely/redis - Redis storage adapter for oncely\n *\n * Uses ioredis for standard Redis connections (TCP-based).\n * For HTTP-based Redis (Upstash, Vercel KV), use @oncely/upstash.\n */\n\nimport type { StorageAdapter, AcquireResult, StoredResponse } from '@oncely/core';\nimport Redis, { type Cluster } from 'ioredis';\n\n/**\n * Environment variable for Redis URL.\n * Scoped to oncely to avoid accidental connections.\n */\nconst ENV_REDIS_URL = 'ONCELY_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 ONCELY_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 'oncely:'\n */\n keyPrefix?: string;\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 '@oncely/redis';\n *\n * // From environment (ONCELY_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 constructor(options: RedisOptions & { _client: Redis | Cluster; _ownsClient: boolean }) {\n this.client = options._client;\n this.keyPrefix = options.keyPrefix ?? 'oncely:';\n this.ownsClient = options._ownsClient;\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 { oncely } from '@oncely/core';\n * import { redis } from '@oncely/redis';\n *\n * // Auto-detect from ONCELY_REDIS_URL\n * oncely.configure({ storage: redis() });\n *\n * // With explicit URL\n * oncely.configure({ storage: redis('redis://localhost:6379') });\n *\n * // With options\n * oncely.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 * oncely.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 '@oncely/core';\n"]}
@@ -0,0 +1,109 @@
1
+ import { StorageAdapter, AcquireResult, StoredResponse } from '@oncely/core';
2
+ export { AcquireResult, StorageAdapter, StoredResponse } from '@oncely/core';
3
+ import Redis, { Cluster } from 'ioredis';
4
+
5
+ /**
6
+ * @oncely/redis - Redis storage adapter for oncely
7
+ *
8
+ * Uses ioredis for standard Redis connections (TCP-based).
9
+ * For HTTP-based Redis (Upstash, Vercel KV), use @oncely/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 ONCELY_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 'oncely:'
29
+ */
30
+ keyPrefix?: string;
31
+ }
32
+ /**
33
+ * Redis storage adapter using ioredis.
34
+ *
35
+ * Works with:
36
+ * - Self-hosted Redis
37
+ * - AWS ElastiCache
38
+ * - Redis Cloud
39
+ * - Azure Cache for Redis
40
+ * - DigitalOcean Managed Redis
41
+ * - Any Redis-compatible service via TCP
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * import { redis } from '@oncely/redis';
46
+ *
47
+ * // From environment (ONCELY_REDIS_URL)
48
+ * const storage = redis();
49
+ *
50
+ * // From URL
51
+ * const storage = redis('redis://localhost:6379');
52
+ *
53
+ * // With existing client
54
+ * import Redis from 'ioredis';
55
+ * const storage = redis({ client: new Redis() });
56
+ * ```
57
+ */
58
+ declare class RedisStorage implements StorageAdapter {
59
+ private readonly client;
60
+ private readonly keyPrefix;
61
+ private readonly ownsClient;
62
+ constructor(options: RedisOptions & {
63
+ _client: Redis | Cluster;
64
+ _ownsClient: boolean;
65
+ });
66
+ private prefixKey;
67
+ acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult>;
68
+ save(key: string, response: StoredResponse): Promise<void>;
69
+ release(key: string): Promise<void>;
70
+ delete(key: string): Promise<void>;
71
+ clear(): Promise<void>;
72
+ /**
73
+ * Disconnect the Redis client if we own it.
74
+ * Call this during shutdown if using auto-created client.
75
+ */
76
+ disconnect(): Promise<void>;
77
+ }
78
+ /**
79
+ * Create a Redis storage adapter.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * import { oncely } from '@oncely/core';
84
+ * import { redis } from '@oncely/redis';
85
+ *
86
+ * // Auto-detect from ONCELY_REDIS_URL
87
+ * oncely.configure({ storage: redis() });
88
+ *
89
+ * // With explicit URL
90
+ * oncely.configure({ storage: redis('redis://localhost:6379') });
91
+ *
92
+ * // With options
93
+ * oncely.configure({
94
+ * storage: redis({
95
+ * url: 'redis://localhost:6379',
96
+ * keyPrefix: 'myapp:',
97
+ * }),
98
+ * });
99
+ *
100
+ * // With existing client
101
+ * import Redis from 'ioredis';
102
+ * oncely.configure({
103
+ * storage: redis({ client: new Redis() }),
104
+ * });
105
+ * ```
106
+ */
107
+ declare function redis(urlOrOptions?: string | RedisOptions): RedisStorage;
108
+
109
+ export { type RedisOptions, RedisStorage, redis };
@@ -0,0 +1,109 @@
1
+ import { StorageAdapter, AcquireResult, StoredResponse } from '@oncely/core';
2
+ export { AcquireResult, StorageAdapter, StoredResponse } from '@oncely/core';
3
+ import Redis, { Cluster } from 'ioredis';
4
+
5
+ /**
6
+ * @oncely/redis - Redis storage adapter for oncely
7
+ *
8
+ * Uses ioredis for standard Redis connections (TCP-based).
9
+ * For HTTP-based Redis (Upstash, Vercel KV), use @oncely/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 ONCELY_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 'oncely:'
29
+ */
30
+ keyPrefix?: string;
31
+ }
32
+ /**
33
+ * Redis storage adapter using ioredis.
34
+ *
35
+ * Works with:
36
+ * - Self-hosted Redis
37
+ * - AWS ElastiCache
38
+ * - Redis Cloud
39
+ * - Azure Cache for Redis
40
+ * - DigitalOcean Managed Redis
41
+ * - Any Redis-compatible service via TCP
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * import { redis } from '@oncely/redis';
46
+ *
47
+ * // From environment (ONCELY_REDIS_URL)
48
+ * const storage = redis();
49
+ *
50
+ * // From URL
51
+ * const storage = redis('redis://localhost:6379');
52
+ *
53
+ * // With existing client
54
+ * import Redis from 'ioredis';
55
+ * const storage = redis({ client: new Redis() });
56
+ * ```
57
+ */
58
+ declare class RedisStorage implements StorageAdapter {
59
+ private readonly client;
60
+ private readonly keyPrefix;
61
+ private readonly ownsClient;
62
+ constructor(options: RedisOptions & {
63
+ _client: Redis | Cluster;
64
+ _ownsClient: boolean;
65
+ });
66
+ private prefixKey;
67
+ acquire(key: string, hash: string | null, ttl: number): Promise<AcquireResult>;
68
+ save(key: string, response: StoredResponse): Promise<void>;
69
+ release(key: string): Promise<void>;
70
+ delete(key: string): Promise<void>;
71
+ clear(): Promise<void>;
72
+ /**
73
+ * Disconnect the Redis client if we own it.
74
+ * Call this during shutdown if using auto-created client.
75
+ */
76
+ disconnect(): Promise<void>;
77
+ }
78
+ /**
79
+ * Create a Redis storage adapter.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * import { oncely } from '@oncely/core';
84
+ * import { redis } from '@oncely/redis';
85
+ *
86
+ * // Auto-detect from ONCELY_REDIS_URL
87
+ * oncely.configure({ storage: redis() });
88
+ *
89
+ * // With explicit URL
90
+ * oncely.configure({ storage: redis('redis://localhost:6379') });
91
+ *
92
+ * // With options
93
+ * oncely.configure({
94
+ * storage: redis({
95
+ * url: 'redis://localhost:6379',
96
+ * keyPrefix: 'myapp:',
97
+ * }),
98
+ * });
99
+ *
100
+ * // With existing client
101
+ * import Redis from 'ioredis';
102
+ * oncely.configure({
103
+ * storage: redis({ client: new Redis() }),
104
+ * });
105
+ * ```
106
+ */
107
+ declare function redis(urlOrOptions?: string | RedisOptions): RedisStorage;
108
+
109
+ export { type RedisOptions, RedisStorage, redis };
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ import Redis from 'ioredis';
2
+
3
+ // src/index.ts
4
+ var ENV_REDIS_URL = "ONCELY_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
+ constructor(options) {
29
+ this.client = options._client;
30
+ this.keyPrefix = options.keyPrefix ?? "oncely:";
31
+ this.ownsClient = options._ownsClient;
32
+ }
33
+ prefixKey(key) {
34
+ return `${this.keyPrefix}${key}`;
35
+ }
36
+ async acquire(key, hash, ttl) {
37
+ const prefixedKey = this.prefixKey(key);
38
+ const now = Date.now();
39
+ const result = await this.client.eval(
40
+ ACQUIRE_SCRIPT,
41
+ 1,
42
+ prefixedKey,
43
+ hash ?? "",
44
+ ttl.toString(),
45
+ now.toString()
46
+ );
47
+ if (result === null) {
48
+ return { status: "acquired" };
49
+ }
50
+ let existing;
51
+ try {
52
+ existing = JSON.parse(result);
53
+ } catch {
54
+ await this.client.del(prefixedKey);
55
+ return { status: "acquired" };
56
+ }
57
+ if (hash && existing.hash && existing.hash !== hash) {
58
+ return {
59
+ status: "mismatch",
60
+ existingHash: existing.hash,
61
+ providedHash: hash
62
+ };
63
+ }
64
+ if (existing.status === "completed") {
65
+ return {
66
+ status: "hit",
67
+ response: {
68
+ data: existing.data,
69
+ createdAt: existing.createdAt,
70
+ hash: existing.hash
71
+ }
72
+ };
73
+ }
74
+ return { status: "conflict", startedAt: existing.startedAt };
75
+ }
76
+ async save(key, response) {
77
+ const prefixedKey = this.prefixKey(key);
78
+ const existing = await this.client.get(prefixedKey);
79
+ if (!existing) return;
80
+ const ttl = await this.client.pttl(prefixedKey);
81
+ if (ttl <= 0) return;
82
+ const record = {
83
+ status: "completed",
84
+ hash: response.hash,
85
+ data: response.data,
86
+ createdAt: response.createdAt,
87
+ startedAt: Date.now()
88
+ };
89
+ await this.client.set(prefixedKey, JSON.stringify(record), "PX", ttl);
90
+ }
91
+ async release(key) {
92
+ await this.client.del(this.prefixKey(key));
93
+ }
94
+ async delete(key) {
95
+ await this.client.del(this.prefixKey(key));
96
+ }
97
+ async clear() {
98
+ const keys = await this.client.keys(`${this.keyPrefix}*`);
99
+ if (keys.length > 0) {
100
+ await this.client.del(...keys);
101
+ }
102
+ }
103
+ /**
104
+ * Disconnect the Redis client if we own it.
105
+ * Call this during shutdown if using auto-created client.
106
+ */
107
+ async disconnect() {
108
+ if (this.ownsClient) {
109
+ await this.client.quit();
110
+ }
111
+ }
112
+ };
113
+ function redis(urlOrOptions) {
114
+ if (typeof urlOrOptions === "string") {
115
+ return createRedisStorage({ url: urlOrOptions });
116
+ }
117
+ return createRedisStorage(urlOrOptions ?? {});
118
+ }
119
+ function createRedisStorage(options) {
120
+ let client;
121
+ let ownsClient = false;
122
+ if (options.client) {
123
+ client = options.client;
124
+ } else {
125
+ const url = options.url ?? process.env[ENV_REDIS_URL];
126
+ if (!url) {
127
+ throw new Error(
128
+ `Redis URL not provided. Either pass a URL, provide a client, or set ${ENV_REDIS_URL} environment variable.`
129
+ );
130
+ }
131
+ client = new Redis(url);
132
+ ownsClient = true;
133
+ }
134
+ return new RedisStorage({
135
+ ...options,
136
+ _client: client,
137
+ _ownsClient: ownsClient
138
+ });
139
+ }
140
+
141
+ export { RedisStorage, redis };
142
+ //# sourceMappingURL=index.js.map
143
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAcA,IAAM,aAAA,GAAgB,kBAAA;AAwCtB,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,EAEjB,YAAY,OAAA,EAA4E;AACtF,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,OAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,SAAA;AACtC,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,WAAA;AAAA,EAC5B;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,CAA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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 * @oncely/redis - Redis storage adapter for oncely\n *\n * Uses ioredis for standard Redis connections (TCP-based).\n * For HTTP-based Redis (Upstash, Vercel KV), use @oncely/upstash.\n */\n\nimport type { StorageAdapter, AcquireResult, StoredResponse } from '@oncely/core';\nimport Redis, { type Cluster } from 'ioredis';\n\n/**\n * Environment variable for Redis URL.\n * Scoped to oncely to avoid accidental connections.\n */\nconst ENV_REDIS_URL = 'ONCELY_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 ONCELY_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 'oncely:'\n */\n keyPrefix?: string;\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 '@oncely/redis';\n *\n * // From environment (ONCELY_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 constructor(options: RedisOptions & { _client: Redis | Cluster; _ownsClient: boolean }) {\n this.client = options._client;\n this.keyPrefix = options.keyPrefix ?? 'oncely:';\n this.ownsClient = options._ownsClient;\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 { oncely } from '@oncely/core';\n * import { redis } from '@oncely/redis';\n *\n * // Auto-detect from ONCELY_REDIS_URL\n * oncely.configure({ storage: redis() });\n *\n * // With explicit URL\n * oncely.configure({ storage: redis('redis://localhost:6379') });\n *\n * // With options\n * oncely.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 * oncely.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 '@oncely/core';\n"]}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@oncely/redis",
3
+ "version": "0.2.0",
4
+ "description": "Redis storage adapter for oncely idempotency - works with ioredis",
5
+ "author": "stacks0x",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/stacks0x/oncely.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
+ "scripts": {
39
+ "build": "tsup",
40
+ "dev": "tsup --watch",
41
+ "typecheck": "tsc --noEmit",
42
+ "clean": "rm -rf dist"
43
+ },
44
+ "dependencies": {
45
+ "@oncely/core": "workspace:*"
46
+ },
47
+ "peerDependencies": {
48
+ "ioredis": "^5.0.0"
49
+ },
50
+ "devDependencies": {
51
+ "ioredis": "^5.3.2",
52
+ "tsup": "^8.0.1",
53
+ "typescript": "^5.3.3"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "engines": {
59
+ "node": ">=18.0.0"
60
+ }
61
+ }