ioredis-toolkit 0.0.8 → 0.0.10
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 +556 -1
- package/dist/cache.d.ts +39 -36
- package/dist/cache.js +77 -64
- package/dist/client.d.ts +4 -1
- package/dist/client.js +3 -4
- package/dist/lock.d.ts +1 -16
- package/dist/lock.js +43 -0
- package/dist/session/scripts/rotate-encrypted.lua +53 -14
- package/dist/session/scripts/rotate.lua +54 -9
- package/dist/session/session-config.d.ts +20 -0
- package/dist/session/session-config.js +9 -0
- package/dist/session/session-keys.d.ts +13 -0
- package/dist/session/session-keys.js +15 -0
- package/dist/session/session-metrics.d.ts +9 -1
- package/dist/session/session-metrics.js +23 -0
- package/dist/session/session-repository.d.ts +23 -0
- package/dist/session/session-repository.js +102 -22
- package/dist/session/session-serializer.d.ts +1 -1
- package/dist/session/session-serializer.js +19 -0
- package/dist/session/session-service.d.ts +20 -1
- package/dist/session/session-service.js +60 -1
- package/dist/session/session-types.d.ts +28 -0
- package/dist/types.d.ts +17 -0
- package/dist/types.js +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1092,10 +1092,565 @@ The package exports comprehensive types for all modules. Key type exports:
|
|
|
1092
1092
|
| `calculateRedisClusterSlot` | CRC16 slot calculation for cluster keys |
|
|
1093
1093
|
| `hashTag` | Extract hash tag from key (`{tag}:key`) |
|
|
1094
1094
|
|
|
1095
|
+
<a name="api-reference"></a>
|
|
1096
|
+
## Complete API Reference
|
|
1097
|
+
|
|
1098
|
+
This section provides JSDoc-style documentation for every public method, class, and type. Use it as a quick lookup for signatures, parameters, return values, and behaviors.
|
|
1099
|
+
|
|
1100
|
+
### `RedisClientWrapper`
|
|
1101
|
+
|
|
1102
|
+
#### Constructor
|
|
1103
|
+
|
|
1104
|
+
```ts
|
|
1105
|
+
new RedisClientWrapper(config: RedisConfigInput, logger?: LoggerLike)
|
|
1106
|
+
```
|
|
1107
|
+
|
|
1108
|
+
| Param | Type | Description |
|
|
1109
|
+
|---|---|---|
|
|
1110
|
+
| `config` | `RedisConfigInput` | Redis configuration (validated with Zod `RedisConfigSchema`). Must include `mode` (standalone/sentinel/cluster), and topology-specific fields. |
|
|
1111
|
+
| `logger` | `LoggerLike` | Optional pino-compatible logger; defaults to `console`. |
|
|
1112
|
+
|
|
1113
|
+
Throws `ConfigurationError` when the config fails Zod validation.
|
|
1114
|
+
|
|
1115
|
+
#### Properties
|
|
1116
|
+
|
|
1117
|
+
| Property | Type | Description |
|
|
1118
|
+
|---|---|---|
|
|
1119
|
+
| `mode` | `RedisMode` | The Redis topology mode (`'standalone'`, `'sentinel'`, or `'cluster'`). |
|
|
1120
|
+
| `cache` | `Cache` | Shared Cache instance (lazily created on first access). |
|
|
1121
|
+
| `pubsub` | `PubSub` | Shared Pub/Sub instance (lazily created on first access). |
|
|
1122
|
+
| `lock` | `DistributedLock` | Shared DistributedLock instance (lazily created on first access). |
|
|
1123
|
+
| `rateLimiter` | `RateLimiter` | Shared RateLimiter instance (lazily created on first access). |
|
|
1124
|
+
| `session` | `SessionManager` | Shared SessionManager instance (lazily created on first access). |
|
|
1125
|
+
| `revocationStore` | `RedisRevocationStore` | Shared revocation store (lazily created on first access). |
|
|
1126
|
+
| `raw` | `RedisClient \| Cluster` | The raw underlying ioredis client. |
|
|
1127
|
+
|
|
1128
|
+
#### Builder-style configurators
|
|
1129
|
+
|
|
1130
|
+
These methods let you swap configuration after construction. The corresponding sub-component is reset so it picks up the new configuration on next access.
|
|
1131
|
+
|
|
1132
|
+
| Method | Description | Args | Returns |
|
|
1133
|
+
|---|---|---|---|
|
|
1134
|
+
| `withCache(value)` | Set cache configuration and reset the cache. | `value: CacheInputConfig` | `this` for chaining |
|
|
1135
|
+
| `withLock(value)` | Set lock options and reset the lock. | `value: DistributedLockInputOptions` | `this` for chaining |
|
|
1136
|
+
| `withRateLimiter(value)` | Set rate limit options and reset the limiter. | `value: RateLimitOptionsInput` | `this` for chaining |
|
|
1137
|
+
| `withSession(value)` | Merge session configuration and reset the session manager. | `value: WithSessionManagerOptions` | `this` for chaining |
|
|
1138
|
+
|
|
1139
|
+
#### Raw client access
|
|
1140
|
+
|
|
1141
|
+
| Method | Description | Args | Returns |
|
|
1142
|
+
|---|---|---|---|
|
|
1143
|
+
| `getRawClient<T>()` | Typed access to the raw ioredis client/cluster. | generic `T` defaults to `RedisClient \| Cluster` | `T` |
|
|
1144
|
+
| `get raw` | The raw underlying client (`RedisClient` or `Cluster`). | — | `RedisClient \| Cluster` |
|
|
1145
|
+
|
|
1146
|
+
#### Lifecycle
|
|
1147
|
+
|
|
1148
|
+
| Method | Description | Args | Returns |
|
|
1149
|
+
|---|---|---|---|
|
|
1150
|
+
| `ping()` | Verify Redis connectivity with PING. | — | `Promise<boolean>` — `true` when the server replied `PONG`, `false` on any error. |
|
|
1151
|
+
| `close()` | Gracefully `QUIT` the underlying client and mark the wrapper as not ready. | — | `Promise<void>` |
|
|
1152
|
+
| `getConnectionStatus()` | Snapshot of the connection state. | — | `ConnectionStatus` |
|
|
1153
|
+
| `defineCommand(...args)` | Forward to `ioredis#defineCommand` to register a custom command on the underlying client. | mirrors `ioredis` | mirrors `ioredis` |
|
|
1154
|
+
|
|
1155
|
+
#### Basic commands (string, key, counter)
|
|
1156
|
+
|
|
1157
|
+
| Method | Description | Args | Returns |
|
|
1158
|
+
|---|---|---|---|
|
|
1159
|
+
| `get(key)` | `GET` a key. | `key: string` | `Promise<string \| null>` |
|
|
1160
|
+
| `set(key, value, ttl?)` | `SET` with optional `EX` TTL. | `key: string`, `value: string \| Buffer`, `ttl?: number` (seconds) | `Promise<"OK" \| null>` |
|
|
1161
|
+
| `setexnx(key, value, ttl?)` | `SET ... EX NX` (optional TTL). | as above | `Promise<"OK" \| null>` |
|
|
1162
|
+
| `setnx(key, value, ttl?)` | `SETNX` with optional `EX` — returns `1` on success, `0` on conflict. | as above | `Promise<number>` (1 or 0) |
|
|
1163
|
+
| `getdel(key)` | `GETDEL` — return and remove. | `key: string` | `Promise<string \| null>` |
|
|
1164
|
+
| `exists(key)` | `EXISTS` — count of existing keys (0 or 1 here). | `key: string` | `Promise<number>` |
|
|
1165
|
+
| `del(...keys)` | `DEL` one or more keys. | `...keys: string[]` | `Promise<number>` — number deleted |
|
|
1166
|
+
| `expire(key, ttl)` | `EXPIRE` — set a TTL in seconds. | `key: string`, `ttl: number` | `Promise<number>` — 1 if applied, 0 if not |
|
|
1167
|
+
| `ttl(key)` | `TTL` — remaining seconds (`-2` missing, `-1` no TTL). | `key: string` | `Promise<number>` |
|
|
1168
|
+
| `incr(key)` | `INCR` — counter by 1. | `key: string` | `Promise<number>` |
|
|
1169
|
+
| `decr(key)` | `DECR` — counter by 1. | `key: string` | `Promise<number>` |
|
|
1170
|
+
| `incrby(key, amount)` | `INCRBY` — counter by `amount` (must be a positive safe integer; throws `RedisError 'INVALID_AMOUNT'` otherwise). | `key: string`, `amount: number` | `Promise<number>` |
|
|
1171
|
+
| `decrby(key, amount)` | `DECRBY` — counter by `amount` (same validation as `incrby`). | `key: string`, `amount: number` | `Promise<number>` |
|
|
1172
|
+
| `time()` | `TIME` — Redis server time (seconds portion). | — | `Promise<number>` — Unix seconds |
|
|
1173
|
+
|
|
1174
|
+
#### Multi-key commands (cluster-safe)
|
|
1175
|
+
|
|
1176
|
+
| Method | Description | Args | Returns |
|
|
1177
|
+
|---|---|---|---|
|
|
1178
|
+
| `mget(...keys)` | `MGET`; routes by hash slot in cluster mode. | `...keys: string[]` | `Promise<(string \| null)[]>` |
|
|
1179
|
+
| `mset(...pairs)` | `MSET`; grouped by hash slot in cluster mode with bounded fan-out (`maxFanOutConcurrency`). | `...pairs: Array<[string, string \| Buffer]>` | `Promise<"OK">` |
|
|
1180
|
+
| `mgetClusterAware(keys)` | Same as `mget`, but the cluster grouping is always applied (useful when the cluster branch is selected by mode narrowing). | `keys: string[]` | `Promise<(string \| null)[]>` |
|
|
1181
|
+
|
|
1182
|
+
#### Hash commands
|
|
1183
|
+
|
|
1184
|
+
| Method | Description | Args | Returns |
|
|
1185
|
+
|---|---|---|---|
|
|
1186
|
+
| `hget(key, field)` | `HGET`. | `key: string`, `field: string` | `Promise<string \| null>` |
|
|
1187
|
+
| `hset(key, field, value)` | `HSET`. | `key: string`, `field: string`, `value: string \| Buffer` | `Promise<number>` — 1 if new, 0 if updated |
|
|
1188
|
+
| `hgetall(key)` | `HGETALL`. | `key: string` | `Promise<Record<string, string>>` |
|
|
1189
|
+
| `hdel(key, ...fields)` | `HDEL`. | `key: string`, `...fields: string[]` | `Promise<number>` — number deleted |
|
|
1190
|
+
|
|
1191
|
+
#### Set commands
|
|
1192
|
+
|
|
1193
|
+
| Method | Description | Args | Returns |
|
|
1194
|
+
|---|---|---|---|
|
|
1195
|
+
| `sadd(key, ...members)` | `SADD`. | `key: string`, `...members: string[]` | `Promise<number>` — added count |
|
|
1196
|
+
| `srem(key, ...members)` | `SREM`. | `key: string`, `...members: string[]` | `Promise<number>` — removed count |
|
|
1197
|
+
| `smembers(key)` | `SMEMBERS`. | `key: string` | `Promise<string[]>` |
|
|
1198
|
+
| `sismember(key, member)` | `SISMEMBER`. | `key: string`, `member: string` | `Promise<number>` — 0 or 1 |
|
|
1199
|
+
|
|
1200
|
+
#### Sorted set commands
|
|
1201
|
+
|
|
1202
|
+
| Method | Description | Args | Returns |
|
|
1203
|
+
|---|---|---|---|
|
|
1204
|
+
| `zadd(key, score, member)` | `ZADD`. | `key: string`, `score: number`, `member: string` | `Promise<number>` — added count |
|
|
1205
|
+
| `zrange(key, start, stop)` | `ZRANGE` (legacy form, ascending). | `key: string`, `start: number`, `stop: number` | `Promise<string[]>` |
|
|
1206
|
+
| `zcard(key)` | `ZCARD`. | `key: string` | `Promise<number>` |
|
|
1207
|
+
| `zrem(key, ...members)` | `ZREM`. | `key: string`, `...members: string[]` | `Promise<number>` — removed count |
|
|
1208
|
+
|
|
1209
|
+
#### Pipelines and scanning
|
|
1210
|
+
|
|
1211
|
+
| Method | Description | Args | Returns |
|
|
1212
|
+
|---|---|---|---|
|
|
1213
|
+
| `pipeline()` | Returns a new ioredis pipeline (keys in a pipeline must share one hash slot in cluster mode). | — | `Pipeline` |
|
|
1214
|
+
| `scanIterator(pattern, count?)` | Cluster-safe async iterator over keys matching `pattern`. | `pattern: string`, `count?: number` (default 100) | `AsyncIterable<string>` |
|
|
1215
|
+
| `scanCluster(pattern, options?)` | Cluster-safe async iterator yielding batches of matching keys. | `pattern: string`, `options?: { count?, batchSize? }` | `AsyncIterable<string[]>` |
|
|
1216
|
+
| `deletePattern(pattern, options?)` | SCAN every node, then `DEL` matches in slot-grouped pipelines. | `pattern: string`, `options?: { batchSize?, scanCount? }` | `Promise<number>` — number deleted |
|
|
1217
|
+
| `clearNamespace(prefix, options?)` | Alias of `deletePattern(${prefix}*)`. | `prefix: string`, `options?: DeletePatternOptions` | `Promise<number>` |
|
|
1218
|
+
| `clearNamespaceClusterAware(prefix, options?)` | Cluster-aware clear (internally calls `clearNamespace`). | as above | `Promise<number>` |
|
|
1219
|
+
|
|
1220
|
+
#### Lua scripts
|
|
1221
|
+
|
|
1222
|
+
| Method | Description | Args | Returns |
|
|
1223
|
+
|---|---|---|---|
|
|
1224
|
+
| `eval(script, numKeys, ...args)` | `EVAL` — first `numKeys` are `KEYS`, the rest are `ARGV`. | `script: string`, `numKeys: number`, `...args: RedisCommandArgument[]` | `Promise<unknown>` |
|
|
1225
|
+
| `evalsha(sha, script, numKeys, ...args)` | `EVALSHA` with automatic `EVAL` fallback on `NOSCRIPT`. | `sha: string`, `script: string`, `numKeys: number`, `...args: RedisCommandArgument[]` | `Promise<unknown>` |
|
|
1226
|
+
| `scriptLoad(script)` | `SCRIPT LOAD`. | `script: string` | `Promise<string>` — the SHA1 |
|
|
1227
|
+
|
|
1228
|
+
#### Cluster helpers (cluster mode only)
|
|
1229
|
+
|
|
1230
|
+
| Method | Description | Args | Returns |
|
|
1231
|
+
|---|---|---|---|
|
|
1232
|
+
| `isCluster()` | Is the underlying client a Cluster? | — | `boolean` |
|
|
1233
|
+
| `getClusterNodes()` | Raw master node clients. | — | `RedisClient[]` (empty for non-cluster) |
|
|
1234
|
+
| `getClusterSlots()` | `CLUSTER SLOTS` parsed into structured slot ranges. | — | `Promise<ClusterSlotRange[]>` |
|
|
1235
|
+
| `getSlotRanges()` | `Map<slot, host:port[]>` for every slot. | — | `Promise<Map<number, string[]>>` |
|
|
1236
|
+
| `calculateSlot(key)` | CRC16 hash slot for a key (honors `{hash tags}`). | `key: string` | `number` (0..16383) |
|
|
1237
|
+
| `getNodeForKey(key)` | The Redis client owning the key's slot, or `null`. | `key: string` | `Promise<RedisClient \| null>` |
|
|
1238
|
+
| `isKeyServed(key)` | Whether the cluster currently serves the key's slot. | `key: string` | `Promise<boolean>` — `true` outside cluster mode |
|
|
1239
|
+
| `executeOnNode(key, command, ...args)` | Run an arbitrary command on the node owning `key` (or the single client outside cluster mode). | `key: string`, `command: string`, `...args: unknown[]` | `Promise<T>` |
|
|
1240
|
+
| `mgetClusterAware(keys)` | Slot-grouped multi-get (always applies the grouping). | `keys: string[]` | `Promise<(string \| null)[]>` |
|
|
1241
|
+
| `clearNamespaceClusterAware(prefix, options?)` | Cluster-aware namespace wipe. | `prefix: string`, `options?: DeletePatternOptions` | `Promise<number>` |
|
|
1242
|
+
| `getClusterInfo()` | Snapshot of the topology and node list. | — | `ClusterInfo` |
|
|
1243
|
+
|
|
1244
|
+
#### Server info and database selection
|
|
1245
|
+
|
|
1246
|
+
| Method | Description | Args | Returns |
|
|
1247
|
+
|---|---|---|---|
|
|
1248
|
+
| `info(section?)` | `INFO` (full or per-section). | `section?: string` | `Promise<string>` |
|
|
1249
|
+
| `select(database)` | `SELECT`. Throws `RedisError 'CLUSTER_MODE'` in cluster mode; throws `RedisError 'INVALID_DATABASE'` when `database` is not an integer in `[0, 15]`. | `database: number` | `Promise<"OK">` |
|
|
1250
|
+
|
|
1251
|
+
#### Internal helpers (private)
|
|
1252
|
+
|
|
1253
|
+
| Method | Description |
|
|
1254
|
+
|---|---|
|
|
1255
|
+
| `exec<T>(command, args, operation)` | Wraps a Redis call with timing/logging. Logs slow commands above `slowCommandThreshold`. |
|
|
1256
|
+
| `isClusterClient(client)` | Type guard for `Cluster`. |
|
|
1257
|
+
| `runWithConcurrency(items, concurrency, worker)` | Bounded-fan-out helper. |
|
|
1258
|
+
| `executeCommandOnClient<T>(client, command, args)` | Reflectively invoke a method on a client. |
|
|
1259
|
+
|
|
1260
|
+
### `Cache`
|
|
1261
|
+
|
|
1262
|
+
#### Constructor
|
|
1263
|
+
|
|
1264
|
+
```ts
|
|
1265
|
+
new Cache(client: RedisClientWrapper, config: CacheInputConfig, logger?: LoggerLike)
|
|
1266
|
+
```
|
|
1267
|
+
|
|
1268
|
+
| Param | Type | Description |
|
|
1269
|
+
|---|---|---|
|
|
1270
|
+
| `client` | `RedisClientWrapper` | The underlying client. |
|
|
1271
|
+
| `config` | `CacheInputConfig` | `{ defaultTTL?, compressionThreshold?, namespace? }`. |
|
|
1272
|
+
| `logger` | `LoggerLike` | Optional pino-compatible logger; defaults to `console`. |
|
|
1273
|
+
|
|
1274
|
+
#### Internal helpers (private)
|
|
1275
|
+
|
|
1276
|
+
| Method | Description |
|
|
1277
|
+
|---|---|
|
|
1278
|
+
| `serialize<T>(value)` | Buffer-ify, then gzip if larger than `compressionThreshold`. Returns `{ data, compressed }`. |
|
|
1279
|
+
| `deserialize<T>(data, compressed)` | Inverse of `serialize` — gunzip if needed, JSON-parse when possible. |
|
|
1280
|
+
| `getKey(key, namespace?)` | Build the final Redis key with the configured/per-call namespace prefix. |
|
|
1281
|
+
| `get getNamespace` | Get the configured namespace prefix with trailing `:`. |
|
|
1282
|
+
|
|
1283
|
+
#### Methods
|
|
1284
|
+
|
|
1285
|
+
See the [Cache](#cache-1) section above for the full method table.
|
|
1286
|
+
|
|
1287
|
+
### `PubSub`
|
|
1288
|
+
|
|
1289
|
+
#### Constructor
|
|
1290
|
+
|
|
1291
|
+
```ts
|
|
1292
|
+
new PubSub(publisher: RedisClientWrapper, logger?: LoggerLike)
|
|
1293
|
+
```
|
|
1294
|
+
|
|
1295
|
+
| Param | Type | Description |
|
|
1296
|
+
|---|---|---|
|
|
1297
|
+
| `publisher` | `RedisClientWrapper` | A client used for publishing. |
|
|
1298
|
+
| `logger` | `LoggerLike` | Optional pino-compatible logger; defaults to `console`. |
|
|
1299
|
+
|
|
1300
|
+
#### Internal helpers (private)
|
|
1301
|
+
|
|
1302
|
+
| Method | Description |
|
|
1303
|
+
|---|---|
|
|
1304
|
+
| `setupSubscriber()` | Wires `message`/`pmessage`/`error` listeners on the subscriber client. |
|
|
1305
|
+
| `handleMessage(channel, message)` | Dispatches a standard message to registered handlers (with JSON parse + per-handler try/catch). |
|
|
1306
|
+
| `handlePatternMessage(pattern, channel, message)` | Same as `handleMessage` for pattern subscriptions. |
|
|
1307
|
+
|
|
1308
|
+
#### Methods
|
|
1309
|
+
|
|
1310
|
+
See the [Pub/Sub](#pubsub-1) section above for the full method table.
|
|
1311
|
+
|
|
1312
|
+
### `DistributedLock`
|
|
1313
|
+
|
|
1314
|
+
#### Constructor
|
|
1315
|
+
|
|
1316
|
+
```ts
|
|
1317
|
+
new DistributedLock(client: RedisClientWrapper, logger?: LoggerLike, options?: Partial<DistributedLockOptions>)
|
|
1318
|
+
```
|
|
1319
|
+
|
|
1320
|
+
| Param | Type | Default | Description |
|
|
1321
|
+
|---|---|---|---|
|
|
1322
|
+
| `client` | `RedisClientWrapper` | — | The underlying client. |
|
|
1323
|
+
| `logger` | `LoggerLike` | `defaultLogger` | Optional pino-compatible logger. |
|
|
1324
|
+
| `options.ttl` | `number` | `30000` | Lock TTL in milliseconds. |
|
|
1325
|
+
| `options.retryCount` | `number` | `3` | Acquisition attempts. |
|
|
1326
|
+
| `options.retryDelay` | `number` | `200` | Base delay (exponential, with jitter) between attempts. |
|
|
1327
|
+
|
|
1328
|
+
#### Internal helpers (private)
|
|
1329
|
+
|
|
1330
|
+
| Method | Description |
|
|
1331
|
+
|---|---|
|
|
1332
|
+
| `getLockKey(key)` | Build the Redis key (`lock:{key}`). |
|
|
1333
|
+
| `generateLockId()` | 16 random bytes as hex. |
|
|
1334
|
+
| `executeWithRetry(fn, retryCount, retryDelay)` | Exponential backoff with 0.5–1.0 jitter. |
|
|
1335
|
+
|
|
1336
|
+
#### Methods
|
|
1337
|
+
|
|
1338
|
+
See the [DistributedLock](#distributedlock) section above for the full method table.
|
|
1339
|
+
|
|
1340
|
+
### `RateLimiter`
|
|
1341
|
+
|
|
1342
|
+
#### Constructor
|
|
1343
|
+
|
|
1344
|
+
```ts
|
|
1345
|
+
new RateLimiter(client: RedisClientWrapper, options?: RateLimitOptionsInput, logger?: LoggerLike)
|
|
1346
|
+
```
|
|
1347
|
+
|
|
1348
|
+
| Param | Type | Default | Description |
|
|
1349
|
+
|---|---|---|---|
|
|
1350
|
+
| `client` | `RedisClientWrapper` | — | The underlying client. |
|
|
1351
|
+
| `options.limit` | `number` | `100` | Max requests per window. |
|
|
1352
|
+
| `options.duration` | `number` | `60` | Window length in seconds. |
|
|
1353
|
+
| `options.algorithm` | `'fixed' \| 'sliding'` | `'sliding'` | Window algorithm. |
|
|
1354
|
+
| `options.namespace` | `string` | `'ratelimit'` | Key prefix. |
|
|
1355
|
+
| `logger` | `LoggerLike` | `defaultLogger` | Optional pino-compatible logger. |
|
|
1356
|
+
|
|
1357
|
+
#### Internal helpers (private)
|
|
1358
|
+
|
|
1359
|
+
| Method | Description |
|
|
1360
|
+
|---|---|
|
|
1361
|
+
| `consumeFixed(key, limit, duration)` | Fixed-window: `INCR` + `EXPIRE` on first hit. |
|
|
1362
|
+
| `consumeSliding(key, limit, duration)` | Sliding-window via atomic Lua over a sorted set. |
|
|
1363
|
+
| `checkFixed(key, limit, duration)` | Fixed-window peek. |
|
|
1364
|
+
| `checkSliding(key, limit, duration)` | Sliding-window peek. |
|
|
1365
|
+
|
|
1366
|
+
#### Methods
|
|
1367
|
+
|
|
1368
|
+
See the [RateLimiter](#ratelimiter-1) section above for the full method table.
|
|
1369
|
+
|
|
1370
|
+
### `HealthChecker`
|
|
1371
|
+
|
|
1372
|
+
#### Constructor
|
|
1373
|
+
|
|
1374
|
+
```ts
|
|
1375
|
+
new HealthChecker(client: RedisClientWrapper, logger?: LoggerLike)
|
|
1376
|
+
```
|
|
1377
|
+
|
|
1378
|
+
| Param | Type | Description |
|
|
1379
|
+
|---|---|---|
|
|
1380
|
+
| `client` | `RedisClientWrapper` | The underlying client. |
|
|
1381
|
+
| `logger` | `LoggerLike` | Optional pino-compatible logger; defaults to `console`. |
|
|
1382
|
+
|
|
1383
|
+
#### Internal helpers (private)
|
|
1384
|
+
|
|
1385
|
+
| Method | Description |
|
|
1386
|
+
|---|---|
|
|
1387
|
+
| `notifyCallbacks(status)` | Fire every registered callback with try/catch isolation. |
|
|
1388
|
+
|
|
1389
|
+
#### Methods
|
|
1390
|
+
|
|
1391
|
+
See the [HealthChecker](#healthchecker) section above for the full method table.
|
|
1392
|
+
|
|
1393
|
+
### `RedisRevocationStore`
|
|
1394
|
+
|
|
1395
|
+
#### Constructor
|
|
1396
|
+
|
|
1397
|
+
```ts
|
|
1398
|
+
new RedisRevocationStore(options: RedisRevocationStoreOptions)
|
|
1399
|
+
```
|
|
1400
|
+
|
|
1401
|
+
| Param | Type | Description |
|
|
1402
|
+
|---|---|---|
|
|
1403
|
+
| `options.client` | `RedisClientWrapper` | The underlying client. |
|
|
1404
|
+
| `options.keyPrefix` | `string` | Key prefix (default `'cache:revoked:'`). |
|
|
1405
|
+
|
|
1406
|
+
#### Internal helpers (private)
|
|
1407
|
+
|
|
1408
|
+
| Method | Description |
|
|
1409
|
+
|---|---|
|
|
1410
|
+
| `key(jti)` | Build the full Redis key (`{prefix}{jti}`). |
|
|
1411
|
+
|
|
1412
|
+
#### Methods
|
|
1413
|
+
|
|
1414
|
+
See the [RedisRevocationStore](#redisrevocationstore) section above for the full method table.
|
|
1415
|
+
|
|
1416
|
+
### Slot / cluster-slot helpers (`src/cluster-slot.ts`)
|
|
1417
|
+
|
|
1418
|
+
| Export | Signature | Description |
|
|
1419
|
+
|---|---|---|
|
|
1420
|
+
| `hashTag(key)` | `(key: string) => string` | Extract the `{...}` hash tag from a key, or return the key when no tag is present. |
|
|
1421
|
+
| `calculateRedisClusterSlot(key)` | `(key: string) => number` | CRC16-CCITT/XMODEM over the hash-tagged key bytes, `crc % 16384`. Honors `{hash tags}`. |
|
|
1422
|
+
|
|
1423
|
+
### Cluster fan-out helpers (`src/cluster.ts`)
|
|
1424
|
+
|
|
1425
|
+
| Export | Signature | Description |
|
|
1426
|
+
|---|---|---|
|
|
1427
|
+
| `PipelineCommand` | interface `{ command, args, slot }` | A single queued pipeline command with its slot precomputed. |
|
|
1428
|
+
| `PipelineCommandResult` | type `[Error \| null, unknown]` | A pipeline result. |
|
|
1429
|
+
| `ExecuteBySlotOptions` | interface `{ concurrency?, retry? }` | Tuning for `executeBySlot`. |
|
|
1430
|
+
| `executeBySlot(client, commands, options?)` | `(client, commands: PipelineCommand[], options?) => Promise<PipelineCommandResult[]>` | Group commands by slot, run one pipeline per slot with bounded concurrency, retry network-level slot-pipeline failures. Result order matches the input order. |
|
|
1431
|
+
| `assertPipelineOk(results, describe?)` | `(results, describe?) => unknown[]` | Throws a structured `Error` listing failed command indexes when any pipeline command returned an error; returns the values otherwise. |
|
|
1432
|
+
| `mapWithConcurrency(items, limit, fn)` | `<T,R>(items, limit, fn) => Promise<R[]>` | Bounded-concurrency async map. |
|
|
1433
|
+
| `chunk(items, size)` | `<T>(items, size) => Generator<T[]>` | Bounded batch chunker. |
|
|
1434
|
+
|
|
1435
|
+
### Logger types (`src/logger.ts`)
|
|
1436
|
+
|
|
1437
|
+
| Export | Description |
|
|
1438
|
+
|---|---|
|
|
1439
|
+
| `LogMeta` | `Record<string, unknown>` — structured log metadata. |
|
|
1440
|
+
| `LoggerLike` | Interface matching pino's `trace/debug/info/warn/error/fatal` + `child()`. |
|
|
1441
|
+
| `defaultLogger` | A `ConsoleLogger` using `console.*` methods. |
|
|
1442
|
+
| `createConsoleLogger(bindings?)` | Factory for a `ConsoleLogger` with pre-bound metadata. |
|
|
1443
|
+
|
|
1444
|
+
### Error types (`src/errors.ts`)
|
|
1445
|
+
|
|
1446
|
+
| Class | Code | When |
|
|
1447
|
+
|---|---|---|
|
|
1448
|
+
| `RedisError` | configurable | Base error for the toolkit. |
|
|
1449
|
+
| `ConnectionError` | `CONNECTION_ERROR` | Underlying connection issues. |
|
|
1450
|
+
| `TimeoutError` | `TIMEOUT_ERROR` | Operation timeout. |
|
|
1451
|
+
| `SessionExpiredError` | `AUTH_SESSION_EXPIRED` | Session referenced by a token no longer exists or has expired. |
|
|
1452
|
+
| `LockError` | `LOCK_ERROR` | Distributed lock error. |
|
|
1453
|
+
| `SerializationError` | `SERIALIZATION_ERROR` | Cache / payload serialization error. |
|
|
1454
|
+
| `CompressionError` | `COMPRESSION_ERROR` | Cache compression error. |
|
|
1455
|
+
| `ConfigurationError` | `CONFIGURATION_ERROR` | Invalid config (e.g. Zod failure). |
|
|
1456
|
+
| `ClusterError` | `CLUSTER_ERROR` | Cluster topology error. |
|
|
1457
|
+
|
|
1458
|
+
### Session types (`src/session/`)
|
|
1459
|
+
|
|
1460
|
+
See [`src/session/README.md`](src/session/README.md) for the complete session reference. Highlights:
|
|
1461
|
+
|
|
1462
|
+
| Export | Description |
|
|
1463
|
+
|---|---|
|
|
1464
|
+
| `createSessionManager` | Build a `SessionManager` (synchronous). |
|
|
1465
|
+
| `SessionManager` | Composition root; exposes `service`, `repository`, `metrics`, `health`, `circuitBreaker`, `cookies`, `token`, `keys`, `init()`, `close()`. |
|
|
1466
|
+
| `SessionService` | Application-facing API: `create`, `validate`, `touch`, `rotate`, `update`, `destroy`, `revoke`, `revokeAll`, `deleteByUser`, `findByUser`, `list`, `setSecurityVersion`, `getSecurityVersion`, `reconcileUser`, `health`. |
|
|
1467
|
+
| `SessionRepository` | Low-level Redis I/O. |
|
|
1468
|
+
| `SessionTokenManager` | Token + jti management (`generate`, `generateNonce`, `hash`, `validateFormat`, `safeEquals`, `tokenToJti`). |
|
|
1469
|
+
| `SessionKeyStrategy` | Cluster-safe key layout (`sessionKey`, `userIndexKey`, `securityVersionKey`, `createClaimKey`, `jtiIndexKey`, `revokedKey`, `sessionKeyPrefix`, `familyHeadKeyPrefix`, `namespacePrefix`). |
|
|
1470
|
+
| `SessionMetrics` | Internal metrics facade (`operation`, `latency`, `breakerState`, `revocationMiss`, `encryptionError`, `jtiIndexWriteFailure`, `reconcileUser`). |
|
|
1471
|
+
| `SessionMetricsAdapter` | Application-provided metrics sink. |
|
|
1472
|
+
| `SessionCircuitBreaker` | Fail-closed breaker (`state`, `run`, `tryAcquire`, `recordSuccess`, `recordFailure`, `reset`). |
|
|
1473
|
+
| `SessionHealthChecker` | PING + sliding-window error rate (`recordOp`, `check`). |
|
|
1474
|
+
| `SessionCookieManager` | `name`, `serialize`, `serializeWithAttributes`, `clear`, `parse`. |
|
|
1475
|
+
| `SessionKeyProvider` | `getCurrentKey` / `getKey` for encryption. |
|
|
1476
|
+
| `StaticSessionKeyProvider` | In-memory map of versions to 32-byte keys. |
|
|
1477
|
+
| `createRandomSessionKeyProvider` | Convenience: a single random 32-byte key. |
|
|
1478
|
+
| `serializeSession` / `serializeEncryptedSession` / `deserializeSession` / `validateSessionRecord` | (De)serialization helpers. |
|
|
1479
|
+
| `parseSessionConfig` / `redactSessionConfig` | Config helpers. |
|
|
1480
|
+
| `TTL` / `IDLE_TIMEOUT` / `TOUCH_INTERVAL` | Default values (7d, 24h, 5m). |
|
|
1481
|
+
| Session error classes | `SessionError`, `SessionNotFoundError`, `SessionExpiredError`, `SessionRevokedError`, `SessionInvalidError`, `SessionRotationError`, `SessionReplayError`, `SessionStorageError`, `SessionSerializationError`, `SessionConfigurationError`, `SessionConcurrencyError`, `RevocationError`, `RevocationBatchError`, `CircuitBreakerOpenError`. |
|
|
1482
|
+
| `redactIdentifier(value)` | Safe-to-log identifier redaction. |
|
|
1483
|
+
|
|
1484
|
+
### Public types catalog
|
|
1485
|
+
|
|
1486
|
+
#### Core client types
|
|
1487
|
+
|
|
1488
|
+
| Type | Description |
|
|
1489
|
+
|---|---|
|
|
1490
|
+
| `RedisClientWrapper` | The unified client wrapper. |
|
|
1491
|
+
| `RedisClient` (alias `RedisClientForMode`) | The unified client, narrowed per topology. |
|
|
1492
|
+
| `createRedisClient` | Factory function: `createRedisClient(config)` — creates a client for the specified mode. |
|
|
1493
|
+
| `ClusterCapabilities` | Cluster-only methods available on cluster clients. |
|
|
1494
|
+
| `RedisConfig` | Normalized configuration (after Zod validation). |
|
|
1495
|
+
| `RedisConfigInput` | User-facing configuration input (validated with Zod). |
|
|
1496
|
+
| `RedisMode` | `'standalone' \| 'sentinel' \| 'cluster'`. |
|
|
1497
|
+
| `RedisConfigForMode<M>` | Mode-specific config type. |
|
|
1498
|
+
| `RedisCommonConfig` | Common config shared by all topologies. |
|
|
1499
|
+
| `RedisCommonConfigInput` | User-input shape for common config. |
|
|
1500
|
+
| `StandaloneRedisConfig` / `StandaloneRedisConfigInput` | Standalone-specific config. |
|
|
1501
|
+
| `SentinelRedisConfig` / `SentinelRedisConfigInput` | Sentinel-specific config. |
|
|
1502
|
+
| `ClusterRedisConfig` / `ClusterRedisConfigInput` | Cluster-specific config. |
|
|
1503
|
+
| `RedisConfigInputSchema` | Zod union schema for input config. |
|
|
1504
|
+
| `BaseRedisConfigSchema` | Base Zod schema (password, username, database, tls, etc.). |
|
|
1505
|
+
| `RedisTlsOptions` / `RedisTlsOptionsInput` | TLS settings (CA / cert / key / `rejectUnauthorized`). |
|
|
1506
|
+
| `RedisNode` / `RedisNodeSchema` | `{ host, port, nodeId? }` for cluster/sentinel nodes. |
|
|
1507
|
+
| `Redis` | Alias for the raw `ioredis` `Redis` type. |
|
|
1508
|
+
|
|
1509
|
+
#### Cache types
|
|
1510
|
+
|
|
1511
|
+
| Type | Description |
|
|
1512
|
+
|---|---|
|
|
1513
|
+
| `Cache` | Cache class. |
|
|
1514
|
+
| `CacheOptions` | `{ ttl?, compress?, namespace? }` per-call options. |
|
|
1515
|
+
| `CacheInputConfig` | `{ defaultTTL?, compressionThreshold?, namespace? }` constructor config. |
|
|
1516
|
+
| `CacheStats` | `{ namespace, connectionStatus }`. |
|
|
1517
|
+
| `CacheOptionsSchema` | Zod schema for cache options. |
|
|
1518
|
+
|
|
1519
|
+
#### Lock types
|
|
1520
|
+
|
|
1521
|
+
| Type | Description |
|
|
1522
|
+
|---|---|
|
|
1523
|
+
| `DistributedLock` | Lock class. |
|
|
1524
|
+
| `DistributedLockOptions` | `{ ttl?, retryCount?, retryDelay? }`. |
|
|
1525
|
+
| `DistributedLockOptionsSchema` | Zod schema for lock options. |
|
|
1526
|
+
| `DistributedLockInputOptions` | Pre-default Zod input type. |
|
|
1527
|
+
| `LockInfo` | `{ locked, ttl?, lockId? }`. |
|
|
1528
|
+
|
|
1529
|
+
#### Rate limit types
|
|
1530
|
+
|
|
1531
|
+
| Type | Description |
|
|
1532
|
+
|---|---|
|
|
1533
|
+
| `RateLimiter` | Limiter class. |
|
|
1534
|
+
| `RateLimitAlgorithm` | `'fixed' \| 'sliding'`. |
|
|
1535
|
+
| `RateLimitOptions` | `{ limit?, duration?, algorithm?, namespace? }` for instance/call. |
|
|
1536
|
+
| `RateLimitOptionsInput` | Pre-default Zod input type. |
|
|
1537
|
+
| `RateLimitOptionsSchema` | Zod schema for rate-limit options. |
|
|
1538
|
+
| `RateLimitResult` | `{ allowed, limit, used, remaining, resetAt, retryAfter }`. |
|
|
1539
|
+
| `RateLimitAlgorithmSchema` | Zod schema for the algorithm literal. |
|
|
1540
|
+
|
|
1541
|
+
#### Pub/Sub types
|
|
1542
|
+
|
|
1543
|
+
| Type | Description |
|
|
1544
|
+
|---|---|
|
|
1545
|
+
| `PubSub` | Pub/Sub class. |
|
|
1546
|
+
| `PubSubMessage<T>` | `{ channel, message }`. |
|
|
1547
|
+
| `PubSubStats` | `{ subscriptions, patternSubscriptions, connected }`. |
|
|
1548
|
+
| `PubSubEventMap` | Event payload map for `EventEmitter` typing. |
|
|
1549
|
+
|
|
1550
|
+
#### Health types
|
|
1551
|
+
|
|
1552
|
+
| Type | Description |
|
|
1553
|
+
|---|---|
|
|
1554
|
+
| `HealthStatus` | `{ healthy, status, latency, timestamp, details }`. |
|
|
1555
|
+
| `HealthChecker` | Checker class. |
|
|
1556
|
+
|
|
1557
|
+
#### Cluster types
|
|
1558
|
+
|
|
1559
|
+
| Type | Description |
|
|
1560
|
+
|---|---|
|
|
1561
|
+
| `ClusterInfo` | `{ mode, status, nodeCount?, slotCount?, nodes?, host?, port?, error? }`. |
|
|
1562
|
+
| `ClusterSlotRange` | `{ start, end, master, replicas }`. |
|
|
1563
|
+
| `ClusterSlotNode` | `{ host, port, nodeId? }`. |
|
|
1564
|
+
|
|
1565
|
+
#### Connection types
|
|
1566
|
+
|
|
1567
|
+
| Type | Description |
|
|
1568
|
+
|---|---|
|
|
1569
|
+
| `ConnectionState` | `'disconnected' \| 'connecting' \| 'connected' \| 'error' \| 'closed'`. |
|
|
1570
|
+
| `ConnectionStatus` | `{ state, connected, ready, lastError?, reconnectAttempts, uptime }`. |
|
|
1571
|
+
| `RedisEventMap` | Event map for the underlying client. |
|
|
1572
|
+
|
|
1573
|
+
#### Session types (exported at root)
|
|
1574
|
+
|
|
1575
|
+
| Type | Description |
|
|
1576
|
+
|---|---|
|
|
1577
|
+
| `SessionManager` | Composition root. |
|
|
1578
|
+
| `SessionManagerOptions` | `{ client, config?, encryptionKeyProvider?, revocationStore?, metricsAdapter?, circuitBreaker?, now? }`. |
|
|
1579
|
+
| `WithSessionManagerOptions` | `{ config?, encryptionKeyProvider?, metricsAdapter?, now? }` (for `withSession`). |
|
|
1580
|
+
| `SessionService` | Application-facing session API. |
|
|
1581
|
+
| `SessionServiceDeps` | Service dependencies. |
|
|
1582
|
+
| `SessionRepository` | Low-level Redis I/O. |
|
|
1583
|
+
| `SessionKeyStrategy` | Key layout. |
|
|
1584
|
+
| `SessionTokenManager` | Token + jti. |
|
|
1585
|
+
| `SessionMetrics` | Internal metrics. |
|
|
1586
|
+
| `SessionMetricsAdapter` | Application-provided metrics sink. |
|
|
1587
|
+
| `SessionCircuitBreaker` | Fail-closed breaker. |
|
|
1588
|
+
| `CircuitBreakerState` | `'closed' \| 'open' \| 'half_open'`. |
|
|
1589
|
+
| `SessionHealthChecker` | Health check. |
|
|
1590
|
+
| `SessionHealthStatus` | `{ healthy, latencyMs, errorRate, reachable, checkedAt }`. |
|
|
1591
|
+
| `SessionCookieManager` | Cookie helper. |
|
|
1592
|
+
| `SerializeCookieOptions` | `serialize` options. |
|
|
1593
|
+
| `SerializedCookie` | `{ header, name, value, attributes }`. |
|
|
1594
|
+
| `SerializedCookieAttributes` | `{ path, domain?, httpOnly, secure, sameSite, maxAge? }`. |
|
|
1595
|
+
| `SessionConfig` | Normalized session configuration. |
|
|
1596
|
+
| `SessionConfigInput` | Pre-default Zod input type. |
|
|
1597
|
+
| `PartialSessionConfig` | Partial pre-default config. |
|
|
1598
|
+
| `SessionRecord` | Persisted session record. |
|
|
1599
|
+
| `SessionCreateInput` | Input for `create()`. |
|
|
1600
|
+
| `SessionUpdatePatch` | Mutable fields for `update()`. |
|
|
1601
|
+
| `CreatedSession` | Result of `create()`. |
|
|
1602
|
+
| `RotatedSession` | Result of `rotate()`. |
|
|
1603
|
+
| `SessionValidationResult` | Result of `validate()`. |
|
|
1604
|
+
| `SessionInvalidReason` | Invalid reason discriminant. |
|
|
1605
|
+
| `TouchOutcome` | Touch outcome codes. |
|
|
1606
|
+
| `SessionEnvelope` | `PlainSessionEnvelope \| EncryptedSessionEnvelope`. |
|
|
1607
|
+
| `EncryptedSessionEnvelope` | AES-256-GCM envelope. |
|
|
1608
|
+
| `PlainSessionEnvelope` | JSON envelope (`v: 1`). |
|
|
1609
|
+
| `ListOptions` | `findByUser`/`list` options. |
|
|
1610
|
+
| `RotateOptions` | `rotate()` options. |
|
|
1611
|
+
| `TouchOptions` | `touch()` options. |
|
|
1612
|
+
| `UpdateOptions` | `update()` options. |
|
|
1613
|
+
| `ValidateOptions` | `validate()` options. |
|
|
1614
|
+
| `BindingMismatch` | Binding mismatch details. |
|
|
1615
|
+
| `SessionStatus` | `'active' \| 'consumed' \| 'revoked'`. |
|
|
1616
|
+
| `RevocationRecord` | Revocation record. |
|
|
1617
|
+
| `RevocationStore` | Storage-agnostic revocation interface. |
|
|
1618
|
+
| `SessionKeyProvider` | Encryption key provider. |
|
|
1619
|
+
| `SessionKeyProvider` | Re-exported from `session-encryption.ts`. |
|
|
1620
|
+
|
|
1621
|
+
#### Revocation store types
|
|
1622
|
+
|
|
1623
|
+
| Type | Description |
|
|
1624
|
+
|---|---|
|
|
1625
|
+
| `RedisRevocationStore` | Redis-backed revocation store. |
|
|
1626
|
+
| `RedisRevocationStoreOptions` | `{ client, keyPrefix? }`. |
|
|
1627
|
+
| `RedisRevocationStoreOptionsSchema` | Zod schema. |
|
|
1628
|
+
| `RedisRevocationStoreOptionsInput` | Pre-default Zod input type. |
|
|
1629
|
+
|
|
1630
|
+
#### Configuration exports
|
|
1631
|
+
|
|
1632
|
+
| Export | Description |
|
|
1633
|
+
|---|---|
|
|
1634
|
+
| `RedisConfigSchema` | Full Zod schema for `RedisConfig` (with `.transform` for `mode: 'standalone'` default). |
|
|
1635
|
+
| `parseSessionConfig` | Validate + apply defaults to a `PartialSessionConfig`. |
|
|
1636
|
+
| `redactSessionConfig` | Returns a redacted copy of a `SessionConfig`. |
|
|
1637
|
+
| `TTL` / `IDLE_TIMEOUT` / `TOUCH_INTERVAL` | Session config defaults. |
|
|
1638
|
+
|
|
1639
|
+
#### Utility exports
|
|
1640
|
+
|
|
1641
|
+
| Export | Description |
|
|
1642
|
+
|---|---|
|
|
1643
|
+
| `RedisError` | Base Redis error. |
|
|
1644
|
+
| `calculateRedisClusterSlot` | CRC16 slot calculation. |
|
|
1645
|
+
| `hashTag` | Hash-tag extraction. |
|
|
1646
|
+
| `RedisConfiguration` | Alias of `RedisConfig`. |
|
|
1647
|
+
| `Redis` | The raw `ioredis` type. |
|
|
1648
|
+
| `default` | Default export: `{ RedisClient, createRedisClient, Cache, PubSub, DistributedLock, HealthChecker, RateLimiter }`. |
|
|
1649
|
+
|
|
1095
1650
|
<a name="changelog"></a>
|
|
1096
1651
|
## Changelog
|
|
1097
1652
|
|
|
1098
1653
|
See [CHANGELOG.md](CHANGELOG.md) for recent changes.
|
|
1099
1654
|
|
|
1100
1655
|
---
|
|
1101
|
-
*Generated with ioredis-toolkit v0.0.
|
|
1656
|
+
*Generated with ioredis-toolkit v0.0.5*
|