@exisjs/redis 0.0.0-stage → 0.11.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 Prasanth
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
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # @exisjs/redis
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm @exisjs/redis package](https://img.shields.io/npm/v/@exisjs/redis.svg)](https://npmjs.org/package/@exisjs/redis)
4
+ [![npm license](https://img.shields.io/npm/l/@exisjs/redis.svg)](https://github.com/v25group/exisjs/blob/main/LICENSE)
5
+
6
+ Redis stores for [ExisJS](https://github.com/v25group/exisjs). With them, several instances of one app share their rate limits, idempotency keys, cron locks and `@Cacheable` results.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm install @exisjs/redis ioredis
12
+ ```
13
+
14
+ `ioredis` is an optional peer dependency. Any client that has the commands in `RedisClientLike` works, including node-redis through a short adapter.
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import Redis from 'ioredis'
20
+ import { redisStores } from '@exisjs/redis'
21
+
22
+ export const stores = redisStores(new Redis(process.env.REDIS_URL!), {
23
+ prefix: 'exis:', // the default
24
+ })
25
+ ```
26
+
27
+ | Store | Wire it with |
28
+ | :--------------------------------------------- | :---------------------------------------------------------------------- |
29
+ | `stores.rateLimit` (`RedisRateLimitStore`) | `rateLimit({ max, windowMs, store: stores.rateLimit })` |
30
+ | `stores.idempotency` (`RedisIdempotencyStore`) | `idempotent({ store: stores.idempotency })` or `@Idempotent({ store })` |
31
+ | `stores.cronLock` (`RedisCronLock`) | `app.cron.lock = stores.cronLock` in `onStart` |
32
+ | `stores.cache` (`RedisCacheStore`) | `cache: { store: stores.cache }` in `exis.config.ts` |
33
+
34
+ Every class also takes `(client, options?)` directly.
35
+
36
+ - **Rate limit:** fixed windows, one atomic Lua script per hit (`INCR` and `PEXPIRE`). Implements `increment`, `get` and `reset`.
37
+ - **Idempotency:** responses as JSON with a `PX` TTL. `claim` is `SET NX PX` with a token, `release` deletes that claim only.
38
+ - **Cron lock:** `SET NX PX` with a random token, released with a compare-and-delete script. ExisJS locks each tick and does not release it after the run, so a later timer for the same tick is refused. `minHoldMs` is optional and no longer needed.
39
+ - **Cache:** JSON values with a `PX` TTL (default 5 minutes). A cached `null` stays `null`; a miss is `undefined`.
40
+
41
+ Keys: `<prefix>rl:<key>`, `<prefix>idem:<key>`, `<prefix>idem-claim:<key>`, `<prefix>cron:<job>`, `<prefix>cache:<key>`.
42
+
43
+ For money, keep a unique key in your database too (an order or payment reference). An idempotency key only covers retries of one request.
44
+
45
+ Full guide, including the node-redis adapter: [Shared stores with Redis](https://github.com/v25group/exisjs/blob/main/docs/content/redis.mdx).
46
+
47
+ ## License
48
+
49
+ MIT
@@ -0,0 +1,31 @@
1
+ import type { CacheStore } from 'exisjs/middleware';
2
+ import { type RedisClientLike, type RedisStoreOptions } from './client';
3
+ export interface RedisCacheStoreOptions extends RedisStoreOptions {
4
+ /**
5
+ * How long a value is kept when `set` gets no TTL, in ms. Default 300000
6
+ * (5 minutes, like the in-memory store)
7
+ */
8
+ defaultTtlMs?: number;
9
+ }
10
+ /**
11
+ * Keeps `@Cacheable` results in Redis, so every instance shares one cache
12
+ * and `@CacheEvict` on one instance clears it for all. Values are saved as
13
+ * JSON: a cached `null` comes back as `null`, a miss as `undefined`.
14
+ *
15
+ * Keys: `<prefix>cache:<key>`
16
+ *
17
+ * @example exis.config.ts
18
+ * ```ts
19
+ * export default defineConfig({ cache: { store: new RedisCacheStore(redis) } })
20
+ * ```
21
+ */
22
+ export declare class RedisCacheStore implements CacheStore {
23
+ private readonly client;
24
+ private readonly prefix;
25
+ private readonly defaultTtlMs;
26
+ constructor(client: RedisClientLike, options?: RedisCacheStoreOptions);
27
+ get(key: string): Promise<unknown>;
28
+ set(key: string, value: unknown, ttlMs?: number): Promise<void>;
29
+ delete(key: string): Promise<void>;
30
+ }
31
+ //# sourceMappingURL=cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACvB,MAAM,UAAU,CAAA;AAEjB,MAAM,WAAW,sBAAuB,SAAQ,iBAAiB;IAC/D;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAED;;;;;;;;;;;GAWG;AACH,qBAAa,eAAgB,YAAW,UAAU;IAK9C,OAAO,CAAC,QAAQ,CAAC,MAAM;IAJzB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAQ;gBAGlB,MAAM,EAAE,eAAe,EACxC,OAAO,GAAE,sBAA2B;IAMhC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAOlC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAc/D,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAGzC"}
package/dist/cache.js ADDED
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedisCacheStore = void 0;
4
+ const client_1 = require("./client");
5
+ /**
6
+ * Keeps `@Cacheable` results in Redis, so every instance shares one cache
7
+ * and `@CacheEvict` on one instance clears it for all. Values are saved as
8
+ * JSON: a cached `null` comes back as `null`, a miss as `undefined`.
9
+ *
10
+ * Keys: `<prefix>cache:<key>`
11
+ *
12
+ * @example exis.config.ts
13
+ * ```ts
14
+ * export default defineConfig({ cache: { store: new RedisCacheStore(redis) } })
15
+ * ```
16
+ */
17
+ class RedisCacheStore {
18
+ constructor(client, options = {}) {
19
+ this.client = client;
20
+ this.prefix = `${options.prefix ?? client_1.DEFAULT_PREFIX}cache:`;
21
+ this.defaultTtlMs = options.defaultTtlMs ?? 300000;
22
+ }
23
+ async get(key) {
24
+ const raw = await this.client.get(this.prefix + key);
25
+ // Redis has no key: a miss. A cached null is the string "null"
26
+ if (raw === null || raw === undefined)
27
+ return undefined;
28
+ return JSON.parse(raw);
29
+ }
30
+ async set(key, value, ttlMs) {
31
+ // undefined means "not cached" (JSON.stringify would return undefined)
32
+ if (value === undefined) {
33
+ await this.delete(key);
34
+ return;
35
+ }
36
+ await this.client.set(this.prefix + key, JSON.stringify(value), 'PX', Math.max(1, Math.ceil(ttlMs ?? this.defaultTtlMs)));
37
+ }
38
+ async delete(key) {
39
+ await this.client.del(this.prefix + key);
40
+ }
41
+ }
42
+ exports.RedisCacheStore = RedisCacheStore;
43
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":";;;AACA,qCAIiB;AAUjB;;;;;;;;;;;GAWG;AACH,MAAa,eAAe;IAI1B,YACmB,MAAuB,EACxC,UAAkC,EAAE;QADnB,WAAM,GAAN,MAAM,CAAiB;QAGxC,IAAI,CAAC,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,IAAI,uBAAc,QAAQ,CAAA;QACzD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,MAAO,CAAA;IACrD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW;QACnB,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;QACpD,+DAA+D;QAC/D,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS;YAAE,OAAO,SAAS,CAAA;QACvD,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACxB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW,EAAE,KAAc,EAAE,KAAc;QACnD,uEAAuE;QACvE,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;YACtB,OAAM;QACR,CAAC;QACD,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CACnB,IAAI,CAAC,MAAM,GAAG,GAAG,EACjB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EACrB,IAAI,EACJ,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,YAAY,CAAC,CAAC,CACnD,CAAA;IACH,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW;QACtB,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;IAC1C,CAAC;CACF;AApCD,0CAoCC"}
@@ -0,0 +1,61 @@
1
+ /** Arguments after the keys of an `EVAL`; Redis receives them as strings */
2
+ export type RedisArg = string | number;
3
+ /**
4
+ * The Redis commands the stores use. An `ioredis` client (`Redis` or
5
+ * `Cluster`) fits as is. For `node-redis`, wrap the client:
6
+ *
7
+ * @example node-redis
8
+ * ```ts
9
+ * import { createClient } from 'redis'
10
+ * import type { RedisClientLike } from '@exisjs/redis'
11
+ *
12
+ * const client = await createClient({ url: process.env.REDIS_URL }).connect()
13
+ * const split = (n: number, args: RedisArg[]) => ({
14
+ * keys: args.slice(0, n).map(String),
15
+ * arguments: args.slice(n).map(String),
16
+ * })
17
+ * export const redis: RedisClientLike = {
18
+ * eval: (script, n, ...args) => client.eval(script, split(n, args)),
19
+ * evalsha: (sha, n, ...args) => client.evalSha(sha, split(n, args)),
20
+ * get: (key) => client.get(key),
21
+ * set: (key, value, _px, ttlMs, nx) =>
22
+ * client.set(key, value, { PX: ttlMs, NX: nx === 'NX' }),
23
+ * del: (key) => client.del(key),
24
+ * }
25
+ * ```
26
+ */
27
+ export interface RedisClientLike {
28
+ /** `EVAL script numKeys ...keys ...args` */
29
+ eval(script: string, numKeys: number, ...args: RedisArg[]): Promise<unknown>;
30
+ /**
31
+ * `EVALSHA sha1 numKeys ...keys ...args`. Optional: when present, scripts
32
+ * are sent by hash and only re-sent in full after a `NOSCRIPT` error.
33
+ */
34
+ evalsha?(sha1: string, numKeys: number, ...args: RedisArg[]): Promise<unknown>;
35
+ /** `GET key`: the value, or `null` when the key does not exist */
36
+ get(key: string): Promise<string | null>;
37
+ /**
38
+ * `SET key value PX ttlMs [NX]`. Resolves to `'OK'` when the value was
39
+ * written, and to `null` when `NX` was given and the key already existed.
40
+ */
41
+ set(key: string, value: string, px: 'PX', ttlMs: number, nx?: 'NX'): Promise<unknown>;
42
+ /** `DEL key` */
43
+ del(key: string): Promise<unknown>;
44
+ }
45
+ /** Options shared by every store */
46
+ export interface RedisStoreOptions {
47
+ /**
48
+ * Put in front of every key, so several apps can share one Redis database.
49
+ * Default `exis:`
50
+ */
51
+ prefix?: string;
52
+ }
53
+ export declare const DEFAULT_PREFIX = "exis:";
54
+ /**
55
+ * Runs a Lua script, by hash when the client has `evalsha`, falling back to
56
+ * `eval` (which also loads the script) when Redis does not know it yet.
57
+ */
58
+ export declare function runScript(client: RedisClientLike, script: string, keys: string[], args: RedisArg[]): Promise<unknown>;
59
+ /** Whether a `SET ... NX` reply means the value was written */
60
+ export declare function setSucceeded(reply: unknown): boolean;
61
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,4EAA4E;AAC5E,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAA;AAEtC;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,WAAW,eAAe;IAC9B,4CAA4C;IAC5C,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC5E;;;OAGG;IACH,OAAO,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC9E,kEAAkE;IAClE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAA;IACxC;;;OAGG;IACH,GAAG,CACD,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,EACb,EAAE,EAAE,IAAI,EACR,KAAK,EAAE,MAAM,EACb,EAAE,CAAC,EAAE,IAAI,GACR,OAAO,CAAC,OAAO,CAAC,CAAA;IACnB,gBAAgB;IAChB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CACnC;AAED,oCAAoC;AACpC,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,eAAO,MAAM,cAAc,UAAU,CAAA;AAarC;;;GAGG;AACH,wBAAsB,SAAS,CAC7B,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EAAE,EACd,IAAI,EAAE,QAAQ,EAAE,GACf,OAAO,CAAC,OAAO,CAAC,CASlB;AAED,+DAA+D;AAC/D,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAEpD"}
package/dist/client.js ADDED
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DEFAULT_PREFIX = void 0;
7
+ exports.runScript = runScript;
8
+ exports.setSucceeded = setSucceeded;
9
+ const node_crypto_1 = __importDefault(require("node:crypto"));
10
+ exports.DEFAULT_PREFIX = 'exis:';
11
+ const shas = new Map();
12
+ function sha1(script) {
13
+ let sha = shas.get(script);
14
+ if (!sha) {
15
+ sha = node_crypto_1.default.createHash('sha1').update(script).digest('hex');
16
+ shas.set(script, sha);
17
+ }
18
+ return sha;
19
+ }
20
+ /**
21
+ * Runs a Lua script, by hash when the client has `evalsha`, falling back to
22
+ * `eval` (which also loads the script) when Redis does not know it yet.
23
+ */
24
+ async function runScript(client, script, keys, args) {
25
+ if (client.evalsha) {
26
+ try {
27
+ return await client.evalsha(sha1(script), keys.length, ...keys, ...args);
28
+ }
29
+ catch (err) {
30
+ if (!String(err?.message ?? err).includes('NOSCRIPT'))
31
+ throw err;
32
+ }
33
+ }
34
+ return client.eval(script, keys.length, ...keys, ...args);
35
+ }
36
+ /** Whether a `SET ... NX` reply means the value was written */
37
+ function setSucceeded(reply) {
38
+ return reply === 'OK';
39
+ }
40
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;;;;AAgFA,8BAcC;AAGD,oCAEC;AAnGD,8DAAgC;AA+DnB,QAAA,cAAc,GAAG,OAAO,CAAA;AAErC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAA;AAEtC,SAAS,IAAI,CAAC,MAAc;IAC1B,IAAI,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IAC1B,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,GAAG,GAAG,qBAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;QAC5D,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACvB,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED;;;GAGG;AACI,KAAK,UAAU,SAAS,CAC7B,MAAuB,EACvB,MAAc,EACd,IAAc,EACd,IAAgB;IAEhB,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,IAAI,CAAC;YACH,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC,CAAA;QAC1E,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,IAAI,GAAG,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC;gBAAE,MAAM,GAAG,CAAA;QAClE,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC,CAAA;AAC3D,CAAC;AAED,+DAA+D;AAC/D,SAAgB,YAAY,CAAC,KAAc;IACzC,OAAO,KAAK,KAAK,IAAI,CAAA;AACvB,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { CronLock } from 'exisjs/cron';
2
+ import { type RedisClientLike, type RedisStoreOptions } from './client';
3
+ export interface RedisCronLockOptions extends RedisStoreOptions {
4
+ /**
5
+ * Keeps a lock for at least this long after it was acquired, in ms, even
6
+ * when it is released sooner. Rarely needed: ExisJS locks each tick and
7
+ * does not release the lock after a run. Default 0.
8
+ */
9
+ minHoldMs?: number;
10
+ }
11
+ /**
12
+ * A lock for `app.cron.lock`, so one instance runs each scheduled job.
13
+ * `acquire` is `SET NX PX` with a random token, and `release` deletes the
14
+ * key only while it still holds that token, so an instance whose lock
15
+ * expired mid-run never frees another instance's lock.
16
+ *
17
+ * Keys: `<prefix>cron:<job name>`
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * app.cron.lock = new RedisCronLock(redis)
22
+ * ```
23
+ */
24
+ export declare class RedisCronLock implements CronLock {
25
+ private readonly client;
26
+ private readonly prefix;
27
+ private readonly minHoldMs;
28
+ private readonly held;
29
+ constructor(client: RedisClientLike, options?: RedisCronLockOptions);
30
+ acquire(jobName: string, ttlMs: number): Promise<boolean>;
31
+ release(jobName: string): Promise<void>;
32
+ }
33
+ //# sourceMappingURL=cron-lock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron-lock.d.ts","sourceRoot":"","sources":["../src/cron-lock.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAIL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACvB,MAAM,UAAU,CAAA;AAGjB,MAAM,WAAW,oBAAqB,SAAQ,iBAAiB;IAC7D;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,aAAc,YAAW,QAAQ;IAM1C,OAAO,CAAC,QAAQ,CAAC,MAAM;IALzB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAQ;IAClC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAmD;gBAGrD,MAAM,EAAE,eAAe,EACxC,OAAO,GAAE,oBAAyB;IAM9B,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAezD,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAY9C"}
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RedisCronLock = void 0;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const client_1 = require("./client");
9
+ const scripts_1 = require("./scripts");
10
+ /**
11
+ * A lock for `app.cron.lock`, so one instance runs each scheduled job.
12
+ * `acquire` is `SET NX PX` with a random token, and `release` deletes the
13
+ * key only while it still holds that token, so an instance whose lock
14
+ * expired mid-run never frees another instance's lock.
15
+ *
16
+ * Keys: `<prefix>cron:<job name>`
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * app.cron.lock = new RedisCronLock(redis)
21
+ * ```
22
+ */
23
+ class RedisCronLock {
24
+ constructor(client, options = {}) {
25
+ this.client = client;
26
+ this.held = new Map();
27
+ this.prefix = `${options.prefix ?? client_1.DEFAULT_PREFIX}cron:`;
28
+ this.minHoldMs = Math.max(0, options.minHoldMs ?? 0);
29
+ }
30
+ async acquire(jobName, ttlMs) {
31
+ const token = node_crypto_1.default.randomUUID();
32
+ const at = Date.now();
33
+ const reply = await this.client.set(this.prefix + jobName, token, 'PX', Math.max(1, Math.ceil(ttlMs)), 'NX');
34
+ if (!(0, client_1.setSucceeded)(reply))
35
+ return false;
36
+ this.held.set(jobName, { token, at });
37
+ return true;
38
+ }
39
+ async release(jobName) {
40
+ const lock = this.held.get(jobName);
41
+ if (!lock)
42
+ return;
43
+ this.held.delete(jobName);
44
+ const key = this.prefix + jobName;
45
+ const keepMs = Math.ceil(lock.at + this.minHoldMs - Date.now());
46
+ if (keepMs > 0) {
47
+ await (0, client_1.runScript)(this.client, scripts_1.HOLD_SCRIPT, [key], [lock.token, keepMs]);
48
+ }
49
+ else {
50
+ await (0, client_1.runScript)(this.client, scripts_1.RELEASE_SCRIPT, [key], [lock.token]);
51
+ }
52
+ }
53
+ }
54
+ exports.RedisCronLock = RedisCronLock;
55
+ //# sourceMappingURL=cron-lock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron-lock.js","sourceRoot":"","sources":["../src/cron-lock.ts"],"names":[],"mappings":";;;;;;AAAA,8DAAgC;AAEhC,qCAMiB;AACjB,uCAAuD;AAWvD;;;;;;;;;;;;GAYG;AACH,MAAa,aAAa;IAKxB,YACmB,MAAuB,EACxC,UAAgC,EAAE;QADjB,WAAM,GAAN,MAAM,CAAiB;QAHzB,SAAI,GAAG,IAAI,GAAG,EAAyC,CAAA;QAMtE,IAAI,CAAC,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,IAAI,uBAAc,OAAO,CAAA;QACxD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,SAAS,IAAI,CAAC,CAAC,CAAA;IACtD,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,OAAe,EAAE,KAAa;QAC1C,MAAM,KAAK,GAAG,qBAAM,CAAC,UAAU,EAAE,CAAA;QACjC,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QACrB,MAAM,KAAK,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import type { IdempotencyRecord, IdempotencyStore } from 'exisjs/middleware';
2
+ import { type RedisClientLike, type RedisStoreOptions } from './client';
3
+ export interface RedisIdempotencyStoreOptions extends RedisStoreOptions {
4
+ /**
5
+ * How long a record is kept when `idempotent()` passes no TTL, in ms.
6
+ * Default 86400000 (24 hours)
7
+ */
8
+ defaultTtlMs?: number;
9
+ }
10
+ /**
11
+ * Keeps idempotent responses in Redis, so a repeated `Idempotency-Key`
12
+ * gets the first response from any instance. `claim` is `SET NX PX`, so of
13
+ * two copies of a request sent to two instances at once, only one runs.
14
+ *
15
+ * Keys: `<prefix>idem:<key>` (the stored response) and
16
+ * `<prefix>idem-claim:<key>` (held while the first request runs).
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * app.post('/payments', idempotent({ store: new RedisIdempotencyStore(redis) }), pay)
21
+ * ```
22
+ */
23
+ export declare class RedisIdempotencyStore implements IdempotencyStore {
24
+ private readonly client;
25
+ private readonly recordPrefix;
26
+ private readonly claimPrefix;
27
+ private readonly defaultTtlMs;
28
+ private readonly tokens;
29
+ constructor(client: RedisClientLike, options?: RedisIdempotencyStoreOptions);
30
+ get(key: string): Promise<IdempotencyRecord | null>;
31
+ set(key: string, data: IdempotencyRecord, ttlMs?: number): Promise<void>;
32
+ claim(key: string, ttlMs: number): Promise<boolean>;
33
+ release(key: string): Promise<void>;
34
+ }
35
+ //# sourceMappingURL=idempotency.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotency.d.ts","sourceRoot":"","sources":["../src/idempotency.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAE5E,OAAO,EAIL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACvB,MAAM,UAAU,CAAA;AAGjB,MAAM,WAAW,4BAA6B,SAAQ,iBAAiB;IACrE;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAQD;;;;;;;;;;;;GAYG;AACH,qBAAa,qBAAsB,YAAW,gBAAgB;IAS1D,OAAO,CAAC,QAAQ,CAAC,MAAM;IARzB,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAQ;IACrC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAQ;IACpC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAQ;IAGrC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA4B;gBAGhC,MAAM,EAAE,eAAe,EACxC,OAAO,GAAE,4BAAiC;IAQtC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAUnD,GAAG,CACP,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,iBAAiB,EACvB,KAAK,SAAoB,GACxB,OAAO,CAAC,IAAI,CAAC;IAYV,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAcnD,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAc1C"}
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RedisIdempotencyStore = void 0;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const client_1 = require("./client");
9
+ const scripts_1 = require("./scripts");
10
+ /**
11
+ * Keeps idempotent responses in Redis, so a repeated `Idempotency-Key`
12
+ * gets the first response from any instance. `claim` is `SET NX PX`, so of
13
+ * two copies of a request sent to two instances at once, only one runs.
14
+ *
15
+ * Keys: `<prefix>idem:<key>` (the stored response) and
16
+ * `<prefix>idem-claim:<key>` (held while the first request runs).
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * app.post('/payments', idempotent({ store: new RedisIdempotencyStore(redis) }), pay)
21
+ * ```
22
+ */
23
+ class RedisIdempotencyStore {
24
+ constructor(client, options = {}) {
25
+ this.client = client;
26
+ // Token of each claim this instance holds, so release() never deletes a
27
+ // claim that expired and was taken by another instance meanwhile
28
+ this.tokens = new Map();
29
+ const prefix = options.prefix ?? client_1.DEFAULT_PREFIX;
30
+ this.recordPrefix = `${prefix}idem:`;
31
+ this.claimPrefix = `${prefix}idem-claim:`;
32
+ this.defaultTtlMs = options.defaultTtlMs ?? 86400000;
33
+ }
34
+ async get(key) {
35
+ const raw = await this.client.get(this.recordPrefix + key);
36
+ if (raw === null || raw === undefined)
37
+ return null;
38
+ const { bodyEncoding, ...stored } = JSON.parse(raw);
39
+ if (bodyEncoding === 'base64') {
40
+ stored.body = Buffer.from(stored.body, 'base64');
41
+ }
42
+ return stored;
43
+ }
44
+ async set(key, data, ttlMs = this.defaultTtlMs) {
45
+ const stored = Buffer.isBuffer(data.body)
46
+ ? { ...data, body: data.body.toString('base64'), bodyEncoding: 'base64' }
47
+ : data;
48
+ await this.client.set(this.recordPrefix + key, JSON.stringify(stored), 'PX', Math.max(1, Math.ceil(ttlMs)));
49
+ }
50
+ async claim(key, ttlMs) {
51
+ const token = node_crypto_1.default.randomUUID();
52
+ const reply = await this.client.set(this.claimPrefix + key, token, 'PX', Math.max(1, Math.ceil(ttlMs)), 'NX');
53
+ if (!(0, client_1.setSucceeded)(reply))
54
+ return false;
55
+ this.tokens.set(key, token);
56
+ return true;
57
+ }
58
+ async release(key) {
59
+ const token = this.tokens.get(key);
60
+ this.tokens.delete(key);
61
+ if (token === undefined) {
62
+ await this.client.del(this.claimPrefix + key);
63
+ return;
64
+ }
65
+ await (0, client_1.runScript)(this.client, scripts_1.RELEASE_SCRIPT, [this.claimPrefix + key], [token]);
66
+ }
67
+ }
68
+ exports.RedisIdempotencyStore = RedisIdempotencyStore;
69
+ //# sourceMappingURL=idempotency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotency.js","sourceRoot":"","sources":["../src/idempotency.ts"],"names":[],"mappings":";;;;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AC,IAAI,CAAC,WAAW,GAAG,GAAG,CAAC,EACxB,CAAC,KAAK,CAAC,CACR,CAAA;IACH,CAAC;CACF;AAxED,sDAwEC"}
@@ -0,0 +1,42 @@
1
+ import { type RedisClientLike, type RedisStoreOptions } from './client';
2
+ import { RedisRateLimitStore } from './rate-limit';
3
+ import { RedisIdempotencyStore, type RedisIdempotencyStoreOptions } from './idempotency';
4
+ import { RedisCronLock, type RedisCronLockOptions } from './cron-lock';
5
+ import { RedisCacheStore, type RedisCacheStoreOptions } from './cache';
6
+ export { DEFAULT_PREFIX, type RedisArg, type RedisClientLike, type RedisStoreOptions, } from './client';
7
+ export { RedisRateLimitStore } from './rate-limit';
8
+ export { RedisIdempotencyStore, type RedisIdempotencyStoreOptions, } from './idempotency';
9
+ export { RedisCronLock, type RedisCronLockOptions } from './cron-lock';
10
+ export { RedisCacheStore, type RedisCacheStoreOptions } from './cache';
11
+ export interface RedisStoresOptions extends RedisStoreOptions {
12
+ /** Options for the idempotency store (its `prefix` is the shared one) */
13
+ idempotency?: Omit<RedisIdempotencyStoreOptions, 'prefix'>;
14
+ /** Options for the cron lock (its `prefix` is the shared one) */
15
+ cronLock?: Omit<RedisCronLockOptions, 'prefix'>;
16
+ /** Options for the cache store (its `prefix` is the shared one) */
17
+ cache?: Omit<RedisCacheStoreOptions, 'prefix'>;
18
+ }
19
+ export interface RedisStores {
20
+ rateLimit: RedisRateLimitStore;
21
+ idempotency: RedisIdempotencyStore;
22
+ cronLock: RedisCronLock;
23
+ cache: RedisCacheStore;
24
+ }
25
+ /**
26
+ * All four stores on one client, with one key prefix (default `exis:`).
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import Redis from 'ioredis'
31
+ * import { redisStores } from '@exisjs/redis'
32
+ *
33
+ * export const stores = redisStores(new Redis(process.env.REDIS_URL!))
34
+ *
35
+ * app.use(rateLimit({ max: 100, store: stores.rateLimit }))
36
+ * app.cron.lock = stores.cronLock
37
+ * // exis.config.ts: cache: { store: stores.cache }
38
+ * // routes: idempotent({ store: stores.idempotency })
39
+ * ```
40
+ */
41
+ export declare function redisStores(client: RedisClientLike, options?: RedisStoresOptions): RedisStores;
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACvB,MAAM,UAAU,CAAA;AACjB,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAA;AAClD,OAAO,EACL,qBAAqB,EACrB,KAAK,4BAA4B,EAClC,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,aAAa,CAAA;AACtE,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAEtE,OAAO,EACL,cAAc,EACd,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,iBAAiB,GACvB,MAAM,UAAU,CAAA;AACjB,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAA;AAClD,OAAO,EACL,qBAAqB,EACrB,KAAK,4BAA4B,GAClC,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,aAAa,CAAA;AACtE,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAEtE,MAAM,WAAW,kBAAmB,SAAQ,iBAAiB;IAC3D,yEAAyE;IACzE,WAAW,CAAC,EAAE,IAAI,CAAC,4BAA4B,EAAE,QAAQ,CAAC,CAAA;IAC1D,iEAAiE;IACjE,QAAQ,CAAC,EAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAC,CAAA;IAC/C,mEAAmE;IACnE,KAAK,CAAC,EAAE,IAAI,CAAC,sBAAsB,EAAE,QAAQ,CAAC,CAAA;CAC/C;AAED,MAAM,WAAW,WAAW;IAC1B,SAAS,EAAE,mBAAmB,CAAA;IAC9B,WAAW,EAAE,qBAAqB,CAAA;IAClC,QAAQ,EAAE,aAAa,CAAA;IACvB,KAAK,EAAE,eAAe,CAAA;CACvB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,eAAe,EACvB,OAAO,GAAE,kBAAuB,GAC/B,WAAW,CAWb"}
package/dist/index.js ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedisCacheStore = exports.RedisCronLock = exports.RedisIdempotencyStore = exports.RedisRateLimitStore = exports.DEFAULT_PREFIX = void 0;
4
+ exports.redisStores = redisStores;
5
+ const client_1 = require("./client");
6
+ const rate_limit_1 = require("./rate-limit");
7
+ const idempotency_1 = require("./idempotency");
8
+ const cron_lock_1 = require("./cron-lock");
9
+ const cache_1 = require("./cache");
10
+ var client_2 = require("./client");
11
+ Object.defineProperty(exports, "DEFAULT_PREFIX", { enumerable: true, get: function () { return client_2.DEFAULT_PREFIX; } });
12
+ var rate_limit_2 = require("./rate-limit");
13
+ Object.defineProperty(exports, "RedisRateLimitStore", { enumerable: true, get: function () { return rate_limit_2.RedisRateLimitStore; } });
14
+ var idempotency_2 = require("./idempotency");
15
+ Object.defineProperty(exports, "RedisIdempotencyStore", { enumerable: true, get: function () { return idempotency_2.RedisIdempotencyStore; } });
16
+ var cron_lock_2 = require("./cron-lock");
17
+ Object.defineProperty(exports, "RedisCronLock", { enumerable: true, get: function () { return cron_lock_2.RedisCronLock; } });
18
+ var cache_2 = require("./cache");
19
+ Object.defineProperty(exports, "RedisCacheStore", { enumerable: true, get: function () { return cache_2.RedisCacheStore; } });
20
+ /**
21
+ * All four stores on one client, with one key prefix (default `exis:`).
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import Redis from 'ioredis'
26
+ * import { redisStores } from '@exisjs/redis'
27
+ *
28
+ * export const stores = redisStores(new Redis(process.env.REDIS_URL!))
29
+ *
30
+ * app.use(rateLimit({ max: 100, store: stores.rateLimit }))
31
+ * app.cron.lock = stores.cronLock
32
+ * // exis.config.ts: cache: { store: stores.cache }
33
+ * // routes: idempotent({ store: stores.idempotency })
34
+ * ```
35
+ */
36
+ function redisStores(client, options = {}) {
37
+ const prefix = options.prefix ?? client_1.DEFAULT_PREFIX;
38
+ return {
39
+ rateLimit: new rate_limit_1.RedisRateLimitStore(client, { prefix }),
40
+ idempotency: new idempotency_1.RedisIdempotencyStore(client, {
41
+ ...options.idempotency,
42
+ prefix,
43
+ }),
44
+ cronLock: new cron_lock_1.RedisCronLock(client, { ...options.cronLock, prefix }),
45
+ cache: new cache_1.RedisCacheStore(client, { ...options.cache, prefix }),
46
+ };
47
+ }
48
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AA2DA,kCAcC;AAzED,qCAIiB;AACjB,6CAAkD;AAClD,+CAGsB;AACtB,2CAAsE;AACtE,mCAAsE;AAEtE,mCAKiB;AAJf,wGAAA,cAAc,OAAA;AAKhB,2CAAkD;AAAzC,iHAAA,mBAAmB,OAAA;AAC5B,6CAGsB;AAFpB,oHAAA,qBAAqB,OAAA;AAGvB,yCAAsE;AAA7D,0GAAA,aAAa,OAAA;AACtB,iCAAsE;AAA7D,wGAAA,eAAe,OAAA;AAkBxB;;;;;;;;;;;;;;;GAeG;AACH,SAAgB,WAAW,CACzB,MAAuB,EACvB,UAA8B,EAAE;IAEhC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,uBAAc,CAAA;IAC/C,OAAO;QACL,SAAS,EAAE,IAAI,gCAAmB,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC;QACtD,WAAW,EAAE,IAAI,mCAAqB,CAAC,MAAM,EAAE;YAC7C,GAAG,OAAO,CAAC,WAAW;YACtB,MAAM;SACP,CAAC;QACF,QAAQ,EAAE,IAAI,yBAAa,CAAC,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,CAAC;QACpE,KAAK,EAAE,IAAI,uBAAe,CAAC,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;KACjE,CAAA;AACH,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { RateLimitHit, RateLimitStore } from 'exisjs/middleware';
2
+ import { type RedisClientLike, type RedisStoreOptions } from './client';
3
+ /**
4
+ * Counts rate-limit hits in Redis, so every instance enforces one limit.
5
+ * Fixed windows: the first hit starts a window of `windowMs`, and the count
6
+ * resets when it ends. Each hit is one atomic script (INCR, then PEXPIRE on
7
+ * a new key).
8
+ *
9
+ * Keys: `<prefix>rl:<key>`
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * app.use(rateLimit({ max: 100, windowMs: 60_000, store: new RedisRateLimitStore(redis) }))
14
+ * ```
15
+ */
16
+ export declare class RedisRateLimitStore implements RateLimitStore {
17
+ private readonly client;
18
+ private readonly prefix;
19
+ constructor(client: RedisClientLike, options?: RedisStoreOptions);
20
+ increment(key: string, windowMs: number): Promise<RateLimitHit>;
21
+ get(key: string): Promise<RateLimitHit | undefined>;
22
+ reset(key: string): Promise<void>;
23
+ }
24
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AACrE,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACvB,MAAM,UAAU,CAAA;AAGjB;;;;;;;;;;;;GAYG;AACH,qBAAa,mBAAoB,YAAW,cAAc;IAItD,OAAO,CAAC,QAAQ,CAAC,MAAM;IAHzB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;gBAGZ,MAAM,EAAE,eAAe,EACxC,OAAO,GAAE,iBAAsB;IAK3B,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAW/D,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC;IAYnD,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAGxC"}
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedisRateLimitStore = void 0;
4
+ const client_1 = require("./client");
5
+ const scripts_1 = require("./scripts");
6
+ /**
7
+ * Counts rate-limit hits in Redis, so every instance enforces one limit.
8
+ * Fixed windows: the first hit starts a window of `windowMs`, and the count
9
+ * resets when it ends. Each hit is one atomic script (INCR, then PEXPIRE on
10
+ * a new key).
11
+ *
12
+ * Keys: `<prefix>rl:<key>`
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * app.use(rateLimit({ max: 100, windowMs: 60_000, store: new RedisRateLimitStore(redis) }))
17
+ * ```
18
+ */
19
+ class RedisRateLimitStore {
20
+ constructor(client, options = {}) {
21
+ this.client = client;
22
+ this.prefix = `${options.prefix ?? client_1.DEFAULT_PREFIX}rl:`;
23
+ }
24
+ async increment(key, windowMs) {
25
+ const window = Math.max(1, Math.ceil(windowMs));
26
+ const reply = (await (0, client_1.runScript)(this.client, scripts_1.INCREMENT_SCRIPT, [this.prefix + key], [window]));
27
+ return toHit(reply);
28
+ }
29
+ async get(key) {
30
+ const reply = (await (0, client_1.runScript)(this.client, scripts_1.PEEK_SCRIPT, [this.prefix + key], []));
31
+ // No key, or one without a window (never written by increment)
32
+ if (!reply || Number(reply[1]) <= 0)
33
+ return undefined;
34
+ return toHit(reply);
35
+ }
36
+ async reset(key) {
37
+ await this.client.del(this.prefix + key);
38
+ }
39
+ }
40
+ exports.RedisRateLimitStore = RedisRateLimitStore;
41
+ function toHit(reply) {
42
+ const ttl = Math.max(0, Number(reply[1]));
43
+ return { count: Number(reply[0]), resetTime: Date.now() + ttl };
44
+ }
45
+ //# sourceMappingURL=rate-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.js","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":";;;AACA,qCAKiB;AACjB,uCAAyD;AAEzD;;;;;;;;;;;;GAYG;AACH,MAAa,mBAAmB;IAG9B,YACmB,MAAuB,EACxC,UAA6B,EAAE;QADd,WAAM,GAAN,MAAM,CAAiB;QAGxC,IAAI,CAAC,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,IAAI,uBAAc,KAAK,CAAA;IACxD,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,QAAgB;QAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAA;QAC/C,MAAM,KAAK,GAAG,CAAC,MAAM,IAAA,kBAAS,EAC5B,IAAI,CAAC,MAAM,EACX,0BAAgB,EAChB,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,EACnB,CAAC,MAAM,CAAC,CACT,CAAuC,CAAA;QACxC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAA;IACrB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW;QACnB,MAAM,KAAK,GAAG,CAAC,MAAM,IAAA,kBAAS,EAC5B,IAAI,CAAC,MAAM,EACX,qBAAW,EACX,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,EACnB,EAAE,CACH,CAA8C,CAAA;QAC/C,+DAA+D;QAC/D,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;YAAE,OAAO,SAAS,CAAA;QACrD,OAAO,KAAK,CAAC,KAAK,CAAC,CAAA;IACrB,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,GAAW;QACrB,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;IAC1C,CAAC;CACF;AApCD,kDAoCC;AAED,SAAS,KAAK,CAAC,KAAyC;IACtD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACzC,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,EAAE,CAAA;AACjE,CAAC"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Counts one hit in a fixed window.
3
+ * KEYS[1] counter, ARGV[1] window in ms. Returns { count, ms left in window }.
4
+ */
5
+ export declare const INCREMENT_SCRIPT = "local count = redis.call('INCR', KEYS[1])\nlocal ttl = redis.call('PTTL', KEYS[1])\nif ttl < 0 then\n redis.call('PEXPIRE', KEYS[1], ARGV[1])\n ttl = tonumber(ARGV[1])\nend\nreturn { count, ttl }";
6
+ /**
7
+ * Reads a counter without counting.
8
+ * KEYS[1] counter. Returns { count, ms left in window }, or nil when absent.
9
+ */
10
+ export declare const PEEK_SCRIPT = "local count = redis.call('GET', KEYS[1])\nif not count then return nil end\nreturn { tonumber(count), redis.call('PTTL', KEYS[1]) }";
11
+ /**
12
+ * Deletes a lock only if this owner still holds it.
13
+ * KEYS[1] lock, ARGV[1] owner token. Returns 1 when deleted.
14
+ */
15
+ export declare const RELEASE_SCRIPT = "if redis.call('GET', KEYS[1]) == ARGV[1] then\n return redis.call('DEL', KEYS[1])\nend\nreturn 0";
16
+ /**
17
+ * Shortens a lock this owner holds to ARGV[2] ms instead of deleting it.
18
+ * KEYS[1] lock, ARGV[1] owner token, ARGV[2] ms to keep it. Returns 1 when set.
19
+ */
20
+ export declare const HOLD_SCRIPT = "if redis.call('GET', KEYS[1]) == ARGV[1] then\n local ttl = redis.call('PTTL', KEYS[1])\n if ttl < 0 or ttl > tonumber(ARGV[2]) then\n redis.call('PEXPIRE', KEYS[1], ARGV[2])\n end\n return 1\nend\nreturn 0";
21
+ //# sourceMappingURL=scripts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scripts.d.ts","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,eAAO,MAAM,gBAAgB,0MAMP,CAAA;AAEtB;;;GAGG;AACH,eAAO,MAAM,WAAW,wIAEgC,CAAA;AAExD;;;GAGG;AACH,eAAO,MAAM,cAAc,sGAGlB,CAAA;AAET;;;GAGG;AACH,eAAO,MAAM,WAAW,0NAOf,CAAA"}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ // Lua scripts the stores run. Each runs atomically inside Redis, so no other
3
+ // command can slip in between its steps, even from another instance.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.HOLD_SCRIPT = exports.RELEASE_SCRIPT = exports.PEEK_SCRIPT = exports.INCREMENT_SCRIPT = void 0;
6
+ /**
7
+ * Counts one hit in a fixed window.
8
+ * KEYS[1] counter, ARGV[1] window in ms. Returns { count, ms left in window }.
9
+ */
10
+ exports.INCREMENT_SCRIPT = `local count = redis.call('INCR', KEYS[1])
11
+ local ttl = redis.call('PTTL', KEYS[1])
12
+ if ttl < 0 then
13
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
14
+ ttl = tonumber(ARGV[1])
15
+ end
16
+ return { count, ttl }`;
17
+ /**
18
+ * Reads a counter without counting.
19
+ * KEYS[1] counter. Returns { count, ms left in window }, or nil when absent.
20
+ */
21
+ exports.PEEK_SCRIPT = `local count = redis.call('GET', KEYS[1])
22
+ if not count then return nil end
23
+ return { tonumber(count), redis.call('PTTL', KEYS[1]) }`;
24
+ /**
25
+ * Deletes a lock only if this owner still holds it.
26
+ * KEYS[1] lock, ARGV[1] owner token. Returns 1 when deleted.
27
+ */
28
+ exports.RELEASE_SCRIPT = `if redis.call('GET', KEYS[1]) == ARGV[1] then
29
+ return redis.call('DEL', KEYS[1])
30
+ end
31
+ return 0`;
32
+ /**
33
+ * Shortens a lock this owner holds to ARGV[2] ms instead of deleting it.
34
+ * KEYS[1] lock, ARGV[1] owner token, ARGV[2] ms to keep it. Returns 1 when set.
35
+ */
36
+ exports.HOLD_SCRIPT = `if redis.call('GET', KEYS[1]) == ARGV[1] then
37
+ local ttl = redis.call('PTTL', KEYS[1])
38
+ if ttl < 0 or ttl > tonumber(ARGV[2]) then
39
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
40
+ end
41
+ return 1
42
+ end
43
+ return 0`;
44
+ //# sourceMappingURL=scripts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scripts.js","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":";AAAA,6EAA6E;AAC7E,qEAAqE;;;AAErE;;;GAGG;AACU,QAAA,gBAAgB,GAAG;;;;;;sBAMV,CAAA;AAEtB;;;GAGG;AACU,QAAA,WAAW,GAAG;;wDAE6B,CAAA;AAExD;;;GAGG;AACU,QAAA,cAAc,GAAG;;;SAGrB,CAAA;AAET;;;GAGG;AACU,QAAA,WAAW,GAAG;;;;;;;SAOlB,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@exisjs/redis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.11.0",
4
+ "description": "Redis stores for ExisJS: shared rate limits, idempotency keys, cron locks and @Cacheable results across instances",
5
+ "keywords": [
6
+ "exisjs",
7
+ "exis",
8
+ "redis",
9
+ "ioredis",
10
+ "rate-limit",
11
+ "idempotency",
12
+ "cron",
13
+ "cache",
14
+ "distributed-lock"
15
+ ],
16
+ "homepage": "https://github.com/v25group/exisjs/tree/main/packages/redis#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/v25group/exisjs/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/v25group/exisjs.git",
23
+ "directory": "packages/redis"
24
+ },
25
+ "license": "MIT",
26
+ "author": "V25 Group <support@v25group.com>",
27
+ "main": "dist/index.js",
28
+ "types": "dist/index.d.ts",
29
+ "type": "commonjs",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "engines": {
41
+ "node": ">=24.0.0"
42
+ },
43
+ "scripts": {
44
+ "prebuild": "node -e \"require('fs').rmSync('dist', {recursive:true, force:true}); require('fs').rmSync('tsconfig.tsbuildinfo', {force:true})\"",
45
+ "build": "tsc",
46
+ "dev": "tsc --watch",
47
+ "prepublishOnly": "npm run build"
48
+ },
49
+ "peerDependencies": {
50
+ "exisjs": "~0.11.0",
51
+ "ioredis": "^5.0.0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "ioredis": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "devDependencies": {
59
+ "@types/node": "^24.19.2",
60
+ "ioredis": "^5.6.1"
61
+ },
62
+ "publishConfig": {
63
+ "access": "public"
64
+ }
65
+ }