@leoribeiroweb/nest-redis 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,6 +53,54 @@ holding the shutdown sequence open.
53
53
  For a client outside the DI graph, `createRedisClient(source, overrides)` and
54
54
  `resolveRedisConnection(source)` do the same work as plain functions.
55
55
 
56
+ ### Username and database
57
+
58
+ In discrete mode two more variables are read. Each is optional, and unset
59
+ leaves the connection exactly as it was:
60
+
61
+ | Variable | ioredis option | Unset |
62
+ | --- | --- | --- |
63
+ | `REDIS_USERNAME` | `username` | the `default` user |
64
+ | `REDIS_DB` | `db` | database `0` |
65
+
66
+ `REDIS_DB` is validated like `REDIS_PORT`, more strictly: decimal digits only.
67
+ `' 2'`, `'0x10'`, `'1e1'` and `'-1'` throw `RedisConfigError` naming the
68
+ variable, instead of reaching ioredis as whatever `Number()` made of them.
69
+
70
+ URL mode ignores both, as it ignores `REDIS_PASSWORD`: put them in the URL
71
+ (`redis://user:password@host:6379/2`).
72
+
73
+ ### An ACL-restricted user
74
+
75
+ A Redis user that holds only the commands it works with needs ioredis to skip
76
+ the commands it sends on its own:
77
+
78
+ ```ts
79
+ const redis = createRedisClient(
80
+ { REDIS_URL: config.get('DEVICE_REDIS_URL') },
81
+ { ...REDIS_ACL_RESTRICTED_OPTIONS, connectionName: 'social-api-device' },
82
+ );
83
+ ```
84
+
85
+ `REDIS_ACL_RESTRICTED_OPTIONS` is `{ enableReadyCheck: false, disableClientInfo:
86
+ true }`: no `INFO` ready check, no `CLIENT SETINFO`. Every other ioredis option
87
+ (`connectionName`, `username`, `db`, ...) goes through the same overrides
88
+ argument, or `options` on `RedisModule`. Two of them send a command the ACL
89
+ must then grant: `connectionName` sends `CLIENT SETNAME` and a non-zero `db`
90
+ sends `SELECT`.
91
+
92
+ Two more pieces avoid commands such a user may lack:
93
+
94
+ - **`closeRedis(client, { method: 'disconnect' })`** tears the socket down
95
+ without `QUIT`. It is also the right close for a connection parked in a
96
+ blocking read, which would hold a `QUIT` until its own timeout.
97
+ `RedisModule` takes the same choice as `closeMethod: 'disconnect'`. The
98
+ default stays `'quit'`, and `closeRedis(client, timeoutMs)` still works.
99
+ - **`new RedisScript(body, { command: 'eval' })`** sends the body with `EVAL`
100
+ on every call, for a user granted `EVAL` but not `EVALSHA`. The default
101
+ stays `EVALSHA` with a `NOSCRIPT` fallback. The token bucket and the lock
102
+ build their scripts with the default.
103
+
56
104
  ### Connection defaults
57
105
 
58
106
  `maxRetriesPerRequest: 1` and `enableOfflineQueue: false` make a command fail
@@ -16,6 +16,23 @@ export interface ClosableRedis {
16
16
  */
17
17
  export declare const REDIS_CLOSE_TIMEOUT_MS = 2000;
18
18
  export type RedisCloseOutcome = 'closed' | 'abandoned';
19
+ /**
20
+ * How a client is closed.
21
+ *
22
+ * - `'quit'` (the default): send `QUIT`, so replies already in flight arrive
23
+ * before the server closes the socket.
24
+ * - `'disconnect'`: tear the socket down at once and send nothing. For a user
25
+ * whose ACL does not grant `QUIT`, and for a connection parked in a blocking
26
+ * command (`BLPOP`, `XREADGROUP BLOCK`), which would hold a `QUIT` until its
27
+ * own timeout.
28
+ */
29
+ export type RedisCloseMethod = 'quit' | 'disconnect';
30
+ export interface RedisCloseOptions {
31
+ /** How long a `quit()` may hold the shutdown sequence. Unused by `'disconnect'`. */
32
+ timeoutMs?: number;
33
+ /** Defaults to `'quit'`. */
34
+ method?: RedisCloseMethod;
35
+ }
19
36
  /**
20
37
  * Close a client without letting it hold the process open.
21
38
  *
@@ -24,5 +41,8 @@ export type RedisCloseOutcome = 'closed' | 'abandoned';
24
41
  * timeout the wait is **abandoned** rather than cancelled — ioredis exposes no
25
42
  * way to cancel an in-flight `quit` — and the socket is torn down so nothing
26
43
  * keeps the event loop alive.
44
+ *
45
+ * The second argument is either the deadline in milliseconds, as it always
46
+ * was, or a {@link RedisCloseOptions} object.
27
47
  */
28
- export declare function closeRedis(client: ClosableRedis | null | undefined, timeoutMs?: number): Promise<RedisCloseOutcome>;
48
+ export declare function closeRedis(client: ClosableRedis | null | undefined, timeoutOrOptions?: number | RedisCloseOptions): Promise<RedisCloseOutcome>;
@@ -21,10 +21,18 @@ exports.REDIS_CLOSE_TIMEOUT_MS = 2_000;
21
21
  * timeout the wait is **abandoned** rather than cancelled — ioredis exposes no
22
22
  * way to cancel an in-flight `quit` — and the socket is torn down so nothing
23
23
  * keeps the event loop alive.
24
+ *
25
+ * The second argument is either the deadline in milliseconds, as it always
26
+ * was, or a {@link RedisCloseOptions} object.
24
27
  */
25
- async function closeRedis(client, timeoutMs = exports.REDIS_CLOSE_TIMEOUT_MS) {
28
+ async function closeRedis(client, timeoutOrOptions = exports.REDIS_CLOSE_TIMEOUT_MS) {
29
+ const { timeoutMs = exports.REDIS_CLOSE_TIMEOUT_MS, method = 'quit' } = typeof timeoutOrOptions === 'number' ? { timeoutMs: timeoutOrOptions } : timeoutOrOptions;
26
30
  if (!client || client.status === 'end')
27
31
  return 'closed';
32
+ if (method === 'disconnect') {
33
+ client.disconnect();
34
+ return 'closed';
35
+ }
28
36
  let timer;
29
37
  const deadline = new Promise((resolve) => {
30
38
  timer = setTimeout(() => resolve('abandoned'), timeoutMs);
@@ -32,7 +32,33 @@ export type RedisConnectionOptions = RedisOptions & {
32
32
  */
33
33
  export declare const redisRetryStrategy: (times: number) => number;
34
34
  export declare const REDIS_DEFAULT_OPTIONS: RedisOptions;
35
- /** Turn resolved settings into the options object ioredis (or BullMQ) needs. */
35
+ /**
36
+ * Overrides for a Redis user whose ACL grants only the commands it works with.
37
+ *
38
+ * ioredis sends two commands of its own on every connect:
39
+ *
40
+ * - `INFO`, the ready check (`enableReadyCheck`). Refused, ioredis carries
41
+ * on but prints an unstructured console warning on every connect.
42
+ * - `CLIENT SETINFO` twice (`disableClientInfo`). Refused, ioredis swallows
43
+ * the error, but every connect still spends the round trips and leaves
44
+ * two denials in the server's `ACL LOG`.
45
+ *
46
+ * Not included, because each sends a command the ACL must then grant:
47
+ * `connectionName` (`CLIENT SETNAME`; a refusal is swallowed and the name is
48
+ * simply not set) and a non-zero `db` (`SELECT`; a refusal is emitted as an
49
+ * `error` event). Add them only for a user that holds those commands. The
50
+ * `browser-worker` desktop user (`WORKER_ACL_COMMANDS`, mirrored from
51
+ * `chloe-infra-final/values/redis-device.yaml`) holds neither.
52
+ */
53
+ export declare const REDIS_ACL_RESTRICTED_OPTIONS: Readonly<Pick<RedisOptions, 'enableReadyCheck' | 'disableClientInfo'>>;
54
+ /**
55
+ * Turn resolved settings into the options object ioredis (or BullMQ) needs.
56
+ *
57
+ * Every other ioredis option — `enableReadyCheck`, `connectionName`,
58
+ * `disableClientInfo`, a `username` or `db` not taken from the environment —
59
+ * goes through `overrides`. Values resolved from the environment win over an
60
+ * override of the same key, as the host, port and password always have.
61
+ */
36
62
  export declare function buildRedisOptions(settings: RedisConnectionSettings, overrides?: RedisOptions): RedisConnectionOptions;
37
63
  /**
38
64
  * Build the process's Redis client, or `null` when Redis is not configured.
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.REDIS_DEFAULT_OPTIONS = exports.redisRetryStrategy = void 0;
6
+ exports.REDIS_ACL_RESTRICTED_OPTIONS = exports.REDIS_DEFAULT_OPTIONS = exports.redisRetryStrategy = void 0;
7
7
  exports.buildRedisOptions = buildRedisOptions;
8
8
  exports.createRedisClient = createRedisClient;
9
9
  const ioredis_1 = __importDefault(require("ioredis"));
@@ -33,17 +33,48 @@ exports.REDIS_DEFAULT_OPTIONS = {
33
33
  enableOfflineQueue: false,
34
34
  retryStrategy: exports.redisRetryStrategy,
35
35
  };
36
- /** Turn resolved settings into the options object ioredis (or BullMQ) needs. */
36
+ /**
37
+ * Overrides for a Redis user whose ACL grants only the commands it works with.
38
+ *
39
+ * ioredis sends two commands of its own on every connect:
40
+ *
41
+ * - `INFO`, the ready check (`enableReadyCheck`). Refused, ioredis carries
42
+ * on but prints an unstructured console warning on every connect.
43
+ * - `CLIENT SETINFO` twice (`disableClientInfo`). Refused, ioredis swallows
44
+ * the error, but every connect still spends the round trips and leaves
45
+ * two denials in the server's `ACL LOG`.
46
+ *
47
+ * Not included, because each sends a command the ACL must then grant:
48
+ * `connectionName` (`CLIENT SETNAME`; a refusal is swallowed and the name is
49
+ * simply not set) and a non-zero `db` (`SELECT`; a refusal is emitted as an
50
+ * `error` event). Add them only for a user that holds those commands. The
51
+ * `browser-worker` desktop user (`WORKER_ACL_COMMANDS`, mirrored from
52
+ * `chloe-infra-final/values/redis-device.yaml`) holds neither.
53
+ */
54
+ exports.REDIS_ACL_RESTRICTED_OPTIONS = {
55
+ enableReadyCheck: false,
56
+ disableClientInfo: true,
57
+ };
58
+ /**
59
+ * Turn resolved settings into the options object ioredis (or BullMQ) needs.
60
+ *
61
+ * Every other ioredis option — `enableReadyCheck`, `connectionName`,
62
+ * `disableClientInfo`, a `username` or `db` not taken from the environment —
63
+ * goes through `overrides`. Values resolved from the environment win over an
64
+ * override of the same key, as the host, port and password always have.
65
+ */
37
66
  function buildRedisOptions(settings, overrides = {}) {
38
67
  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
- };
68
+ if (settings.mode === 'url')
69
+ return { ...base, url: settings.url };
70
+ return {
71
+ ...base,
72
+ host: settings.host,
73
+ port: settings.port,
74
+ password: settings.password,
75
+ ...(settings.username !== undefined ? { username: settings.username } : {}),
76
+ ...(settings.db !== undefined ? { db: settings.db } : {}),
77
+ };
47
78
  }
48
79
  /**
49
80
  * Build the process's Redis client, or `null` when Redis is not configured.
@@ -5,6 +5,10 @@ export declare const REDIS_URL_KEY = "REDIS_URL";
5
5
  export declare const REDIS_HOST_KEY = "REDIS_HOST";
6
6
  export declare const REDIS_PORT_KEY = "REDIS_PORT";
7
7
  export declare const REDIS_PASSWORD_KEY = "REDIS_PASSWORD";
8
+ /** Discrete mode only: the ACL user to authenticate as. Unset means the `default` user. */
9
+ export declare const REDIS_USERNAME_KEY = "REDIS_USERNAME";
10
+ /** Discrete mode only: the logical database index. Unset means database 0. */
11
+ export declare const REDIS_DB_KEY = "REDIS_DB";
8
12
  /**
9
13
  * Where the connection came from.
10
14
  *
@@ -18,6 +22,12 @@ export declare const REDIS_PASSWORD_KEY = "REDIS_PASSWORD";
18
22
  *
19
23
  * The mode is kept on the result rather than collapsed into ioredis options so
20
24
  * callers (and tests) can assert which branch a given environment takes.
25
+ *
26
+ * `username` and `db` exist only in discrete mode and only when configured:
27
+ * the key is absent, not `undefined`, so a deployment that sets neither
28
+ * resolves to exactly the object it always did. URL mode ignores
29
+ * `REDIS_USERNAME` and `REDIS_DB` as it ignores `REDIS_PASSWORD`: a URL
30
+ * carries its own (`redis://user:password@host:6379/2`).
21
31
  */
22
32
  export type RedisConnectionSettings = {
23
33
  readonly mode: 'url';
@@ -27,6 +37,8 @@ export type RedisConnectionSettings = {
27
37
  readonly host: string;
28
38
  readonly port: number;
29
39
  readonly password: string | undefined;
40
+ readonly username?: string;
41
+ readonly db?: number;
30
42
  };
31
43
  /** A `ConfigService`-shaped source, structurally typed so no config package is required. */
32
44
  export interface RedisConfigGetter {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
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;
3
+ exports.RedisConfigError = exports.REDIS_DB_KEY = exports.REDIS_USERNAME_KEY = exports.REDIS_PASSWORD_KEY = exports.REDIS_PORT_KEY = exports.REDIS_HOST_KEY = exports.REDIS_URL_KEY = exports.DEFAULT_REDIS_PORT = void 0;
4
4
  exports.resolveRedisConnection = resolveRedisConnection;
5
5
  /** The port Redis listens on when the deployment does not say otherwise. */
6
6
  exports.DEFAULT_REDIS_PORT = 6379;
@@ -9,6 +9,10 @@ exports.REDIS_URL_KEY = 'REDIS_URL';
9
9
  exports.REDIS_HOST_KEY = 'REDIS_HOST';
10
10
  exports.REDIS_PORT_KEY = 'REDIS_PORT';
11
11
  exports.REDIS_PASSWORD_KEY = 'REDIS_PASSWORD';
12
+ /** Discrete mode only: the ACL user to authenticate as. Unset means the `default` user. */
13
+ exports.REDIS_USERNAME_KEY = 'REDIS_USERNAME';
14
+ /** Discrete mode only: the logical database index. Unset means database 0. */
15
+ exports.REDIS_DB_KEY = 'REDIS_DB';
12
16
  /** Thrown when Redis is configured, but configured wrongly. */
13
17
  class RedisConfigError extends Error {
14
18
  constructor(message) {
@@ -53,6 +57,25 @@ function parsePort(raw) {
53
57
  }
54
58
  return port;
55
59
  }
60
+ /**
61
+ * Parse `REDIS_DB`: decimal digits only.
62
+ *
63
+ * Stricter than the port on purpose, since there is no legacy value to stay
64
+ * compatible with: `Number()` reads `' 2'`, `'0x10'` and `'1e1'` as integers,
65
+ * and a job queue silently sharing database 16 with something else is worse
66
+ * than a boot that names the variable. The upper bound is the server's
67
+ * `databases` setting, which only the server knows; it answers an
68
+ * out-of-range `SELECT` with an error on connect.
69
+ */
70
+ function parseDb(raw) {
71
+ if (raw === undefined)
72
+ return undefined;
73
+ const db = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
74
+ if (!Number.isSafeInteger(db)) {
75
+ throw new RedisConfigError(`${exports.REDIS_DB_KEY} must be a non-negative integer, got ${JSON.stringify(raw)}`);
76
+ }
77
+ return db;
78
+ }
56
79
  /**
57
80
  * Resolve the one Redis connection this process should use, or `null` when
58
81
  * Redis is not configured at all.
@@ -69,10 +92,15 @@ function resolveRedisConnection(source) {
69
92
  const host = readKey(source, exports.REDIS_HOST_KEY);
70
93
  if (host === undefined)
71
94
  return null;
95
+ const port = parsePort(readKey(source, exports.REDIS_PORT_KEY));
96
+ const username = readKey(source, exports.REDIS_USERNAME_KEY);
97
+ const db = parseDb(readKey(source, exports.REDIS_DB_KEY));
72
98
  return {
73
99
  mode: 'discrete',
74
100
  host,
75
- port: parsePort(readKey(source, exports.REDIS_PORT_KEY)),
101
+ port,
76
102
  password: readKey(source, exports.REDIS_PASSWORD_KEY),
103
+ ...(username !== undefined ? { username } : {}),
104
+ ...(db !== undefined ? { db } : {}),
77
105
  };
78
106
  }
@@ -1,6 +1,7 @@
1
1
  import { type DynamicModule, type InjectionToken, type ModuleMetadata, type OnApplicationShutdown, type OptionalFactoryDependency } from '@nestjs/common';
2
2
  import type Redis from 'ioredis';
3
3
  import type { RedisOptions } from 'ioredis';
4
+ import { type RedisCloseMethod } from './close-redis';
4
5
  import type { RedisConfigSource } from './redis-connection';
5
6
  /**
6
7
  * The process's Redis client, or `null` when Redis is not configured.
@@ -11,12 +12,21 @@ import type { RedisConfigSource } from './redis-connection';
11
12
  */
12
13
  export declare const REDIS_CLIENT: unique symbol;
13
14
  export interface RedisModuleOptions {
14
- /** Where to read `REDIS_URL` / `REDIS_HOST` / `REDIS_PORT` / `REDIS_PASSWORD`. */
15
+ /**
16
+ * Where to read `REDIS_URL` / `REDIS_HOST` / `REDIS_PORT` / `REDIS_PASSWORD`
17
+ * (and, in discrete mode, `REDIS_USERNAME` / `REDIS_DB`).
18
+ */
15
19
  source: RedisConfigSource;
16
- /** ioredis overrides on top of `REDIS_DEFAULT_OPTIONS`. */
20
+ /**
21
+ * ioredis overrides on top of `REDIS_DEFAULT_OPTIONS`: `enableReadyCheck`,
22
+ * `connectionName`, `disableClientInfo` and the rest. See
23
+ * `REDIS_ACL_RESTRICTED_OPTIONS` for an ACL-restricted user.
24
+ */
17
25
  options?: RedisOptions;
18
26
  /** How long `quit()` may hold shutdown. Align with the consumer's budget. */
19
27
  closeTimeoutMs?: number;
28
+ /** `'disconnect'` closes without sending `QUIT`. Defaults to `'quit'`. */
29
+ closeMethod?: RedisCloseMethod;
20
30
  }
21
31
  export interface RedisModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
22
32
  inject?: (InjectionToken | OptionalFactoryDependency)[];
@@ -31,7 +41,8 @@ export interface RedisModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'>
31
41
  export declare class RedisModule implements OnApplicationShutdown {
32
42
  private readonly client;
33
43
  private readonly closeTimeoutMs?;
34
- constructor(client: Redis | null, closeTimeoutMs?: number | undefined);
44
+ private readonly closeMethod?;
45
+ constructor(client: Redis | null, closeTimeoutMs?: number | undefined, closeMethod?: RedisCloseMethod | undefined);
35
46
  static forRoot(options: RedisModuleOptions): DynamicModule;
36
47
  static forRootAsync(asyncOptions: RedisModuleAsyncOptions): DynamicModule;
37
48
  onApplicationShutdown(): Promise<void>;
@@ -27,6 +27,8 @@ const redis_client_1 = require("./redis-client");
27
27
  exports.REDIS_CLIENT = Symbol('nest-redis:client');
28
28
  /** Internal token carrying the close deadline to the shutdown hook. */
29
29
  const REDIS_CLOSE_TIMEOUT = Symbol('nest-redis:close-timeout');
30
+ /** Internal token carrying the close method to the shutdown hook. */
31
+ const REDIS_CLOSE_METHOD = Symbol('nest-redis:close-method');
30
32
  /**
31
33
  * Wires one Redis connection into the application and closes it on the way out.
32
34
  *
@@ -34,9 +36,10 @@ const REDIS_CLOSE_TIMEOUT = Symbol('nest-redis:close-timeout');
34
36
  * every feature module re-import it only spreads the same singleton around.
35
37
  */
36
38
  let RedisModule = RedisModule_1 = class RedisModule {
37
- constructor(client, closeTimeoutMs) {
39
+ constructor(client, closeTimeoutMs, closeMethod) {
38
40
  this.client = client;
39
41
  this.closeTimeoutMs = closeTimeoutMs;
42
+ this.closeMethod = closeMethod;
40
43
  }
41
44
  static forRoot(options) {
42
45
  return {
@@ -60,6 +63,10 @@ let RedisModule = RedisModule_1 = class RedisModule {
60
63
  provide: REDIS_CLOSE_TIMEOUT,
61
64
  useValue: options.closeTimeoutMs ?? close_redis_1.REDIS_CLOSE_TIMEOUT_MS,
62
65
  },
66
+ {
67
+ provide: REDIS_CLOSE_METHOD,
68
+ useValue: options.closeMethod ?? 'quit',
69
+ },
63
70
  ],
64
71
  exports: [exports.REDIS_CLIENT],
65
72
  };
@@ -85,12 +92,20 @@ let RedisModule = RedisModule_1 = class RedisModule {
85
92
  useFactory: (options) => options.closeTimeoutMs ?? close_redis_1.REDIS_CLOSE_TIMEOUT_MS,
86
93
  inject: [RESOLVED],
87
94
  },
95
+ {
96
+ provide: REDIS_CLOSE_METHOD,
97
+ useFactory: (options) => options.closeMethod ?? 'quit',
98
+ inject: [RESOLVED],
99
+ },
88
100
  ],
89
101
  exports: [exports.REDIS_CLIENT],
90
102
  };
91
103
  }
92
104
  async onApplicationShutdown() {
93
- await (0, close_redis_1.closeRedis)(this.client, this.closeTimeoutMs);
105
+ await (0, close_redis_1.closeRedis)(this.client, {
106
+ timeoutMs: this.closeTimeoutMs,
107
+ method: this.closeMethod,
108
+ });
94
109
  }
95
110
  };
96
111
  exports.RedisModule = RedisModule;
@@ -100,5 +115,7 @@ exports.RedisModule = RedisModule = RedisModule_1 = __decorate([
100
115
  __param(0, (0, common_1.Inject)(exports.REDIS_CLIENT)),
101
116
  __param(1, (0, common_1.Optional)()),
102
117
  __param(1, (0, common_1.Inject)(REDIS_CLOSE_TIMEOUT)),
103
- __metadata("design:paramtypes", [Object, Number])
118
+ __param(2, (0, common_1.Optional)()),
119
+ __param(2, (0, common_1.Inject)(REDIS_CLOSE_METHOD)),
120
+ __metadata("design:paramtypes", [Object, Number, String])
104
121
  ], RedisModule);
package/dist/index.d.ts CHANGED
@@ -1,7 +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';
1
+ export { closeRedis, REDIS_CLOSE_TIMEOUT_MS, type ClosableRedis, type RedisCloseMethod, type RedisCloseOptions, type RedisCloseOutcome, } from './connection/close-redis';
2
+ export { buildRedisOptions, createRedisClient, REDIS_ACL_RESTRICTED_OPTIONS, REDIS_DEFAULT_OPTIONS, redisRetryStrategy, type RedisConnectionOptions, } from './connection/redis-client';
3
+ export { DEFAULT_REDIS_PORT, REDIS_DB_KEY, REDIS_HOST_KEY, REDIS_PASSWORD_KEY, REDIS_PORT_KEY, REDIS_URL_KEY, REDIS_USERNAME_KEY, RedisConfigError, resolveRedisConnection, type RedisConfigGetter, type RedisConfigSource, type RedisConnectionSettings, } from './connection/redis-connection';
4
4
  export { REDIS_CLIENT, RedisModule, type RedisModuleAsyncOptions, type RedisModuleOptions, } from './connection/redis.module';
5
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
6
  export { consumeTokenBucket, TokenBucketConfigError, type TokenBucketOptions, type TokenBucketResult, } from './rate-limit/token-bucket';
7
- export { RedisScript, type ScriptableRedis } from './scripting/redis-script';
7
+ export { RedisScript, type RedisScriptCommand, type RedisScriptOptions, type ScriptableRedis, } from './scripting/redis-script';
package/dist/index.js CHANGED
@@ -1,20 +1,23 @@
1
1
  "use strict";
2
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;
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_USERNAME_KEY = exports.REDIS_URL_KEY = exports.REDIS_PORT_KEY = exports.REDIS_PASSWORD_KEY = exports.REDIS_HOST_KEY = exports.REDIS_DB_KEY = exports.DEFAULT_REDIS_PORT = exports.redisRetryStrategy = exports.REDIS_DEFAULT_OPTIONS = exports.REDIS_ACL_RESTRICTED_OPTIONS = exports.createRedisClient = exports.buildRedisOptions = exports.REDIS_CLOSE_TIMEOUT_MS = exports.closeRedis = void 0;
4
4
  var close_redis_1 = require("./connection/close-redis");
5
5
  Object.defineProperty(exports, "closeRedis", { enumerable: true, get: function () { return close_redis_1.closeRedis; } });
6
6
  Object.defineProperty(exports, "REDIS_CLOSE_TIMEOUT_MS", { enumerable: true, get: function () { return close_redis_1.REDIS_CLOSE_TIMEOUT_MS; } });
7
7
  var redis_client_1 = require("./connection/redis-client");
8
8
  Object.defineProperty(exports, "buildRedisOptions", { enumerable: true, get: function () { return redis_client_1.buildRedisOptions; } });
9
9
  Object.defineProperty(exports, "createRedisClient", { enumerable: true, get: function () { return redis_client_1.createRedisClient; } });
10
+ Object.defineProperty(exports, "REDIS_ACL_RESTRICTED_OPTIONS", { enumerable: true, get: function () { return redis_client_1.REDIS_ACL_RESTRICTED_OPTIONS; } });
10
11
  Object.defineProperty(exports, "REDIS_DEFAULT_OPTIONS", { enumerable: true, get: function () { return redis_client_1.REDIS_DEFAULT_OPTIONS; } });
11
12
  Object.defineProperty(exports, "redisRetryStrategy", { enumerable: true, get: function () { return redis_client_1.redisRetryStrategy; } });
12
13
  var redis_connection_1 = require("./connection/redis-connection");
13
14
  Object.defineProperty(exports, "DEFAULT_REDIS_PORT", { enumerable: true, get: function () { return redis_connection_1.DEFAULT_REDIS_PORT; } });
15
+ Object.defineProperty(exports, "REDIS_DB_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_DB_KEY; } });
14
16
  Object.defineProperty(exports, "REDIS_HOST_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_HOST_KEY; } });
15
17
  Object.defineProperty(exports, "REDIS_PASSWORD_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_PASSWORD_KEY; } });
16
18
  Object.defineProperty(exports, "REDIS_PORT_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_PORT_KEY; } });
17
19
  Object.defineProperty(exports, "REDIS_URL_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_URL_KEY; } });
20
+ Object.defineProperty(exports, "REDIS_USERNAME_KEY", { enumerable: true, get: function () { return redis_connection_1.REDIS_USERNAME_KEY; } });
18
21
  Object.defineProperty(exports, "RedisConfigError", { enumerable: true, get: function () { return redis_connection_1.RedisConfigError; } });
19
22
  Object.defineProperty(exports, "resolveRedisConnection", { enumerable: true, get: function () { return redis_connection_1.resolveRedisConnection; } });
20
23
  var redis_module_1 = require("./connection/redis.module");
@@ -7,6 +7,18 @@ export interface ScriptableRedis {
7
7
  evalsha(sha: string, ...args: unknown[]): Promise<unknown>;
8
8
  eval(script: string, ...args: unknown[]): Promise<unknown>;
9
9
  }
10
+ /**
11
+ * - `'evalsha'` (the default): send the SHA, and the body only after a
12
+ * `NOSCRIPT`.
13
+ * - `'eval'`: send the body with `EVAL` every time. For a Redis user whose
14
+ * ACL grants `EVAL` but not `EVALSHA`, such as the `browser-worker` desktop
15
+ * user. Worth it only for a short script on a low-traffic path.
16
+ */
17
+ export type RedisScriptCommand = 'evalsha' | 'eval';
18
+ export interface RedisScriptOptions {
19
+ /** Defaults to `'evalsha'`. */
20
+ command?: RedisScriptCommand;
21
+ }
10
22
  /**
11
23
  * A server-side Lua script, sent by SHA and loaded on demand.
12
24
  *
@@ -24,6 +36,8 @@ export declare class RedisScript {
24
36
  private readonly body;
25
37
  /** The SHA-1 Redis itself derives from the body — the value `SCRIPT LOAD` returns. */
26
38
  readonly sha: string;
27
- constructor(body: string);
39
+ /** The command `run` sends. */
40
+ readonly command: RedisScriptCommand;
41
+ constructor(body: string, options?: RedisScriptOptions);
28
42
  run(redis: ScriptableRedis, keys: string[], args: Array<string | number>): Promise<unknown>;
29
43
  }
@@ -20,11 +20,15 @@ function isNoScriptError(error) {
20
20
  * fresh replica all lose the cache, so every call has to be able to reload.
21
21
  */
22
22
  class RedisScript {
23
- constructor(body) {
23
+ constructor(body, options = {}) {
24
24
  this.body = body;
25
25
  this.sha = (0, node_crypto_1.createHash)('sha1').update(body).digest('hex');
26
+ this.command = options.command ?? 'evalsha';
26
27
  }
27
28
  async run(redis, keys, args) {
29
+ if (this.command === 'eval') {
30
+ return redis.eval(this.body, keys.length, ...keys, ...args);
31
+ }
28
32
  try {
29
33
  return await redis.evalsha(this.sha, keys.length, ...keys, ...args);
30
34
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leoribeiroweb/nest-redis",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
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
5
  "license": "UNLICENSED",
6
6
  "repository": {