@leoribeiroweb/nest-redis 0.1.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 +131 -0
- package/dist/connection/close-redis.d.ts +28 -0
- package/dist/connection/close-redis.js +51 -0
- package/dist/connection/redis-client.d.ts +44 -0
- package/dist/connection/redis-client.js +69 -0
- package/dist/connection/redis-connection.d.ts +50 -0
- package/dist/connection/redis-connection.js +78 -0
- package/dist/connection/redis.module.d.ts +38 -0
- package/dist/connection/redis.module.js +104 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +32 -0
- package/dist/lock/distributed-lock.d.ts +74 -0
- package/dist/lock/distributed-lock.js +99 -0
- package/dist/rate-limit/token-bucket.d.ts +28 -0
- package/dist/rate-limit/token-bucket.js +77 -0
- package/dist/scripting/redis-script.d.ts +29 -0
- package/dist/scripting/redis-script.js +38 -0
- package/package.json +50 -0
package/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# @leoribeiroweb/nest-redis
|
|
2
|
+
|
|
3
|
+
One Redis connection for a NestJS service, plus the two coordination
|
|
4
|
+
primitives that keep getting rewritten around it: an atomic token bucket and a
|
|
5
|
+
distributed lock.
|
|
6
|
+
|
|
7
|
+
This package is part of the shared framework behind my own services. It is
|
|
8
|
+
published publicly so builds need no registry credentials, but it is **not an
|
|
9
|
+
open-source project**: there is no support commitment, and the API changes to
|
|
10
|
+
suit the services that consume it. Pin a major version.
|
|
11
|
+
|
|
12
|
+
## The connection
|
|
13
|
+
|
|
14
|
+
Two configuration modes, because both exist and each is the only one exercised
|
|
15
|
+
somewhere:
|
|
16
|
+
|
|
17
|
+
| Mode | Variables | Where it runs |
|
|
18
|
+
| --- | --- | --- |
|
|
19
|
+
| URL | `REDIS_URL` | local development, docker-compose |
|
|
20
|
+
| Discrete | `REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD` | the k3s cluster, where the password is a declarative secret reference rather than a substring of a URL |
|
|
21
|
+
|
|
22
|
+
`REDIS_URL` wins when both are set. `REDIS_PORT` defaults to `6379` and is
|
|
23
|
+
**validated**: a non-numeric or out-of-range value throws `RedisConfigError`
|
|
24
|
+
instead of reaching ioredis as `NaN`. The throw happens when Nest instantiates
|
|
25
|
+
the module, not when the file is imported, so it arrives inside the bootstrap
|
|
26
|
+
with a stack that points at it.
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { RedisModule, REDIS_CLIENT } from '@leoribeiroweb/nest-redis';
|
|
30
|
+
|
|
31
|
+
@Module({
|
|
32
|
+
imports: [
|
|
33
|
+
RedisModule.forRootAsync({
|
|
34
|
+
imports: [ConfigModule],
|
|
35
|
+
inject: [ConfigService],
|
|
36
|
+
useFactory: (config: ConfigService) => ({ source: config }),
|
|
37
|
+
}),
|
|
38
|
+
],
|
|
39
|
+
})
|
|
40
|
+
export class AppModule {}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`REDIS_CLIENT` resolves to `Redis | null`. **`null` is a supported answer**, not
|
|
44
|
+
a failure: it is how a single-instance process — local development, the test
|
|
45
|
+
suite, a service deployed without Redis — tells a caller to fall back to an
|
|
46
|
+
in-memory Map or disable a feature. A *misconfigured* Redis is a different
|
|
47
|
+
thing and throws.
|
|
48
|
+
|
|
49
|
+
`RedisModule` closes the client in `onApplicationShutdown` with a deadline, so
|
|
50
|
+
a connection that will not close politely is disconnected rather than left
|
|
51
|
+
holding the shutdown sequence open.
|
|
52
|
+
|
|
53
|
+
For a client outside the DI graph, `createRedisClient(source, overrides)` and
|
|
54
|
+
`resolveRedisConnection(source)` do the same work as plain functions.
|
|
55
|
+
|
|
56
|
+
### Connection defaults
|
|
57
|
+
|
|
58
|
+
`maxRetriesPerRequest: 1` and `enableOfflineQueue: false` make a command fail
|
|
59
|
+
promptly during an outage, so callers reject and degrade instead of piling up
|
|
60
|
+
work that lands minutes late. `retryStrategy` reconnects **indefinitely** with
|
|
61
|
+
capped backoff: returning `null` would make ioredis end the client
|
|
62
|
+
permanently, and a transient Redis restart would then break the feature until
|
|
63
|
+
the pod restarts.
|
|
64
|
+
|
|
65
|
+
## Token bucket
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
const { allowed, remaining, resetInSeconds } = await consumeTokenBucket(redis, {
|
|
69
|
+
key: `rl:apikey:${apiKeyId}`,
|
|
70
|
+
capacity: 60,
|
|
71
|
+
windowSeconds: 60,
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`INCR` + `EXPIRE` + `TTL` run as a single Lua script. A pipeline is not atomic
|
|
76
|
+
across replicas or against other concurrent clients, so three round trips leave
|
|
77
|
+
a window where two callers both read `count == capacity` and both pass the cap.
|
|
78
|
+
`EXPIRE` runs only on the first increment, which anchors the window to the
|
|
79
|
+
first request — re-expiring on every call would slide the window forward and a
|
|
80
|
+
bucket under sustained traffic would never reset.
|
|
81
|
+
|
|
82
|
+
`capacity` and `windowSeconds` must be integers of at least 1, or the call
|
|
83
|
+
throws `TokenBucketConfigError`. `EXPIRE key 0` deletes the key, so a zero
|
|
84
|
+
window would make every request see a fresh counter and pass — a limiter that
|
|
85
|
+
silently does not limit. A counter that somehow lost its TTL is re-anchored
|
|
86
|
+
rather than left to climb forever.
|
|
87
|
+
|
|
88
|
+
A Redis error propagates. A rate limiter that silently allows everything on
|
|
89
|
+
error stops existing exactly when it is needed.
|
|
90
|
+
|
|
91
|
+
## Distributed lock
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
const lock = new DistributedLock(redis, { keyPrefix: 'cache-lock' });
|
|
95
|
+
|
|
96
|
+
const outcome = await lock.withLock('participants:refresh', () => refresh(groupJid));
|
|
97
|
+
if (!outcome.acquired) return; // another replica is already on it
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`SET NX PX` to take it; a Lua compare-and-delete to release it, so a lease that
|
|
101
|
+
lapsed and was taken by another replica is never deleted by its previous
|
|
102
|
+
holder. `extend(ttlMs)` pushes the lease out under the same ownership check.
|
|
103
|
+
`acquire` returns `null` immediately unless given a `retryTimeoutMs` budget.
|
|
104
|
+
|
|
105
|
+
A throw from the work inside `withLock` propagates after the lock is released.
|
|
106
|
+
Turning it into a result field is how a failing refresh becomes invisible. A
|
|
107
|
+
failure of the *release* is swallowed instead — it would otherwise replace a
|
|
108
|
+
completed result, or displace the error the work threw — and the lease expires
|
|
109
|
+
on its TTL. Pass `onReleaseFailure` to have it logged. A caller that releases a
|
|
110
|
+
handle by hand still sees the rejection.
|
|
111
|
+
|
|
112
|
+
There is deliberately **no in-memory fallback** when Redis is absent. A local
|
|
113
|
+
lock answers "acquired" on every replica at once — the exact opposite of what
|
|
114
|
+
the caller asked for — and does so silently. Construct the lock only when
|
|
115
|
+
`createRedisClient` returned a client, and take the un-coordinated path
|
|
116
|
+
otherwise.
|
|
117
|
+
|
|
118
|
+
## Requirements
|
|
119
|
+
|
|
120
|
+
Node `>=20.11.0`. Peer dependencies: `@nestjs/common` ^11, `ioredis` `^5 || ^6`,
|
|
121
|
+
`reflect-metadata` ^0.2.
|
|
122
|
+
|
|
123
|
+
Both ioredis majors are exercised in CI: the lockfile installs 6, which the
|
|
124
|
+
live services run, and a separate job installs the floor of the range and
|
|
125
|
+
re-runs the suite.
|
|
126
|
+
|
|
127
|
+
## Not in this package
|
|
128
|
+
|
|
129
|
+
The idempotency decorator, interceptor and store are **deferred**, not
|
|
130
|
+
forgotten — see `docs/decisions/2026-09-18-a4-redis-and-queue.md` in the
|
|
131
|
+
repository.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** The teardown surface of an ioredis client. */
|
|
2
|
+
export interface ClosableRedis {
|
|
3
|
+
readonly status: string;
|
|
4
|
+
quit(): Promise<unknown>;
|
|
5
|
+
disconnect(): void;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* How long a `quit()` may hold the shutdown sequence.
|
|
9
|
+
*
|
|
10
|
+
* Closing a connection has nothing legitimate to wait for — it is not draining
|
|
11
|
+
* work — so this is short. It matches `SHUTDOWN_STEP_TIMEOUT_MS` in
|
|
12
|
+
* `@leoribeiroweb/nest-core`'s shutdown budget, which is where a consumer's
|
|
13
|
+
* arithmetic lives. The value is duplicated rather than imported so that
|
|
14
|
+
* `nest-redis` stays installable without `nest-core`; a consumer that runs the
|
|
15
|
+
* derived budget should pass its own value here.
|
|
16
|
+
*/
|
|
17
|
+
export declare const REDIS_CLOSE_TIMEOUT_MS = 2000;
|
|
18
|
+
export type RedisCloseOutcome = 'closed' | 'abandoned';
|
|
19
|
+
/**
|
|
20
|
+
* Close a client without letting it hold the process open.
|
|
21
|
+
*
|
|
22
|
+
* Nothing here rejects: shutdown steps run in a sequence that must finish, and
|
|
23
|
+
* a connection that refuses to close politely is disconnected instead. On
|
|
24
|
+
* timeout the wait is **abandoned** rather than cancelled — ioredis exposes no
|
|
25
|
+
* way to cancel an in-flight `quit` — and the socket is torn down so nothing
|
|
26
|
+
* keeps the event loop alive.
|
|
27
|
+
*/
|
|
28
|
+
export declare function closeRedis(client: ClosableRedis | null | undefined, timeoutMs?: number): Promise<RedisCloseOutcome>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.REDIS_CLOSE_TIMEOUT_MS = void 0;
|
|
4
|
+
exports.closeRedis = closeRedis;
|
|
5
|
+
/**
|
|
6
|
+
* How long a `quit()` may hold the shutdown sequence.
|
|
7
|
+
*
|
|
8
|
+
* Closing a connection has nothing legitimate to wait for — it is not draining
|
|
9
|
+
* work — so this is short. It matches `SHUTDOWN_STEP_TIMEOUT_MS` in
|
|
10
|
+
* `@leoribeiroweb/nest-core`'s shutdown budget, which is where a consumer's
|
|
11
|
+
* arithmetic lives. The value is duplicated rather than imported so that
|
|
12
|
+
* `nest-redis` stays installable without `nest-core`; a consumer that runs the
|
|
13
|
+
* derived budget should pass its own value here.
|
|
14
|
+
*/
|
|
15
|
+
exports.REDIS_CLOSE_TIMEOUT_MS = 2_000;
|
|
16
|
+
/**
|
|
17
|
+
* Close a client without letting it hold the process open.
|
|
18
|
+
*
|
|
19
|
+
* Nothing here rejects: shutdown steps run in a sequence that must finish, and
|
|
20
|
+
* a connection that refuses to close politely is disconnected instead. On
|
|
21
|
+
* timeout the wait is **abandoned** rather than cancelled — ioredis exposes no
|
|
22
|
+
* way to cancel an in-flight `quit` — and the socket is torn down so nothing
|
|
23
|
+
* keeps the event loop alive.
|
|
24
|
+
*/
|
|
25
|
+
async function closeRedis(client, timeoutMs = exports.REDIS_CLOSE_TIMEOUT_MS) {
|
|
26
|
+
if (!client || client.status === 'end')
|
|
27
|
+
return 'closed';
|
|
28
|
+
let timer;
|
|
29
|
+
const deadline = new Promise((resolve) => {
|
|
30
|
+
timer = setTimeout(() => resolve('abandoned'), timeoutMs);
|
|
31
|
+
timer.unref?.();
|
|
32
|
+
});
|
|
33
|
+
// A `quit()` that rejects has still *settled* — 'Connection is closed.' is
|
|
34
|
+
// the usual reason, and the connection is indeed gone. Only a quit that
|
|
35
|
+
// outlives the deadline is abandoned. Either way the socket is torn down
|
|
36
|
+
// below if it is somehow still open.
|
|
37
|
+
let rejected = false;
|
|
38
|
+
const quitting = client
|
|
39
|
+
.quit()
|
|
40
|
+
.catch(() => {
|
|
41
|
+
rejected = true;
|
|
42
|
+
})
|
|
43
|
+
.then(() => 'closed');
|
|
44
|
+
const outcome = await Promise.race([quitting, deadline]);
|
|
45
|
+
if (timer !== undefined)
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
if ((outcome === 'abandoned' || rejected) && client.status !== 'end') {
|
|
48
|
+
client.disconnect();
|
|
49
|
+
}
|
|
50
|
+
return outcome;
|
|
51
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import Redis, { type RedisOptions } from 'ioredis';
|
|
2
|
+
import { type RedisConfigSource, type RedisConnectionSettings } from './redis-connection';
|
|
3
|
+
/**
|
|
4
|
+
* ioredis options, plus the `url` key BullMQ understands.
|
|
5
|
+
*
|
|
6
|
+
* ioredis itself takes a URL as its first constructor argument and has no
|
|
7
|
+
* `url` option, so an object carrying one has to be split before it reaches
|
|
8
|
+
* `new Redis(...)` — which is exactly what BullMQ's own `RedisConnection`
|
|
9
|
+
* does. Keeping the URL on the options object is what lets `nest-queue` hand
|
|
10
|
+
* the same resolved shape to BullMQ untouched.
|
|
11
|
+
*/
|
|
12
|
+
export type RedisConnectionOptions = RedisOptions & {
|
|
13
|
+
url?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Defaults every connection starts from.
|
|
17
|
+
*
|
|
18
|
+
* `maxRetriesPerRequest: 1` plus `enableOfflineQueue: false` make individual
|
|
19
|
+
* commands fail promptly during an outage, so callers reject and degrade
|
|
20
|
+
* instead of piling up a queue of work that will land minutes late.
|
|
21
|
+
*
|
|
22
|
+
* `retryStrategy` reconnects **indefinitely** with capped backoff. Returning
|
|
23
|
+
* `null` (as one of the three copies this replaces did) makes ioredis end the
|
|
24
|
+
* client permanently: a transient Redis restart would then break the feature
|
|
25
|
+
* until the pod restarts. The two behaviours are reconciled in
|
|
26
|
+
* `docs/decisions/2026-09-18-a4-redis-and-queue.md`.
|
|
27
|
+
*
|
|
28
|
+
* {@link redisRetryStrategy} is exported separately because ioredis types the
|
|
29
|
+
* *option* as `((times) => …) | null | undefined` while BullMQ accepts only the
|
|
30
|
+
* function; `nest-queue` needs the narrow type to stay assignable to BullMQ's
|
|
31
|
+
* `ConnectionOptions` without a cast.
|
|
32
|
+
*/
|
|
33
|
+
export declare const redisRetryStrategy: (times: number) => number;
|
|
34
|
+
export declare const REDIS_DEFAULT_OPTIONS: RedisOptions;
|
|
35
|
+
/** Turn resolved settings into the options object ioredis (or BullMQ) needs. */
|
|
36
|
+
export declare function buildRedisOptions(settings: RedisConnectionSettings, overrides?: RedisOptions): RedisConnectionOptions;
|
|
37
|
+
/**
|
|
38
|
+
* Build the process's Redis client, or `null` when Redis is not configured.
|
|
39
|
+
*
|
|
40
|
+
* Accepts either a configuration source to resolve or settings already
|
|
41
|
+
* resolved, so a caller that needs to branch on the mode does not have to
|
|
42
|
+
* resolve twice.
|
|
43
|
+
*/
|
|
44
|
+
export declare function createRedisClient(source: RedisConfigSource | RedisConnectionSettings | null, overrides?: RedisOptions): Redis | null;
|
|
@@ -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.REDIS_DEFAULT_OPTIONS = exports.redisRetryStrategy = void 0;
|
|
7
|
+
exports.buildRedisOptions = buildRedisOptions;
|
|
8
|
+
exports.createRedisClient = createRedisClient;
|
|
9
|
+
const ioredis_1 = __importDefault(require("ioredis"));
|
|
10
|
+
const redis_connection_1 = require("./redis-connection");
|
|
11
|
+
/**
|
|
12
|
+
* Defaults every connection starts from.
|
|
13
|
+
*
|
|
14
|
+
* `maxRetriesPerRequest: 1` plus `enableOfflineQueue: false` make individual
|
|
15
|
+
* commands fail promptly during an outage, so callers reject and degrade
|
|
16
|
+
* instead of piling up a queue of work that will land minutes late.
|
|
17
|
+
*
|
|
18
|
+
* `retryStrategy` reconnects **indefinitely** with capped backoff. Returning
|
|
19
|
+
* `null` (as one of the three copies this replaces did) makes ioredis end the
|
|
20
|
+
* client permanently: a transient Redis restart would then break the feature
|
|
21
|
+
* until the pod restarts. The two behaviours are reconciled in
|
|
22
|
+
* `docs/decisions/2026-09-18-a4-redis-and-queue.md`.
|
|
23
|
+
*
|
|
24
|
+
* {@link redisRetryStrategy} is exported separately because ioredis types the
|
|
25
|
+
* *option* as `((times) => …) | null | undefined` while BullMQ accepts only the
|
|
26
|
+
* function; `nest-queue` needs the narrow type to stay assignable to BullMQ's
|
|
27
|
+
* `ConnectionOptions` without a cast.
|
|
28
|
+
*/
|
|
29
|
+
const redisRetryStrategy = (times) => Math.min(times * 200, 5000);
|
|
30
|
+
exports.redisRetryStrategy = redisRetryStrategy;
|
|
31
|
+
exports.REDIS_DEFAULT_OPTIONS = {
|
|
32
|
+
maxRetriesPerRequest: 1,
|
|
33
|
+
enableOfflineQueue: false,
|
|
34
|
+
retryStrategy: exports.redisRetryStrategy,
|
|
35
|
+
};
|
|
36
|
+
/** Turn resolved settings into the options object ioredis (or BullMQ) needs. */
|
|
37
|
+
function buildRedisOptions(settings, overrides = {}) {
|
|
38
|
+
const base = { ...exports.REDIS_DEFAULT_OPTIONS, ...overrides };
|
|
39
|
+
return settings.mode === 'url'
|
|
40
|
+
? { ...base, url: settings.url }
|
|
41
|
+
: {
|
|
42
|
+
...base,
|
|
43
|
+
host: settings.host,
|
|
44
|
+
port: settings.port,
|
|
45
|
+
password: settings.password,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Build the process's Redis client, or `null` when Redis is not configured.
|
|
50
|
+
*
|
|
51
|
+
* Accepts either a configuration source to resolve or settings already
|
|
52
|
+
* resolved, so a caller that needs to branch on the mode does not have to
|
|
53
|
+
* resolve twice.
|
|
54
|
+
*/
|
|
55
|
+
function createRedisClient(source, overrides = {}) {
|
|
56
|
+
const settings = toSettings(source);
|
|
57
|
+
if (settings === null)
|
|
58
|
+
return null;
|
|
59
|
+
const { url, ...options } = buildRedisOptions(settings, overrides);
|
|
60
|
+
return url !== undefined ? new ioredis_1.default(url, options) : new ioredis_1.default(options);
|
|
61
|
+
}
|
|
62
|
+
function toSettings(source) {
|
|
63
|
+
if (source === null)
|
|
64
|
+
return null;
|
|
65
|
+
const mode = source.mode;
|
|
66
|
+
if (mode === 'url' || mode === 'discrete')
|
|
67
|
+
return source;
|
|
68
|
+
return (0, redis_connection_1.resolveRedisConnection)(source);
|
|
69
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** The port Redis listens on when the deployment does not say otherwise. */
|
|
2
|
+
export declare const DEFAULT_REDIS_PORT = 6379;
|
|
3
|
+
/** Environment variables this resolver reads, in precedence order. */
|
|
4
|
+
export declare const REDIS_URL_KEY = "REDIS_URL";
|
|
5
|
+
export declare const REDIS_HOST_KEY = "REDIS_HOST";
|
|
6
|
+
export declare const REDIS_PORT_KEY = "REDIS_PORT";
|
|
7
|
+
export declare const REDIS_PASSWORD_KEY = "REDIS_PASSWORD";
|
|
8
|
+
/**
|
|
9
|
+
* Where the connection came from.
|
|
10
|
+
*
|
|
11
|
+
* Both modes exist in production and each is the only one exercised somewhere:
|
|
12
|
+
*
|
|
13
|
+
* - `url` — a single `REDIS_URL`. Local development and docker-compose.
|
|
14
|
+
* - `discrete` — `REDIS_HOST` + `REDIS_PORT` + `REDIS_PASSWORD`. The k3s
|
|
15
|
+
* cluster, where every sibling chart keeps the password as a declarative
|
|
16
|
+
* secret reference (`redis-auth`/`redis-password`) instead of embedding it
|
|
17
|
+
* inside a URL string.
|
|
18
|
+
*
|
|
19
|
+
* The mode is kept on the result rather than collapsed into ioredis options so
|
|
20
|
+
* callers (and tests) can assert which branch a given environment takes.
|
|
21
|
+
*/
|
|
22
|
+
export type RedisConnectionSettings = {
|
|
23
|
+
readonly mode: 'url';
|
|
24
|
+
readonly url: string;
|
|
25
|
+
} | {
|
|
26
|
+
readonly mode: 'discrete';
|
|
27
|
+
readonly host: string;
|
|
28
|
+
readonly port: number;
|
|
29
|
+
readonly password: string | undefined;
|
|
30
|
+
};
|
|
31
|
+
/** A `ConfigService`-shaped source, structurally typed so no config package is required. */
|
|
32
|
+
export interface RedisConfigGetter {
|
|
33
|
+
get(key: string): unknown;
|
|
34
|
+
}
|
|
35
|
+
/** Anything the resolver can read four keys out of: a config service, `process.env`, a literal. */
|
|
36
|
+
export type RedisConfigSource = RedisConfigGetter | Record<string, unknown>;
|
|
37
|
+
/** Thrown when Redis is configured, but configured wrongly. */
|
|
38
|
+
export declare class RedisConfigError extends Error {
|
|
39
|
+
constructor(message: string);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Resolve the one Redis connection this process should use, or `null` when
|
|
43
|
+
* Redis is not configured at all.
|
|
44
|
+
*
|
|
45
|
+
* `null` is a supported answer, not a failure: it is how a single-instance
|
|
46
|
+
* process (local development, the test suite) tells its caller to fall back to
|
|
47
|
+
* an in-memory Map or to disable the feature, instead of crashing at startup.
|
|
48
|
+
* A *misconfigured* Redis is a different thing and throws.
|
|
49
|
+
*/
|
|
50
|
+
export declare function resolveRedisConnection(source: RedisConfigSource): RedisConnectionSettings | null;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RedisConfigError = exports.REDIS_PASSWORD_KEY = exports.REDIS_PORT_KEY = exports.REDIS_HOST_KEY = exports.REDIS_URL_KEY = exports.DEFAULT_REDIS_PORT = void 0;
|
|
4
|
+
exports.resolveRedisConnection = resolveRedisConnection;
|
|
5
|
+
/** The port Redis listens on when the deployment does not say otherwise. */
|
|
6
|
+
exports.DEFAULT_REDIS_PORT = 6379;
|
|
7
|
+
/** Environment variables this resolver reads, in precedence order. */
|
|
8
|
+
exports.REDIS_URL_KEY = 'REDIS_URL';
|
|
9
|
+
exports.REDIS_HOST_KEY = 'REDIS_HOST';
|
|
10
|
+
exports.REDIS_PORT_KEY = 'REDIS_PORT';
|
|
11
|
+
exports.REDIS_PASSWORD_KEY = 'REDIS_PASSWORD';
|
|
12
|
+
/** Thrown when Redis is configured, but configured wrongly. */
|
|
13
|
+
class RedisConfigError extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'RedisConfigError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.RedisConfigError = RedisConfigError;
|
|
20
|
+
function hasGetter(source) {
|
|
21
|
+
return typeof source.get === 'function';
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Read one key as a string. A number is accepted and stringified because a
|
|
25
|
+
* validated config snapshot may already have coerced `REDIS_PORT`, and an
|
|
26
|
+
* empty string is reported as absent because every call site downstream tests
|
|
27
|
+
* these values for truthiness.
|
|
28
|
+
*/
|
|
29
|
+
function readKey(source, key) {
|
|
30
|
+
const raw = hasGetter(source) ? source.get(key) : source[key];
|
|
31
|
+
if (raw === undefined || raw === null)
|
|
32
|
+
return undefined;
|
|
33
|
+
const value = typeof raw === 'number' ? String(raw) : raw;
|
|
34
|
+
if (typeof value !== 'string' || value === '')
|
|
35
|
+
return undefined;
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Parse `REDIS_PORT`, refusing what `Number()` would otherwise wave through.
|
|
40
|
+
*
|
|
41
|
+
* All three services do `Number(get('REDIS_PORT') ?? '6379')` and pass the
|
|
42
|
+
* result straight to ioredis, so a typo becomes `NaN` and a blank value
|
|
43
|
+
* becomes `0` — a connection that fails at runtime, in the cluster, with an
|
|
44
|
+
* error that names neither the variable nor the value. This is the one place
|
|
45
|
+
* that knows what a port is, so this is where it is checked.
|
|
46
|
+
*/
|
|
47
|
+
function parsePort(raw) {
|
|
48
|
+
if (raw === undefined)
|
|
49
|
+
return exports.DEFAULT_REDIS_PORT;
|
|
50
|
+
const port = Number(raw);
|
|
51
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
52
|
+
throw new RedisConfigError(`${exports.REDIS_PORT_KEY} must be an integer between 1 and 65535, got ${JSON.stringify(raw)}`);
|
|
53
|
+
}
|
|
54
|
+
return port;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Resolve the one Redis connection this process should use, or `null` when
|
|
58
|
+
* Redis is not configured at all.
|
|
59
|
+
*
|
|
60
|
+
* `null` is a supported answer, not a failure: it is how a single-instance
|
|
61
|
+
* process (local development, the test suite) tells its caller to fall back to
|
|
62
|
+
* an in-memory Map or to disable the feature, instead of crashing at startup.
|
|
63
|
+
* A *misconfigured* Redis is a different thing and throws.
|
|
64
|
+
*/
|
|
65
|
+
function resolveRedisConnection(source) {
|
|
66
|
+
const url = readKey(source, exports.REDIS_URL_KEY);
|
|
67
|
+
if (url !== undefined)
|
|
68
|
+
return { mode: 'url', url };
|
|
69
|
+
const host = readKey(source, exports.REDIS_HOST_KEY);
|
|
70
|
+
if (host === undefined)
|
|
71
|
+
return null;
|
|
72
|
+
return {
|
|
73
|
+
mode: 'discrete',
|
|
74
|
+
host,
|
|
75
|
+
port: parsePort(readKey(source, exports.REDIS_PORT_KEY)),
|
|
76
|
+
password: readKey(source, exports.REDIS_PASSWORD_KEY),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type DynamicModule, type InjectionToken, type ModuleMetadata, type OnApplicationShutdown, type OptionalFactoryDependency } from '@nestjs/common';
|
|
2
|
+
import type Redis from 'ioredis';
|
|
3
|
+
import type { RedisOptions } from 'ioredis';
|
|
4
|
+
import type { RedisConfigSource } from './redis-connection';
|
|
5
|
+
/**
|
|
6
|
+
* The process's Redis client, or `null` when Redis is not configured.
|
|
7
|
+
*
|
|
8
|
+
* The token always resolves, so a consumer injects `Redis | null` and decides
|
|
9
|
+
* what "no Redis" means for its own feature — an in-memory Map, a disabled
|
|
10
|
+
* feature, a direct call. Nothing here decides that on its behalf.
|
|
11
|
+
*/
|
|
12
|
+
export declare const REDIS_CLIENT: unique symbol;
|
|
13
|
+
export interface RedisModuleOptions {
|
|
14
|
+
/** Where to read `REDIS_URL` / `REDIS_HOST` / `REDIS_PORT` / `REDIS_PASSWORD`. */
|
|
15
|
+
source: RedisConfigSource;
|
|
16
|
+
/** ioredis overrides on top of `REDIS_DEFAULT_OPTIONS`. */
|
|
17
|
+
options?: RedisOptions;
|
|
18
|
+
/** How long `quit()` may hold shutdown. Align with the consumer's budget. */
|
|
19
|
+
closeTimeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface RedisModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
|
|
22
|
+
inject?: (InjectionToken | OptionalFactoryDependency)[];
|
|
23
|
+
useFactory: (...args: never[]) => RedisModuleOptions | Promise<RedisModuleOptions>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Wires one Redis connection into the application and closes it on the way out.
|
|
27
|
+
*
|
|
28
|
+
* `@Global()` because a connection is process-wide infrastructure: making
|
|
29
|
+
* every feature module re-import it only spreads the same singleton around.
|
|
30
|
+
*/
|
|
31
|
+
export declare class RedisModule implements OnApplicationShutdown {
|
|
32
|
+
private readonly client;
|
|
33
|
+
private readonly closeTimeoutMs?;
|
|
34
|
+
constructor(client: Redis | null, closeTimeoutMs?: number | undefined);
|
|
35
|
+
static forRoot(options: RedisModuleOptions): DynamicModule;
|
|
36
|
+
static forRootAsync(asyncOptions: RedisModuleAsyncOptions): DynamicModule;
|
|
37
|
+
onApplicationShutdown(): Promise<void>;
|
|
38
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
var RedisModule_1;
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.RedisModule = exports.REDIS_CLIENT = void 0;
|
|
17
|
+
const common_1 = require("@nestjs/common");
|
|
18
|
+
const close_redis_1 = require("./close-redis");
|
|
19
|
+
const redis_client_1 = require("./redis-client");
|
|
20
|
+
/**
|
|
21
|
+
* The process's Redis client, or `null` when Redis is not configured.
|
|
22
|
+
*
|
|
23
|
+
* The token always resolves, so a consumer injects `Redis | null` and decides
|
|
24
|
+
* what "no Redis" means for its own feature — an in-memory Map, a disabled
|
|
25
|
+
* feature, a direct call. Nothing here decides that on its behalf.
|
|
26
|
+
*/
|
|
27
|
+
exports.REDIS_CLIENT = Symbol('nest-redis:client');
|
|
28
|
+
/** Internal token carrying the close deadline to the shutdown hook. */
|
|
29
|
+
const REDIS_CLOSE_TIMEOUT = Symbol('nest-redis:close-timeout');
|
|
30
|
+
/**
|
|
31
|
+
* Wires one Redis connection into the application and closes it on the way out.
|
|
32
|
+
*
|
|
33
|
+
* `@Global()` because a connection is process-wide infrastructure: making
|
|
34
|
+
* every feature module re-import it only spreads the same singleton around.
|
|
35
|
+
*/
|
|
36
|
+
let RedisModule = RedisModule_1 = class RedisModule {
|
|
37
|
+
constructor(client, closeTimeoutMs) {
|
|
38
|
+
this.client = client;
|
|
39
|
+
this.closeTimeoutMs = closeTimeoutMs;
|
|
40
|
+
}
|
|
41
|
+
static forRoot(options) {
|
|
42
|
+
return {
|
|
43
|
+
module: RedisModule_1,
|
|
44
|
+
providers: [
|
|
45
|
+
{
|
|
46
|
+
provide: exports.REDIS_CLIENT,
|
|
47
|
+
// A factory, never `useValue`. `forRoot(...)` is evaluated while the
|
|
48
|
+
// `@Module({ imports: [...] })` decorator argument is built — at
|
|
49
|
+
// import time, before `NestFactory.create()`, before config
|
|
50
|
+
// validation and before the logger exists. A client constructed
|
|
51
|
+
// there connects immediately; if the bootstrap then aborts,
|
|
52
|
+
// `onApplicationShutdown` never runs and the socket holds the event
|
|
53
|
+
// loop open. A bad `REDIS_PORT` would likewise throw with a stack
|
|
54
|
+
// that points at an import rather than at boot — the opposite of the
|
|
55
|
+
// named error `parsePort` exists to give. Same reasoning as row C4
|
|
56
|
+
// of the A1a decision record.
|
|
57
|
+
useFactory: () => (0, redis_client_1.createRedisClient)(options.source, options.options),
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
provide: REDIS_CLOSE_TIMEOUT,
|
|
61
|
+
useValue: options.closeTimeoutMs ?? close_redis_1.REDIS_CLOSE_TIMEOUT_MS,
|
|
62
|
+
},
|
|
63
|
+
],
|
|
64
|
+
exports: [exports.REDIS_CLIENT],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
static forRootAsync(asyncOptions) {
|
|
68
|
+
const RESOLVED = Symbol('nest-redis:resolved-options');
|
|
69
|
+
return {
|
|
70
|
+
module: RedisModule_1,
|
|
71
|
+
imports: asyncOptions.imports ?? [],
|
|
72
|
+
providers: [
|
|
73
|
+
{
|
|
74
|
+
provide: RESOLVED,
|
|
75
|
+
useFactory: asyncOptions.useFactory,
|
|
76
|
+
inject: asyncOptions.inject,
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
provide: exports.REDIS_CLIENT,
|
|
80
|
+
useFactory: (options) => (0, redis_client_1.createRedisClient)(options.source, options.options),
|
|
81
|
+
inject: [RESOLVED],
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
provide: REDIS_CLOSE_TIMEOUT,
|
|
85
|
+
useFactory: (options) => options.closeTimeoutMs ?? close_redis_1.REDIS_CLOSE_TIMEOUT_MS,
|
|
86
|
+
inject: [RESOLVED],
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
exports: [exports.REDIS_CLIENT],
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
async onApplicationShutdown() {
|
|
93
|
+
await (0, close_redis_1.closeRedis)(this.client, this.closeTimeoutMs);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
exports.RedisModule = RedisModule;
|
|
97
|
+
exports.RedisModule = RedisModule = RedisModule_1 = __decorate([
|
|
98
|
+
(0, common_1.Global)(),
|
|
99
|
+
(0, common_1.Module)({}),
|
|
100
|
+
__param(0, (0, common_1.Inject)(exports.REDIS_CLIENT)),
|
|
101
|
+
__param(1, (0, common_1.Optional)()),
|
|
102
|
+
__param(1, (0, common_1.Inject)(REDIS_CLOSE_TIMEOUT)),
|
|
103
|
+
__metadata("design:paramtypes", [Object, Number])
|
|
104
|
+
], RedisModule);
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { closeRedis, REDIS_CLOSE_TIMEOUT_MS, type ClosableRedis, type RedisCloseOutcome, } from './connection/close-redis';
|
|
2
|
+
export { buildRedisOptions, createRedisClient, REDIS_DEFAULT_OPTIONS, redisRetryStrategy, type RedisConnectionOptions, } from './connection/redis-client';
|
|
3
|
+
export { DEFAULT_REDIS_PORT, REDIS_HOST_KEY, REDIS_PASSWORD_KEY, REDIS_PORT_KEY, REDIS_URL_KEY, RedisConfigError, resolveRedisConnection, type RedisConfigGetter, type RedisConfigSource, type RedisConnectionSettings, } from './connection/redis-connection';
|
|
4
|
+
export { REDIS_CLIENT, RedisModule, type RedisModuleAsyncOptions, type RedisModuleOptions, } from './connection/redis.module';
|
|
5
|
+
export { DEFAULT_LOCK_KEY_PREFIX, DEFAULT_LOCK_RETRY_INTERVAL_MS, DEFAULT_LOCK_TTL_MS, DistributedLock, type AcquireLockOptions, type DistributedLockOptions, type LockHandle, type LockOutcome, type LockRedis, } from './lock/distributed-lock';
|
|
6
|
+
export { consumeTokenBucket, TokenBucketConfigError, type TokenBucketOptions, type TokenBucketResult, } from './rate-limit/token-bucket';
|
|
7
|
+
export { RedisScript, type ScriptableRedis } from './scripting/redis-script';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RedisScript = exports.TokenBucketConfigError = exports.consumeTokenBucket = exports.DistributedLock = exports.DEFAULT_LOCK_TTL_MS = exports.DEFAULT_LOCK_RETRY_INTERVAL_MS = exports.DEFAULT_LOCK_KEY_PREFIX = exports.RedisModule = exports.REDIS_CLIENT = exports.resolveRedisConnection = exports.RedisConfigError = exports.REDIS_URL_KEY = exports.REDIS_PORT_KEY = exports.REDIS_PASSWORD_KEY = exports.REDIS_HOST_KEY = exports.DEFAULT_REDIS_PORT = exports.redisRetryStrategy = exports.REDIS_DEFAULT_OPTIONS = exports.createRedisClient = exports.buildRedisOptions = exports.REDIS_CLOSE_TIMEOUT_MS = exports.closeRedis = void 0;
|
|
4
|
+
var close_redis_1 = require("./connection/close-redis");
|
|
5
|
+
Object.defineProperty(exports, "closeRedis", { enumerable: true, get: function () { return close_redis_1.closeRedis; } });
|
|
6
|
+
Object.defineProperty(exports, "REDIS_CLOSE_TIMEOUT_MS", { enumerable: true, get: function () { return close_redis_1.REDIS_CLOSE_TIMEOUT_MS; } });
|
|
7
|
+
var redis_client_1 = require("./connection/redis-client");
|
|
8
|
+
Object.defineProperty(exports, "buildRedisOptions", { enumerable: true, get: function () { return redis_client_1.buildRedisOptions; } });
|
|
9
|
+
Object.defineProperty(exports, "createRedisClient", { enumerable: true, get: function () { return redis_client_1.createRedisClient; } });
|
|
10
|
+
Object.defineProperty(exports, "REDIS_DEFAULT_OPTIONS", { enumerable: true, get: function () { return redis_client_1.REDIS_DEFAULT_OPTIONS; } });
|
|
11
|
+
Object.defineProperty(exports, "redisRetryStrategy", { enumerable: true, get: function () { return redis_client_1.redisRetryStrategy; } });
|
|
12
|
+
var redis_connection_1 = require("./connection/redis-connection");
|
|
13
|
+
Object.defineProperty(exports, "DEFAULT_REDIS_PORT", { enumerable: true, get: function () { return redis_connection_1.DEFAULT_REDIS_PORT; } });
|
|
14
|
+
Object.defineProperty(exports, "REDIS_HOST_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_HOST_KEY; } });
|
|
15
|
+
Object.defineProperty(exports, "REDIS_PASSWORD_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_PASSWORD_KEY; } });
|
|
16
|
+
Object.defineProperty(exports, "REDIS_PORT_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_PORT_KEY; } });
|
|
17
|
+
Object.defineProperty(exports, "REDIS_URL_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_URL_KEY; } });
|
|
18
|
+
Object.defineProperty(exports, "RedisConfigError", { enumerable: true, get: function () { return redis_connection_1.RedisConfigError; } });
|
|
19
|
+
Object.defineProperty(exports, "resolveRedisConnection", { enumerable: true, get: function () { return redis_connection_1.resolveRedisConnection; } });
|
|
20
|
+
var redis_module_1 = require("./connection/redis.module");
|
|
21
|
+
Object.defineProperty(exports, "REDIS_CLIENT", { enumerable: true, get: function () { return redis_module_1.REDIS_CLIENT; } });
|
|
22
|
+
Object.defineProperty(exports, "RedisModule", { enumerable: true, get: function () { return redis_module_1.RedisModule; } });
|
|
23
|
+
var distributed_lock_1 = require("./lock/distributed-lock");
|
|
24
|
+
Object.defineProperty(exports, "DEFAULT_LOCK_KEY_PREFIX", { enumerable: true, get: function () { return distributed_lock_1.DEFAULT_LOCK_KEY_PREFIX; } });
|
|
25
|
+
Object.defineProperty(exports, "DEFAULT_LOCK_RETRY_INTERVAL_MS", { enumerable: true, get: function () { return distributed_lock_1.DEFAULT_LOCK_RETRY_INTERVAL_MS; } });
|
|
26
|
+
Object.defineProperty(exports, "DEFAULT_LOCK_TTL_MS", { enumerable: true, get: function () { return distributed_lock_1.DEFAULT_LOCK_TTL_MS; } });
|
|
27
|
+
Object.defineProperty(exports, "DistributedLock", { enumerable: true, get: function () { return distributed_lock_1.DistributedLock; } });
|
|
28
|
+
var token_bucket_1 = require("./rate-limit/token-bucket");
|
|
29
|
+
Object.defineProperty(exports, "consumeTokenBucket", { enumerable: true, get: function () { return token_bucket_1.consumeTokenBucket; } });
|
|
30
|
+
Object.defineProperty(exports, "TokenBucketConfigError", { enumerable: true, get: function () { return token_bucket_1.TokenBucketConfigError; } });
|
|
31
|
+
var redis_script_1 = require("./scripting/redis-script");
|
|
32
|
+
Object.defineProperty(exports, "RedisScript", { enumerable: true, get: function () { return redis_script_1.RedisScript; } });
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type ScriptableRedis } from '../scripting/redis-script';
|
|
2
|
+
/** The commands a lock needs: `SET NX PX` plus the two ownership scripts. */
|
|
3
|
+
export interface LockRedis extends ScriptableRedis {
|
|
4
|
+
set(key: string, value: string, mode: 'PX', ttlMs: number, condition: 'NX'): Promise<'OK' | null>;
|
|
5
|
+
}
|
|
6
|
+
/** A lock this process currently holds. */
|
|
7
|
+
export interface LockHandle {
|
|
8
|
+
/** The full Redis key, prefix included. */
|
|
9
|
+
readonly key: string;
|
|
10
|
+
/** This holder's fencing token. Ownership is decided by comparing it. */
|
|
11
|
+
readonly token: string;
|
|
12
|
+
/** Release the lock. `false` means it was already lost — someone else owns it now. */
|
|
13
|
+
release(): Promise<boolean>;
|
|
14
|
+
/** Push the lease out by `ttlMs`. `false` means the lease was already lost. */
|
|
15
|
+
extend(ttlMs: number): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
export interface AcquireLockOptions {
|
|
18
|
+
/** How long the lease survives without being extended. */
|
|
19
|
+
ttlMs?: number;
|
|
20
|
+
/** How long to keep retrying a contended lock. `0` (the default) tries once. */
|
|
21
|
+
retryTimeoutMs?: number;
|
|
22
|
+
/** How long to wait between attempts while retrying. */
|
|
23
|
+
retryIntervalMs?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface DistributedLockOptions {
|
|
26
|
+
/** Namespace for every key this instance takes, so two features cannot collide. */
|
|
27
|
+
keyPrefix?: string;
|
|
28
|
+
defaultTtlMs?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Called when `withLock` cannot release a lease it held.
|
|
31
|
+
*
|
|
32
|
+
* The failure is swallowed on purpose — see `withLock` — so this is the only
|
|
33
|
+
* place it can be observed. A caller that wants it in the log passes a
|
|
34
|
+
* logger call here; one that does not gets the lease expiring on its TTL.
|
|
35
|
+
*/
|
|
36
|
+
onReleaseFailure?: (key: string, error: unknown) => void;
|
|
37
|
+
}
|
|
38
|
+
/** What `withLock` did: ran the work, or found somebody else already on it. */
|
|
39
|
+
export type LockOutcome<T> = {
|
|
40
|
+
acquired: true;
|
|
41
|
+
result: T;
|
|
42
|
+
} | {
|
|
43
|
+
acquired: false;
|
|
44
|
+
};
|
|
45
|
+
export declare const DEFAULT_LOCK_TTL_MS = 30000;
|
|
46
|
+
export declare const DEFAULT_LOCK_KEY_PREFIX = "lock";
|
|
47
|
+
export declare const DEFAULT_LOCK_RETRY_INTERVAL_MS = 50;
|
|
48
|
+
/**
|
|
49
|
+
* A Redis lock for work that must happen once across replicas.
|
|
50
|
+
*
|
|
51
|
+
* There is deliberately **no in-memory fallback** when Redis is absent. A
|
|
52
|
+
* local lock answers "acquired" on every replica at once, which is the exact
|
|
53
|
+
* opposite of what the caller asked for, and it does so silently. A caller
|
|
54
|
+
* without Redis holds no lock and should know it: construct the lock only when
|
|
55
|
+
* `createRedisClient` returned a client, and take the un-coordinated path
|
|
56
|
+
* otherwise.
|
|
57
|
+
*/
|
|
58
|
+
export declare class DistributedLock {
|
|
59
|
+
private readonly redis;
|
|
60
|
+
private readonly keyPrefix;
|
|
61
|
+
private readonly defaultTtlMs;
|
|
62
|
+
private readonly onReleaseFailure;
|
|
63
|
+
constructor(redis: LockRedis, options?: DistributedLockOptions);
|
|
64
|
+
/** Take the lock, or return `null` if someone else holds it. */
|
|
65
|
+
acquire(key: string, options?: AcquireLockOptions): Promise<LockHandle | null>;
|
|
66
|
+
/**
|
|
67
|
+
* Run `work` while holding the lock, releasing it afterwards either way.
|
|
68
|
+
*
|
|
69
|
+
* A throw from `work` propagates: turning it into a result field is how a
|
|
70
|
+
* failing refresh becomes invisible to the caller that asked for it.
|
|
71
|
+
*/
|
|
72
|
+
withLock<T>(key: string, work: () => Promise<T>, options?: AcquireLockOptions): Promise<LockOutcome<T>>;
|
|
73
|
+
private handle;
|
|
74
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DistributedLock = exports.DEFAULT_LOCK_RETRY_INTERVAL_MS = exports.DEFAULT_LOCK_KEY_PREFIX = exports.DEFAULT_LOCK_TTL_MS = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const redis_script_1 = require("../scripting/redis-script");
|
|
6
|
+
exports.DEFAULT_LOCK_TTL_MS = 30_000;
|
|
7
|
+
exports.DEFAULT_LOCK_KEY_PREFIX = 'lock';
|
|
8
|
+
exports.DEFAULT_LOCK_RETRY_INTERVAL_MS = 50;
|
|
9
|
+
/**
|
|
10
|
+
* Release only if we still own the lease.
|
|
11
|
+
*
|
|
12
|
+
* `GET` then `DEL` as two round trips is the classic way a lock becomes a
|
|
13
|
+
* no-op: between the two, the lease can lapse and another replica can take it,
|
|
14
|
+
* and the `DEL` then frees *its* lock. Matching the token and deleting must be
|
|
15
|
+
* one server-side step.
|
|
16
|
+
*/
|
|
17
|
+
const RELEASE = new redis_script_1.RedisScript(`
|
|
18
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
19
|
+
return redis.call('DEL', KEYS[1])
|
|
20
|
+
end
|
|
21
|
+
return 0
|
|
22
|
+
`);
|
|
23
|
+
/** Extend only if we still own the lease, for the same reason. */
|
|
24
|
+
const EXTEND = new redis_script_1.RedisScript(`
|
|
25
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
26
|
+
return redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
27
|
+
end
|
|
28
|
+
return 0
|
|
29
|
+
`);
|
|
30
|
+
/**
|
|
31
|
+
* A Redis lock for work that must happen once across replicas.
|
|
32
|
+
*
|
|
33
|
+
* There is deliberately **no in-memory fallback** when Redis is absent. A
|
|
34
|
+
* local lock answers "acquired" on every replica at once, which is the exact
|
|
35
|
+
* opposite of what the caller asked for, and it does so silently. A caller
|
|
36
|
+
* without Redis holds no lock and should know it: construct the lock only when
|
|
37
|
+
* `createRedisClient` returned a client, and take the un-coordinated path
|
|
38
|
+
* otherwise.
|
|
39
|
+
*/
|
|
40
|
+
class DistributedLock {
|
|
41
|
+
constructor(redis, options = {}) {
|
|
42
|
+
this.redis = redis;
|
|
43
|
+
this.keyPrefix = options.keyPrefix ?? exports.DEFAULT_LOCK_KEY_PREFIX;
|
|
44
|
+
this.defaultTtlMs = options.defaultTtlMs ?? exports.DEFAULT_LOCK_TTL_MS;
|
|
45
|
+
this.onReleaseFailure = options.onReleaseFailure;
|
|
46
|
+
}
|
|
47
|
+
/** Take the lock, or return `null` if someone else holds it. */
|
|
48
|
+
async acquire(key, options = {}) {
|
|
49
|
+
const lockKey = `${this.keyPrefix}:${key}`;
|
|
50
|
+
const ttlMs = options.ttlMs ?? this.defaultTtlMs;
|
|
51
|
+
const retryUntil = Date.now() + (options.retryTimeoutMs ?? 0);
|
|
52
|
+
const retryIntervalMs = options.retryIntervalMs ?? exports.DEFAULT_LOCK_RETRY_INTERVAL_MS;
|
|
53
|
+
for (;;) {
|
|
54
|
+
const token = (0, node_crypto_1.randomUUID)();
|
|
55
|
+
if ((await this.redis.set(lockKey, token, 'PX', ttlMs, 'NX')) !== null) {
|
|
56
|
+
return this.handle(lockKey, token);
|
|
57
|
+
}
|
|
58
|
+
if (Date.now() + retryIntervalMs > retryUntil)
|
|
59
|
+
return null;
|
|
60
|
+
await sleep(retryIntervalMs);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Run `work` while holding the lock, releasing it afterwards either way.
|
|
65
|
+
*
|
|
66
|
+
* A throw from `work` propagates: turning it into a result field is how a
|
|
67
|
+
* failing refresh becomes invisible to the caller that asked for it.
|
|
68
|
+
*/
|
|
69
|
+
async withLock(key, work, options = {}) {
|
|
70
|
+
const handle = await this.acquire(key, options);
|
|
71
|
+
if (handle === null)
|
|
72
|
+
return { acquired: false };
|
|
73
|
+
try {
|
|
74
|
+
return { acquired: true, result: await work() };
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
// A rejection from `release` must not escape this `finally`: it would
|
|
78
|
+
// replace a completed result with a Redis error the caller never asked
|
|
79
|
+
// about, or — worse — displace the error `work` actually threw. The
|
|
80
|
+
// lease expires on its own, which is what the TTL is for.
|
|
81
|
+
await handle.release().catch((error) => {
|
|
82
|
+
this.onReleaseFailure?.(key, error);
|
|
83
|
+
return false;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
handle(key, token) {
|
|
88
|
+
return {
|
|
89
|
+
key,
|
|
90
|
+
token,
|
|
91
|
+
release: async () => (await RELEASE.run(this.redis, [key], [token])) === 1,
|
|
92
|
+
extend: async (ttlMs) => (await EXTEND.run(this.redis, [key], [token, ttlMs])) === 1,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
exports.DistributedLock = DistributedLock;
|
|
97
|
+
function sleep(ms) {
|
|
98
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
99
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type ScriptableRedis } from '../scripting/redis-script';
|
|
2
|
+
/** What one attempt to spend a token learned about the bucket. */
|
|
3
|
+
export interface TokenBucketResult {
|
|
4
|
+
/** Whether this request is within the quota. */
|
|
5
|
+
allowed: boolean;
|
|
6
|
+
/** Tokens left in the current window; `0` once the quota is spent. */
|
|
7
|
+
remaining: number;
|
|
8
|
+
/** Seconds until the window resets — the value a `Retry-After` header wants. */
|
|
9
|
+
resetInSeconds: number;
|
|
10
|
+
}
|
|
11
|
+
/** One bucket: which counter, how many requests, over how long. */
|
|
12
|
+
export interface TokenBucketOptions {
|
|
13
|
+
key: string;
|
|
14
|
+
capacity: number;
|
|
15
|
+
windowSeconds: number;
|
|
16
|
+
}
|
|
17
|
+
/** Thrown when a bucket is configured in a way that could not limit anything. */
|
|
18
|
+
export declare class TokenBucketConfigError extends Error {
|
|
19
|
+
constructor(message: string);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Spend one token from `key`'s bucket.
|
|
23
|
+
*
|
|
24
|
+
* Fails open nowhere: a Redis error propagates, because a rate limiter that
|
|
25
|
+
* silently allows everything on error is a rate limiter that stops existing
|
|
26
|
+
* exactly when it is needed. Callers decide what to do with the rejection.
|
|
27
|
+
*/
|
|
28
|
+
export declare function consumeTokenBucket(redis: ScriptableRedis, { key, capacity, windowSeconds }: TokenBucketOptions): Promise<TokenBucketResult>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TokenBucketConfigError = void 0;
|
|
4
|
+
exports.consumeTokenBucket = consumeTokenBucket;
|
|
5
|
+
const redis_script_1 = require("../scripting/redis-script");
|
|
6
|
+
/** Thrown when a bucket is configured in a way that could not limit anything. */
|
|
7
|
+
class TokenBucketConfigError extends Error {
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = 'TokenBucketConfigError';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.TokenBucketConfigError = TokenBucketConfigError;
|
|
14
|
+
/**
|
|
15
|
+
* Count one request and anchor the window, as one server-side step.
|
|
16
|
+
*
|
|
17
|
+
* Why Lua and not a pipeline: a pipeline is not atomic across replicas or
|
|
18
|
+
* against other concurrent clients, so `INCR` + `EXPIRE` + `TTL` as three
|
|
19
|
+
* round trips leaves a TOCTOU window where two callers both read
|
|
20
|
+
* `count == capacity` and both pass the cap.
|
|
21
|
+
*
|
|
22
|
+
* `EXPIRE` runs on the first increment, which is what anchors the window to
|
|
23
|
+
* the first request. Re-expiring on every call would slide the window forward,
|
|
24
|
+
* and a bucket under sustained traffic would never reset.
|
|
25
|
+
*
|
|
26
|
+
* It also runs whenever the counter reports no usable TTL (`ttl <= 0`), which
|
|
27
|
+
* is not the same thing. A key whose expiry never landed, or that an operator
|
|
28
|
+
* PERSISTed (`-1`), would otherwise only ever be incremented: the count climbs
|
|
29
|
+
* past the capacity and the bucket denies every request for the life of the
|
|
30
|
+
* key. `0` is the same case a second later. Re-anchoring makes both recover on
|
|
31
|
+
* their own after one window, and leaves the script with no path that returns
|
|
32
|
+
* a TTL the caller has to second-guess.
|
|
33
|
+
*/
|
|
34
|
+
const TOKEN_BUCKET = new redis_script_1.RedisScript(`
|
|
35
|
+
local count = redis.call('INCR', KEYS[1])
|
|
36
|
+
local ttl = redis.call('TTL', KEYS[1])
|
|
37
|
+
if count == 1 or ttl <= 0 then
|
|
38
|
+
redis.call('EXPIRE', KEYS[1], ARGV[1])
|
|
39
|
+
ttl = tonumber(ARGV[1])
|
|
40
|
+
end
|
|
41
|
+
return {count, ttl}
|
|
42
|
+
`);
|
|
43
|
+
/**
|
|
44
|
+
* Spend one token from `key`'s bucket.
|
|
45
|
+
*
|
|
46
|
+
* Fails open nowhere: a Redis error propagates, because a rate limiter that
|
|
47
|
+
* silently allows everything on error is a rate limiter that stops existing
|
|
48
|
+
* exactly when it is needed. Callers decide what to do with the rejection.
|
|
49
|
+
*/
|
|
50
|
+
async function consumeTokenBucket(redis, { key, capacity, windowSeconds }) {
|
|
51
|
+
assertPositiveInteger('windowSeconds', windowSeconds);
|
|
52
|
+
assertPositiveInteger('capacity', capacity);
|
|
53
|
+
const [count, ttl] = (await TOKEN_BUCKET.run(redis, [key], [windowSeconds]));
|
|
54
|
+
const allowed = count <= capacity;
|
|
55
|
+
return {
|
|
56
|
+
allowed,
|
|
57
|
+
remaining: allowed ? Math.max(0, capacity - count) : 0,
|
|
58
|
+
// Always positive: the script re-anchors anything that is not, so there is
|
|
59
|
+
// no "no window to report" case left for the caller to paper over.
|
|
60
|
+
resetInSeconds: ttl,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Validate the bucket before it reaches Redis.
|
|
65
|
+
*
|
|
66
|
+
* `EXPIRE key 0` **deletes** the key, so a zero or negative window makes every
|
|
67
|
+
* call see `count == 1` and pass: a rate limiter that silently does not limit,
|
|
68
|
+
* discovered only by whoever abuses the endpoint. A fractional window is
|
|
69
|
+
* truncated by Redis and a fractional capacity compares against an integer
|
|
70
|
+
* count, so both mean something other than what they say. This is the argument
|
|
71
|
+
* `parsePort` makes about `REDIS_PORT`, applied where it matters more.
|
|
72
|
+
*/
|
|
73
|
+
function assertPositiveInteger(field, value) {
|
|
74
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
75
|
+
throw new TokenBucketConfigError(`${field} must be an integer of at least 1, got ${JSON.stringify(value)}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two commands a Lua script needs. Structural rather than `Redis`, so the
|
|
3
|
+
* scripts are testable without a server and usable with any ioredis-shaped
|
|
4
|
+
* client a consumer already holds.
|
|
5
|
+
*/
|
|
6
|
+
export interface ScriptableRedis {
|
|
7
|
+
evalsha(sha: string, ...args: unknown[]): Promise<unknown>;
|
|
8
|
+
eval(script: string, ...args: unknown[]): Promise<unknown>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A server-side Lua script, sent by SHA and loaded on demand.
|
|
12
|
+
*
|
|
13
|
+
* Why not `EVAL` every time: the script body would travel on every call, which
|
|
14
|
+
* for a rate limiter is the body on every request. Why not `defineCommand`:
|
|
15
|
+
* it attaches a method to the client, so a script becomes something a client
|
|
16
|
+
* must be prepared for before it can be used, and the resulting dynamic method
|
|
17
|
+
* cannot be typed or faked cleanly. `EVALSHA` with a `NOSCRIPT` fallback is
|
|
18
|
+
* what `defineCommand` does underneath, expressed as a value.
|
|
19
|
+
*
|
|
20
|
+
* The fallback is not a one-time warm-up. `SCRIPT FLUSH`, a failover and a
|
|
21
|
+
* fresh replica all lose the cache, so every call has to be able to reload.
|
|
22
|
+
*/
|
|
23
|
+
export declare class RedisScript {
|
|
24
|
+
private readonly body;
|
|
25
|
+
/** The SHA-1 Redis itself derives from the body — the value `SCRIPT LOAD` returns. */
|
|
26
|
+
readonly sha: string;
|
|
27
|
+
constructor(body: string);
|
|
28
|
+
run(redis: ScriptableRedis, keys: string[], args: Array<string | number>): Promise<unknown>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RedisScript = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
/** Redis answers a SHA it has never loaded with an error starting `NOSCRIPT`. */
|
|
6
|
+
function isNoScriptError(error) {
|
|
7
|
+
return error instanceof Error && error.message.startsWith('NOSCRIPT');
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A server-side Lua script, sent by SHA and loaded on demand.
|
|
11
|
+
*
|
|
12
|
+
* Why not `EVAL` every time: the script body would travel on every call, which
|
|
13
|
+
* for a rate limiter is the body on every request. Why not `defineCommand`:
|
|
14
|
+
* it attaches a method to the client, so a script becomes something a client
|
|
15
|
+
* must be prepared for before it can be used, and the resulting dynamic method
|
|
16
|
+
* cannot be typed or faked cleanly. `EVALSHA` with a `NOSCRIPT` fallback is
|
|
17
|
+
* what `defineCommand` does underneath, expressed as a value.
|
|
18
|
+
*
|
|
19
|
+
* The fallback is not a one-time warm-up. `SCRIPT FLUSH`, a failover and a
|
|
20
|
+
* fresh replica all lose the cache, so every call has to be able to reload.
|
|
21
|
+
*/
|
|
22
|
+
class RedisScript {
|
|
23
|
+
constructor(body) {
|
|
24
|
+
this.body = body;
|
|
25
|
+
this.sha = (0, node_crypto_1.createHash)('sha1').update(body).digest('hex');
|
|
26
|
+
}
|
|
27
|
+
async run(redis, keys, args) {
|
|
28
|
+
try {
|
|
29
|
+
return await redis.evalsha(this.sha, keys.length, ...keys, ...args);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (!isNoScriptError(error))
|
|
33
|
+
throw error;
|
|
34
|
+
return redis.eval(this.body, keys.length, ...keys, ...args);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
exports.RedisScript = RedisScript;
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@leoribeiroweb/nest-redis",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Shared Redis building blocks: one dual-mode connection (REDIS_URL or host/port/password), an atomic token bucket and a distributed lock.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/leoribeiro2/nest-core.git",
|
|
9
|
+
"directory": "packages/nest-redis"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/leoribeiro2/nest-core/issues"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/leoribeiro2/nest-core#readme",
|
|
15
|
+
"main": "dist/index.js",
|
|
16
|
+
"types": "dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=20.11.0"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.build.json",
|
|
35
|
+
"prepublishOnly": "npm run build"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@nestjs/common": "^11",
|
|
39
|
+
"ioredis": "^5 || ^6",
|
|
40
|
+
"reflect-metadata": "^0.2"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@nestjs/common": "^11.1.28",
|
|
44
|
+
"@nestjs/core": "^11.1.28",
|
|
45
|
+
"@nestjs/testing": "^11.1.28",
|
|
46
|
+
"fengari": "^0.1.5",
|
|
47
|
+
"ioredis": "^6.0.0",
|
|
48
|
+
"reflect-metadata": "^0.2.2"
|
|
49
|
+
}
|
|
50
|
+
}
|