@venizia/ignis-docs 0.2.0 → 0.2.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 +14 -14
- package/content/best-practices/api-usage-examples.md +39 -19
- package/content/best-practices/architectural-patterns.md +22 -11
- package/content/best-practices/architecture-decisions.md +29 -16
- package/content/best-practices/code-style-standards/advanced-patterns.md +43 -31
- package/content/best-practices/code-style-standards/constants-configuration.md +19 -4
- package/content/best-practices/code-style-standards/control-flow.md +33 -1
- package/content/best-practices/code-style-standards/documentation.md +28 -8
- package/content/best-practices/code-style-standards/function-patterns.md +15 -4
- package/content/best-practices/code-style-standards/index.md +7 -2
- package/content/best-practices/code-style-standards/naming-conventions.md +26 -2
- package/content/best-practices/code-style-standards/route-definitions.md +9 -5
- package/content/best-practices/code-style-standards/tooling.md +14 -1
- package/content/best-practices/code-style-standards/type-safety.md +39 -6
- package/content/best-practices/common-pitfalls.md +59 -35
- package/content/best-practices/contribution-workflow.md +6 -2
- package/content/best-practices/data-modeling.md +78 -62
- package/content/best-practices/deployment-strategies.md +56 -19
- package/content/best-practices/error-handling.md +182 -93
- package/content/best-practices/index.md +6 -0
- package/content/best-practices/performance-optimization.md +26 -13
- package/content/best-practices/security-guidelines.md +35 -9
- package/content/best-practices/testing-strategies.md +7 -2
- package/content/best-practices/troubleshooting-tips.md +27 -17
- package/content/extensions/components/api-reference.md +107 -322
- package/content/extensions/components/authentication/api.md +454 -603
- package/content/extensions/components/authentication/errors.md +121 -498
- package/content/extensions/components/authentication/index.md +88 -801
- package/content/extensions/components/authentication/usage.md +207 -956
- package/content/extensions/components/authorization/api.md +736 -656
- package/content/extensions/components/authorization/errors.md +168 -206
- package/content/extensions/components/authorization/index.md +82 -797
- package/content/extensions/components/authorization/usage.md +194 -527
- package/content/extensions/components/health-check.md +71 -243
- package/content/extensions/components/mail/api.md +504 -287
- package/content/extensions/components/mail/errors.md +73 -61
- package/content/extensions/components/mail/index.md +96 -467
- package/content/extensions/components/mail/usage.md +130 -172
- package/content/extensions/components/request-tracker.md +66 -173
- package/content/extensions/components/socket-io/api.md +195 -13
- package/content/extensions/components/socket-io/errors.md +3 -3
- package/content/extensions/components/socket-io/index.md +50 -337
- package/content/extensions/components/socket-io/usage.md +143 -26
- package/content/extensions/components/static-asset/api.md +410 -142
- package/content/extensions/components/static-asset/errors.md +110 -53
- package/content/extensions/components/static-asset/index.md +79 -608
- package/content/extensions/components/static-asset/usage.md +180 -300
- package/content/extensions/components/websocket/api.md +275 -399
- package/content/extensions/components/websocket/errors.md +47 -56
- package/content/extensions/components/websocket/index.md +74 -407
- package/content/extensions/components/websocket/usage.md +110 -341
- package/content/extensions/helpers/cron/index.md +51 -160
- package/content/extensions/helpers/crypto/index.md +62 -483
- package/content/extensions/helpers/crypto/reference.md +456 -0
- package/content/extensions/helpers/env/index.md +60 -178
- package/content/extensions/helpers/error/index.md +221 -207
- package/content/extensions/helpers/inversion/index.md +65 -556
- package/content/extensions/helpers/inversion/reference.md +522 -0
- package/content/extensions/helpers/kafka/admin.md +20 -1
- package/content/extensions/helpers/kafka/compile-binary.md +41 -35
- package/content/extensions/helpers/kafka/consumer.md +54 -20
- package/content/extensions/helpers/kafka/examples.md +21 -16
- package/content/extensions/helpers/kafka/index.md +80 -610
- package/content/extensions/helpers/kafka/producer.md +134 -5
- package/content/extensions/helpers/kafka/schema-registry.md +45 -70
- package/content/extensions/helpers/logger/hf-logger.md +193 -0
- package/content/extensions/helpers/logger/index.md +64 -563
- package/content/extensions/helpers/logger/pino.md +85 -0
- package/content/extensions/helpers/logger/reference.md +746 -0
- package/content/extensions/helpers/network/api.md +241 -195
- package/content/extensions/helpers/network/index.md +72 -530
- package/content/extensions/helpers/queue/index.md +72 -900
- package/content/extensions/helpers/queue/reference.md +467 -0
- package/content/extensions/helpers/redis/index.md +73 -645
- package/content/extensions/helpers/redis/reference.md +727 -0
- package/content/extensions/helpers/secrets/index.md +66 -0
- package/content/extensions/helpers/socket-io/api.md +305 -203
- package/content/extensions/helpers/socket-io/index.md +66 -432
- package/content/extensions/helpers/storage/api.md +564 -462
- package/content/extensions/helpers/storage/index.md +77 -573
- package/content/extensions/helpers/types/index.md +66 -499
- package/content/extensions/helpers/types/reference.md +650 -0
- package/content/extensions/helpers/uid/index.md +58 -227
- package/content/extensions/helpers/websocket/api.md +329 -216
- package/content/extensions/helpers/websocket/index.md +65 -503
- package/content/extensions/helpers/worker-thread/index.md +58 -396
- package/content/extensions/helpers/worker-thread/reference.md +428 -0
- package/content/guides/core-concepts/persistent/models.md +1 -1
- package/content/guides/core-concepts/persistent/search-typesense.md +3 -3
- package/content/guides/core-concepts/persistent/transactions.md +1 -1
- package/content/guides/core-concepts/secrets-vault.md +177 -0
- package/content/guides/core-concepts/services.md +1 -1
- package/content/guides/migrations/redis-helpers-migration.md +1 -1
- package/content/guides/migrations/unified-connectors-migration.md +2 -2
- package/content/guides/tutorials/ecommerce-api.md +3 -8
- package/content/references/base/application.md +1 -1
- package/content/references/base/connectors.md +79 -136
- package/content/references/base/datasources-reference.md +599 -0
- package/content/references/base/datasources.md +84 -444
- package/content/references/base/dependency-injection.md +17 -39
- package/content/references/base/filter-system/application-usage.md +69 -121
- package/content/references/base/filter-system/array-operators.md +12 -0
- package/content/references/base/filter-system/comparison-operators.md +12 -0
- package/content/references/base/filter-system/default-filter.md +136 -348
- package/content/references/base/filter-system/fields-order-pagination.md +38 -16
- package/content/references/base/filter-system/index.md +106 -257
- package/content/references/base/filter-system/json-filtering.md +12 -2
- package/content/references/base/filter-system/list-operators.md +16 -2
- package/content/references/base/filter-system/logical-operators.md +13 -0
- package/content/references/base/filter-system/null-operators.md +13 -0
- package/content/references/base/filter-system/pattern-matching.md +12 -0
- package/content/references/base/filter-system/quick-reference.md +11 -2
- package/content/references/base/filter-system/range-operators.md +12 -0
- package/content/references/base/filter-system/tips.md +70 -133
- package/content/references/base/filter-system/use-cases.md +156 -233
- package/content/references/base/middlewares.md +35 -21
- package/content/references/base/models-reference.md +886 -0
- package/content/references/base/models.md +80 -1452
- package/content/references/base/repositories/advanced.md +156 -192
- package/content/references/base/repositories/index.md +77 -650
- package/content/references/base/repositories/mixins.md +22 -18
- package/content/references/base/repositories/relations.md +123 -171
- package/content/references/base/repositories/soft-deletable.md +58 -56
- package/content/references/base/secrets.md +263 -0
- package/content/references/base/services.md +2 -2
- package/content/references/configuration/environment-variables.md +48 -4
- package/content/references/configuration/index.md +49 -31
- package/content/references/quick-reference.md +3 -16
- package/content/references/utilities/crypto.md +35 -76
- package/content/references/utilities/date.md +33 -73
- package/content/references/utilities/index.md +1 -1
- package/content/references/utilities/jsx-reference.md +298 -0
- package/content/references/utilities/jsx.md +82 -525
- package/content/references/utilities/module.md +29 -62
- package/content/references/utilities/parse.md +34 -64
- package/content/references/utilities/performance.md +33 -58
- package/content/references/utilities/promise.md +28 -62
- package/content/references/utilities/request.md +57 -218
- package/content/references/utilities/schema.md +43 -137
- package/content/references/utilities/statuses-reference.md +361 -0
- package/content/references/utilities/statuses.md +63 -667
- package/package.json +8 -8
|
@@ -0,0 +1,727 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Redis - Full Reference
|
|
3
|
+
description: Complete reference for the Redis helper class hierarchy, all three topology constructors, the full data API, lifecycle events, and framework integrations
|
|
4
|
+
difficulty: intermediate
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Redis - Full Reference
|
|
8
|
+
|
|
9
|
+
Exhaustive reference for `AbstractRedisHelper`, the three topology classes, the `createRedisHelper` factory, and every data-API method. For a readable introduction and the common tasks, start with the [Redis overview](/extensions/helpers/redis/).
|
|
10
|
+
|
|
11
|
+
Backed by **ioredis** under the hood.
|
|
12
|
+
|
|
13
|
+
**Files:**
|
|
14
|
+
|
|
15
|
+
- [`packages/helpers/src/modules/redis/base/abstract.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/base/abstract.helper.ts) - `AbstractRedisHelper`
|
|
16
|
+
- [`packages/helpers/src/modules/redis/single/single.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/single/single.helper.ts) - `RedisSingleHelper`
|
|
17
|
+
- [`packages/helpers/src/modules/redis/cluster/cluster.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/cluster/cluster.helper.ts) - `RedisClusterHelper`
|
|
18
|
+
- [`packages/helpers/src/modules/redis/sentinel/sentinel.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/sentinel/sentinel.helper.ts) - `RedisSentinelHelper`
|
|
19
|
+
- [`packages/helpers/src/modules/redis/factory.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/factory.ts) - `createRedisHelper` factory
|
|
20
|
+
- [`packages/helpers/src/modules/redis/common/interfaces.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/common/interfaces.ts) - `IRedisHelper` and its nine capability interfaces
|
|
21
|
+
- [`packages/helpers/src/modules/redis/common/types.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/common/types.ts) - option and callback types
|
|
22
|
+
- [`packages/helpers/src/modules/redis/common/constants.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/common/constants.ts) - `RedisModes`, `RedisSentinelRoles`
|
|
23
|
+
|
|
24
|
+
## Class and Interface Model
|
|
25
|
+
|
|
26
|
+
### Class hierarchy
|
|
27
|
+
|
|
28
|
+
| Class | Extends | Notes |
|
|
29
|
+
|-------|---------|-------|
|
|
30
|
+
| `AbstractRedisHelper` | `BaseHelper` | Base class; implements `IRedisHelper`; never constructed directly |
|
|
31
|
+
| `RedisSingleHelper` | `AbstractRedisHelper` | ioredis `Redis` client; returns `Redis` from `getClient()` |
|
|
32
|
+
| `RedisClusterHelper` | `AbstractRedisHelper` | ioredis `Cluster` client; returns `Cluster` from `getClient()` |
|
|
33
|
+
| `RedisSentinelHelper` | `AbstractRedisHelper` | ioredis `Redis` client (Sentinel mode); returns `Redis` from `getClient()` |
|
|
34
|
+
|
|
35
|
+
> [!TIP] Typing rule
|
|
36
|
+
> Declare parameters and bindings as `IRedisHelper`. Use `instanceof AbstractRedisHelper` for runtime topology checks. Never type-check against the concrete subclasses unless you need topology-specific behavior.
|
|
37
|
+
|
|
38
|
+
### TRedisClient
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
type TRedisClient = Redis | Cluster; // ioredis
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`RedisSingleHelper` and `RedisSentinelHelper` return a `Redis` instance. `RedisClusterHelper` returns a `Cluster` instance. Both satisfy `TRedisClient`.
|
|
45
|
+
|
|
46
|
+
### IRedisHelper and its nine capability interfaces
|
|
47
|
+
|
|
48
|
+
`Source ->` [`packages/helpers/src/modules/redis/common/interfaces.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/common/interfaces.ts)
|
|
49
|
+
|
|
50
|
+
`IRedisHelper` extends all nine of the following:
|
|
51
|
+
|
|
52
|
+
| Interface | Responsibility |
|
|
53
|
+
|-----------|----------------|
|
|
54
|
+
| `IRedisConnection` | Connection lifecycle - `connect`, `disconnect`, `ping`, `getClient`, `duplicateClient` |
|
|
55
|
+
| `IRedisKey` | Key TTL and counters - `exists`, `expire`, `expireAt`, `ttl`, `persist`, `incr`/`decr` variants |
|
|
56
|
+
| `IRedisKeyValue` | String key-value - `get`, `set`, `del`, `keys`, `getString(s)`, `getObject(s)`, `mSet`, `mGet` |
|
|
57
|
+
| `IRedisHash` | Hash maps - `hSet`, `hGetAll`, `hGet`, `hDel`, `hExists`, `hKeys`, `hVals`, `hIncrBy`, `hLen` |
|
|
58
|
+
| `IRedisSet` | Sets - `sAdd`, `sRem`, `sMembers`, `sIsMember`, `sCard` |
|
|
59
|
+
| `IRedisList` | Lists - `lPush`, `rPush`, `lPop`, `rPop`, `lRange`, `lLen` |
|
|
60
|
+
| `IRedisPubSub` | Pub/Sub with optional zlib compression - `publish`, `subscribe`, `unsubscribe` |
|
|
61
|
+
| `IRedisJson` | RedisJSON module operations - `jSet`, `jGet`, `jDelete`, `jNumberIncreaseBy`, `jStringAppend`, `jPush`, `jPop` |
|
|
62
|
+
| `IRedisCommand` | Raw escape hatch - `execute(command, params?)` |
|
|
63
|
+
|
|
64
|
+
## Construction - Single
|
|
65
|
+
|
|
66
|
+
`Source ->` [`packages/helpers/src/modules/redis/single/single.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/single/single.helper.ts)
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { RedisSingleHelper } from '@venizia/ignis-helpers';
|
|
70
|
+
|
|
71
|
+
const redis = new RedisSingleHelper({
|
|
72
|
+
name: 'cache',
|
|
73
|
+
host: 'localhost',
|
|
74
|
+
port: 6379,
|
|
75
|
+
password: 'secret',
|
|
76
|
+
database: 0,
|
|
77
|
+
autoConnect: true,
|
|
78
|
+
maxRetry: 5,
|
|
79
|
+
|
|
80
|
+
onInitialized: ({ name, helper }) => {
|
|
81
|
+
console.log(`[${name}] initialized`);
|
|
82
|
+
},
|
|
83
|
+
onConnected: ({ name }) => {
|
|
84
|
+
console.log(`[${name}] connected`);
|
|
85
|
+
},
|
|
86
|
+
onReady: ({ name }) => {
|
|
87
|
+
console.log(`[${name}] ready`);
|
|
88
|
+
},
|
|
89
|
+
onError: ({ name, error }) => {
|
|
90
|
+
console.error(`[${name}] error`, error);
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### IRedisSingleHelperOptions
|
|
96
|
+
|
|
97
|
+
Combines `IRedisSingleHelperProps` and `IRedisHelperCallbacks`.
|
|
98
|
+
|
|
99
|
+
| Field | Type | Required | Default | Description |
|
|
100
|
+
|-------|------|----------|---------|-------------|
|
|
101
|
+
| `name` | `string` | Yes | - | Helper identifier used in logs and as `IRedisHelper.name` |
|
|
102
|
+
| `host` | `string` | Yes | - | Redis server hostname |
|
|
103
|
+
| `port` | `string \| number` | Yes | - | Redis server port |
|
|
104
|
+
| `password` | `string` | Yes | - | Redis `requirepass` value |
|
|
105
|
+
| `database` | `number` | No | `0` | Redis database index (0-15) |
|
|
106
|
+
| `autoConnect` | `boolean` | No | `true` | Connect immediately; `false` uses ioredis `lazyConnect` |
|
|
107
|
+
| `maxRetry` | `number` | No | `0` | Max reconnect attempts; `0` = unlimited; `-1` = no retry |
|
|
108
|
+
| `onInitialized` | `(opts: { name: string; helper: IRedisHelper }) => void` | No | - | Fired synchronously after construction |
|
|
109
|
+
| `onConnected` | `(opts: { name: string; helper: IRedisHelper }) => void` | No | - | Fired on TCP connection established |
|
|
110
|
+
| `onReady` | `(opts: { name: string; helper: IRedisHelper }) => void` | No | - | Fired when client is ready for commands |
|
|
111
|
+
| `onError` | `(opts: { name: string; helper: IRedisHelper; error: unknown }) => void` | No | - | Fired on connection or command errors |
|
|
112
|
+
|
|
113
|
+
### Retry strategy
|
|
114
|
+
|
|
115
|
+
- **Backoff formula.** `Math.max(Math.min(attempt * 2000, 5000), 1000)` - starting at 1 s, capped at 5 s.
|
|
116
|
+
- **Stop condition.** Reconnect stops when `attempt > maxRetry` (if `maxRetry > -1`).
|
|
117
|
+
- **BullMQ requirement.** The framework always sets `maxRetriesPerRequest: null` internally, which BullMQ requires.
|
|
118
|
+
|
|
119
|
+
## Construction - Cluster
|
|
120
|
+
|
|
121
|
+
`Source ->` [`packages/helpers/src/modules/redis/cluster/cluster.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/cluster/cluster.helper.ts)
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
import { RedisClusterHelper } from '@venizia/ignis-helpers';
|
|
125
|
+
|
|
126
|
+
const cluster = new RedisClusterHelper({
|
|
127
|
+
name: 'cache-cluster',
|
|
128
|
+
nodes: [
|
|
129
|
+
{ host: 'redis-node-1', port: 7000 },
|
|
130
|
+
{ host: 'redis-node-2', port: 7001 },
|
|
131
|
+
{ host: 'redis-node-3', port: 7002 },
|
|
132
|
+
],
|
|
133
|
+
clusterOptions: {
|
|
134
|
+
redisOptions: { password: 'cluster-password' },
|
|
135
|
+
},
|
|
136
|
+
onReady: ({ name }) => {
|
|
137
|
+
console.log(`[${name}] cluster ready`);
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### IRedisClusterHelperOptions
|
|
143
|
+
|
|
144
|
+
| Field | Type | Required | Default | Description |
|
|
145
|
+
|-------|------|----------|---------|-------------|
|
|
146
|
+
| `name` | `string` | Yes | - | Helper identifier |
|
|
147
|
+
| `nodes` | `Array<{ host: string; port: string \| number; password?: string }>` | Yes | - | Startup nodes - ioredis discovers the rest |
|
|
148
|
+
| `clusterOptions` | `ClusterOptions` | No | - | Passed verbatim to `new Cluster(nodes, clusterOptions)` |
|
|
149
|
+
| `onInitialized` / `onConnected` / `onReady` / `onError` | callbacks | No | - | Same shape as single |
|
|
150
|
+
|
|
151
|
+
> [!WARNING] No framework defaults injected
|
|
152
|
+
> Cluster does not apply the backoff retry strategy or `maxRetriesPerRequest: null` automatically. Pass those inside `clusterOptions.redisOptions` if your consumers (e.g. BullMQ) require them.
|
|
153
|
+
|
|
154
|
+
`duplicateClient()` on a cluster creates a **new** `Cluster` instance from the same startup nodes and options (because ioredis `Cluster` does not implement `.duplicate()`).
|
|
155
|
+
|
|
156
|
+
## Construction - Sentinel
|
|
157
|
+
|
|
158
|
+
`Source ->` [`packages/helpers/src/modules/redis/sentinel/sentinel.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/sentinel/sentinel.helper.ts)
|
|
159
|
+
|
|
160
|
+
### What Redis Sentinel is
|
|
161
|
+
|
|
162
|
+
Redis Sentinel is a high-availability (HA) architecture made of three process types:
|
|
163
|
+
|
|
164
|
+
```
|
|
165
|
+
+------------------+ monitors +--------------------+
|
|
166
|
+
| Sentinel (1) |<------------------>| Master (primary) |
|
|
167
|
+
+------------------+ +--------------------+
|
|
168
|
+
+------------------+ replication |
|
|
169
|
+
| Sentinel (2) | +--------------+
|
|
170
|
+
+------------------+ v
|
|
171
|
+
+------------------+ +--------------------+
|
|
172
|
+
| Sentinel (3) | | Replica (standby) |
|
|
173
|
+
+------------------+ +--------------------+
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
- **Sentinels** form a quorum (typically 3 processes). They monitor the master, agree by majority vote when it is down, and promote a replica to master (failover).
|
|
177
|
+
- **Master** accepts all writes.
|
|
178
|
+
- **Replicas** replicate from master and serve reads when `role: 'slave'` is set.
|
|
179
|
+
|
|
180
|
+
### Why your app connects to sentinels, not the master
|
|
181
|
+
|
|
182
|
+
- **The master's address can change after a failover.** Hard-coding a master host would break on every failover.
|
|
183
|
+
- **You give ioredis the sentinel addresses instead**, plus the monitored master group name (`masterName`). ioredis asks a sentinel for the current master and connects to it.
|
|
184
|
+
- **ioredis re-queries sentinels automatically after a failover** - no manual reconnection logic needed.
|
|
185
|
+
- **Your application code does not change during a failover.** The only observable effect is a few seconds of transient command failures, which the retry strategy handles.
|
|
186
|
+
|
|
187
|
+
### Constructor
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
import { RedisSentinelHelper } from '@venizia/ignis-helpers';
|
|
191
|
+
|
|
192
|
+
const redis = new RedisSentinelHelper({
|
|
193
|
+
name: 'ha-cache', // helper identifier (logging/scope)
|
|
194
|
+
masterName: 'mymaster', // group name in sentinel.conf "sentinel monitor mymaster ..."
|
|
195
|
+
sentinels: [
|
|
196
|
+
{ host: '10.0.0.1', port: 26379 },
|
|
197
|
+
{ host: '10.0.0.2', port: 26379 },
|
|
198
|
+
{ host: '10.0.0.3' }, // port defaults to 26379
|
|
199
|
+
],
|
|
200
|
+
role: 'master', // 'master' (default) or 'slave'
|
|
201
|
+
password: 'data-secret', // master/replica requirepass
|
|
202
|
+
sentinelPassword: 'sentinel-secret', // sentinel.conf requirepass
|
|
203
|
+
database: 0,
|
|
204
|
+
autoConnect: true,
|
|
205
|
+
maxRetry: 5,
|
|
206
|
+
});
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### IRedisSentinelHelperOptions
|
|
210
|
+
|
|
211
|
+
| Field | Type | Required | Default | Description |
|
|
212
|
+
|-------|------|----------|---------|-------------|
|
|
213
|
+
| `name` | `string` | Yes | - | Helper identifier (logs, `IRedisHelper.name`) |
|
|
214
|
+
| `masterName` | `string` | Yes | - | Sentinel-monitored master group name - maps to ioredis `name` |
|
|
215
|
+
| `sentinels` | `Array<{ host: string; port?: string \| number }>` | Yes | - | Sentinel process addresses |
|
|
216
|
+
| `role` | `TRedisSentinelRole` (`RedisSentinelRoles.MASTER \| SLAVE`) | No | `RedisSentinelRoles.MASTER` | Connect to master (writes) or a replica (reads) |
|
|
217
|
+
| `password` | `string` | No | - | Data-node `requirepass` (master and replicas) |
|
|
218
|
+
| `sentinelPassword` | `string` | No | - | Sentinel-process `requirepass` |
|
|
219
|
+
| `sentinelUsername` | `string` | No | - | Sentinel ACL username |
|
|
220
|
+
| `database` | `number` | No | `0` | Redis database index |
|
|
221
|
+
| `autoConnect` | `boolean` | No | `true` | Connect immediately |
|
|
222
|
+
| `maxRetry` | `number` | No | `0` | Max reconnect attempts |
|
|
223
|
+
| `redisOptions` | `Partial<RedisOptions>` | No | - | Extra ioredis options; first-class fields above always override matching keys here |
|
|
224
|
+
| `onInitialized` / `onConnected` / `onReady` / `onError` | callbacks | No | - | Same shape as single |
|
|
225
|
+
|
|
226
|
+
### Field clarity - name vs masterName
|
|
227
|
+
|
|
228
|
+
This is the most common source of confusion:
|
|
229
|
+
|
|
230
|
+
| Field | What it is | Where it goes |
|
|
231
|
+
|-------|-----------|---------------|
|
|
232
|
+
| `name` | The helper's own identifier used for logging and `IRedisHelper.name` | `AbstractRedisHelper` identifier |
|
|
233
|
+
| `masterName` | The master group being monitored by Sentinel processes, matching `sentinel monitor <name> ...` in sentinel.conf | Maps to ioredis `name` option |
|
|
234
|
+
|
|
235
|
+
They are independent. You can name the helper `'ha-cache'` while `masterName` is `'mymaster'`.
|
|
236
|
+
|
|
237
|
+
### The authentication model - 4 relationships
|
|
238
|
+
|
|
239
|
+
Sentinel deployments have four separate authentication relationships. The app only configures two of them; the other two are server-side.
|
|
240
|
+
|
|
241
|
+
| # | From | To | App field | Server config |
|
|
242
|
+
|---|------|----|-----------|---------------|
|
|
243
|
+
| 1 | **App** | **Sentinel processes** | `sentinelPassword` | `requirepass` in sentinel.conf |
|
|
244
|
+
| 2 | **App** | **Data nodes** (master/replica) | `password` | `requirepass` in redis.conf |
|
|
245
|
+
| 3 | **Sentinel** | **Data nodes** | (not set by app) | `sentinel auth-pass <group> <pass>` in sentinel.conf |
|
|
246
|
+
| 4 | **Replica** | **Master** (replication) | (not set by app) | `masterauth` in redis.conf |
|
|
247
|
+
|
|
248
|
+
**Relationship 3 is the silent failure.** If the data nodes require a password but sentinel.conf does not have `sentinel auth-pass`, the sentinel processes cannot check master health and will trigger false failovers. Configure it on the server side even when your app only sets `password`.
|
|
249
|
+
|
|
250
|
+
**Common cases:**
|
|
251
|
+
- Private network, sentinels unauthenticated: set only `password`.
|
|
252
|
+
- Fully secured cluster: set both `password` and `sentinelPassword`; configure relationships 3 and 4 on the servers.
|
|
253
|
+
|
|
254
|
+
### Failover behavior
|
|
255
|
+
|
|
256
|
+
When the master fails:
|
|
257
|
+
|
|
258
|
+
1. Sentinels reach quorum and promote a replica.
|
|
259
|
+
2. ioredis detects the master change via sentinel notification.
|
|
260
|
+
3. ioredis reconnects to the new master transparently.
|
|
261
|
+
4. Any in-flight commands during the few-second window may fail transiently - the retry strategy retries them.
|
|
262
|
+
5. **Your application code does not change.** The same `RedisSentinelHelper` instance continues to work after failover.
|
|
263
|
+
|
|
264
|
+
### Local testing with Docker Compose
|
|
265
|
+
|
|
266
|
+
The following Compose file starts a master, one replica, and one sentinel with full authentication. It demonstrates all four relationships.
|
|
267
|
+
|
|
268
|
+
```yaml
|
|
269
|
+
version: '3.8'
|
|
270
|
+
|
|
271
|
+
services:
|
|
272
|
+
redis-master:
|
|
273
|
+
image: redis:7-alpine
|
|
274
|
+
command: redis-server --requirepass data-secret --masterauth data-secret
|
|
275
|
+
ports:
|
|
276
|
+
- '6379:6379'
|
|
277
|
+
|
|
278
|
+
redis-replica:
|
|
279
|
+
image: redis:7-alpine
|
|
280
|
+
command: >
|
|
281
|
+
redis-server
|
|
282
|
+
--requirepass data-secret
|
|
283
|
+
--masterauth data-secret
|
|
284
|
+
--replicaof redis-master 6379
|
|
285
|
+
depends_on:
|
|
286
|
+
- redis-master
|
|
287
|
+
|
|
288
|
+
redis-sentinel:
|
|
289
|
+
image: redis:7-alpine
|
|
290
|
+
command: >
|
|
291
|
+
sh -c "
|
|
292
|
+
echo 'sentinel monitor mymaster redis-master 6379 1' > /sentinel.conf &&
|
|
293
|
+
echo 'sentinel auth-pass mymaster data-secret' >> /sentinel.conf &&
|
|
294
|
+
echo 'sentinel down-after-milliseconds mymaster 3000' >> /sentinel.conf &&
|
|
295
|
+
echo 'sentinel failover-timeout mymaster 10000' >> /sentinel.conf &&
|
|
296
|
+
echo 'requirepass sentinel-secret' >> /sentinel.conf &&
|
|
297
|
+
redis-sentinel /sentinel.conf
|
|
298
|
+
"
|
|
299
|
+
ports:
|
|
300
|
+
- '26379:26379'
|
|
301
|
+
depends_on:
|
|
302
|
+
- redis-master
|
|
303
|
+
- redis-replica
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Connect and verify failover:
|
|
307
|
+
|
|
308
|
+
```typescript
|
|
309
|
+
import { RedisSentinelHelper } from '@venizia/ignis-helpers';
|
|
310
|
+
|
|
311
|
+
const redis = new RedisSentinelHelper({
|
|
312
|
+
name: 'test',
|
|
313
|
+
masterName: 'mymaster',
|
|
314
|
+
sentinels: [{ host: 'localhost', port: 26379 }],
|
|
315
|
+
password: 'data-secret',
|
|
316
|
+
sentinelPassword: 'sentinel-secret',
|
|
317
|
+
onReady: ({ name }) => console.log(`[${name}] ready`),
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
await redis.set({ key: 'hello', value: 'world' });
|
|
321
|
+
const val = await redis.getObject({ key: 'hello' });
|
|
322
|
+
console.log(val); // "world"
|
|
323
|
+
|
|
324
|
+
// Stop the master container - wait ~5 s - the replica is promoted.
|
|
325
|
+
// The same redis instance will reconnect automatically and continue working.
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
## Selecting a Topology - the Factory
|
|
329
|
+
|
|
330
|
+
`Source ->` [`packages/helpers/src/modules/redis/factory.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/factory.ts)
|
|
331
|
+
|
|
332
|
+
`createRedisHelper` is an overloaded factory that returns the concrete type when `mode` is a literal.
|
|
333
|
+
|
|
334
|
+
```typescript
|
|
335
|
+
import { createRedisHelper, RedisModes } from '@venizia/ignis-helpers';
|
|
336
|
+
|
|
337
|
+
// Type inferred as RedisSingleHelper
|
|
338
|
+
const single = createRedisHelper({
|
|
339
|
+
mode: RedisModes.SINGLE,
|
|
340
|
+
name: 'cache',
|
|
341
|
+
host: process.env.REDIS_HOST!,
|
|
342
|
+
port: Number(process.env.REDIS_PORT),
|
|
343
|
+
password: process.env.REDIS_PASSWORD!,
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
// Type inferred as RedisSentinelHelper
|
|
347
|
+
const sentinel = createRedisHelper({
|
|
348
|
+
mode: RedisModes.SENTINEL,
|
|
349
|
+
name: 'cache-ha',
|
|
350
|
+
masterName: 'mymaster',
|
|
351
|
+
sentinels: [{ host: process.env.SENTINEL_HOST! }],
|
|
352
|
+
password: process.env.REDIS_PASSWORD!,
|
|
353
|
+
});
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
Switch by environment:
|
|
357
|
+
|
|
358
|
+
```typescript
|
|
359
|
+
import { createRedisHelper, RedisModes, type IRedisHelper } from '@venizia/ignis-helpers';
|
|
360
|
+
|
|
361
|
+
const mode = (process.env.REDIS_MODE ?? RedisModes.SINGLE) as typeof RedisModes.SINGLE;
|
|
362
|
+
|
|
363
|
+
const redis: IRedisHelper = createRedisHelper({
|
|
364
|
+
mode,
|
|
365
|
+
name: 'app-cache',
|
|
366
|
+
host: process.env.REDIS_HOST!,
|
|
367
|
+
port: Number(process.env.REDIS_PORT),
|
|
368
|
+
password: process.env.REDIS_PASSWORD!,
|
|
369
|
+
});
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
| `mode` value | Returns |
|
|
373
|
+
|---|---|
|
|
374
|
+
| `RedisModes.SINGLE` (`'single'`) | `RedisSingleHelper` |
|
|
375
|
+
| `RedisModes.CLUSTER` (`'cluster'`) | `RedisClusterHelper` |
|
|
376
|
+
| `RedisModes.SENTINEL` (`'sentinel'`) | `RedisSentinelHelper` |
|
|
377
|
+
|
|
378
|
+
Unknown mode throws an `ApplicationError`.
|
|
379
|
+
|
|
380
|
+
## Lifecycle and Events
|
|
381
|
+
|
|
382
|
+
`Source ->` [`packages/helpers/src/modules/redis/base/abstract.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/base/abstract.helper.ts)
|
|
383
|
+
|
|
384
|
+
### autoConnect and manual connect
|
|
385
|
+
|
|
386
|
+
When `autoConnect: true` (default), the ioredis client starts connecting immediately in the constructor. When `autoConnect: false`, ioredis uses `lazyConnect` mode and you must call `connect()` explicitly before issuing commands.
|
|
387
|
+
|
|
388
|
+
```typescript
|
|
389
|
+
// Lazy connect
|
|
390
|
+
const redis = new RedisSingleHelper({
|
|
391
|
+
name: 'cache',
|
|
392
|
+
host: 'localhost',
|
|
393
|
+
port: 6379,
|
|
394
|
+
password: 'secret',
|
|
395
|
+
autoConnect: false,
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
await redis.connect(); // resolves true when status === 'ready'
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
### Connection methods
|
|
402
|
+
|
|
403
|
+
| Method | Behavior |
|
|
404
|
+
|--------|----------|
|
|
405
|
+
| `connect()` | Resolves `false` (no-op) if status is `ready`, `reconnecting`, or `connecting`; otherwise calls ioredis `connect()` and resolves `true` when status reaches `ready` |
|
|
406
|
+
| `disconnect()` | Resolves `false` (no-op) if status is `end` or `close`; otherwise sends `QUIT` and resolves `true` on `'OK'` |
|
|
407
|
+
| `ping()` | Sends `PING`; returns `'PONG'` |
|
|
408
|
+
|
|
409
|
+
### The four lifecycle callbacks
|
|
410
|
+
|
|
411
|
+
All helpers accept `IRedisHelperCallbacks`:
|
|
412
|
+
|
|
413
|
+
| Callback | Fired when | ioredis event |
|
|
414
|
+
|----------|-----------|---------------|
|
|
415
|
+
| `onInitialized` | Synchronously at the end of the constructor | - |
|
|
416
|
+
| `onConnected` | TCP connection is established | `connect` |
|
|
417
|
+
| `onReady` | Client is ready to accept commands | `ready` |
|
|
418
|
+
| `onError` | A connection or command error occurs | `error` |
|
|
419
|
+
|
|
420
|
+
The client also logs a `WARN` internally on `reconnecting` events (not surfaced as a callback).
|
|
421
|
+
|
|
422
|
+
### duplicateClient
|
|
423
|
+
|
|
424
|
+
```typescript
|
|
425
|
+
const dedicated = redis.duplicateClient();
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
- **Creates an independent ioredis connection** from the same configuration.
|
|
429
|
+
- **Implementation.** `AbstractRedisHelper.duplicateClient()` calls ioredis `client.duplicate()`, which copies the parent's `options` - including `lazyConnect`.
|
|
430
|
+
- **Lazy or immediate.** `lazyConnect` is set to `!autoConnect`. With the default `autoConnect: true` (`lazyConnect: false`) the duplicate connects immediately; it is lazy (connects on first use) only when the parent was created with `autoConnect: false`.
|
|
431
|
+
- **When to use it.** Whenever a consumer needs its own dedicated connection - Pub/Sub, BullMQ, Socket.IO adapters.
|
|
432
|
+
- **Cluster is different.** For `RedisClusterHelper`, `duplicateClient()` instead constructs a new `Cluster` from the same startup nodes and options (ioredis `Cluster` has no `.duplicate()`).
|
|
433
|
+
|
|
434
|
+
## Full Method Reference
|
|
435
|
+
|
|
436
|
+
`Source ->` [`packages/helpers/src/modules/redis/common/interfaces.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/common/interfaces.ts) (signatures) and [`packages/helpers/src/modules/redis/base/abstract.helper.ts`](https://github.com/VENIZIA-AI/ignis/blob/main/packages/helpers/src/modules/redis/base/abstract.helper.ts) (behavior)
|
|
437
|
+
|
|
438
|
+
### General notes (apply to all families)
|
|
439
|
+
|
|
440
|
+
- **Empty-input no-ops:** Methods that accept an array (`keys`, `members`, `values`, `fields`, `payload`) short-circuit immediately when the array is empty, without calling ioredis - returning `0`, `[]`, or (for `mSet`) resolving `void`, per each method's return type. This prevents the "wrong number of arguments" error ioredis throws on empty varargs.
|
|
441
|
+
- **Boolean mapping:** `expire`, `expireAt`, `persist`, `hExists`, `sIsMember` map ioredis numeric replies to `true` (`=== 1`) / `false`.
|
|
442
|
+
- **JSON auto-serialization:** `set`, `mSet`, `jSet`, `jPush` call `JSON.stringify` before writing. `getObject`, `getObjects`, `jGet` parse on read. `get` and `mGet` return raw strings unless you pass `transform`.
|
|
443
|
+
- **TTL units:** `set.options.expiresIn` is **milliseconds** (ioredis `PX`). `expire.seconds` is **seconds** (ioredis `EXPIRE`). `expireAt.atEpochSeconds` is a Unix epoch **in seconds** (ioredis `EXPIREAT`).
|
|
444
|
+
- **Pub/Sub errors:** On subscription callback error, the helper **logs** the error and returns without throwing, because throwing inside an ioredis async callback would be an unhandled rejection.
|
|
445
|
+
|
|
446
|
+
### IRedisConnection - connection lifecycle
|
|
447
|
+
|
|
448
|
+
| Method | Signature | Behavior |
|
|
449
|
+
|--------|-----------|----------|
|
|
450
|
+
| `getClient` | `(): TRedisClient` | Returns the raw ioredis `Redis` or `Cluster` instance |
|
|
451
|
+
| `duplicateClient` | `(): TRedisClient` | Creates an independent ioredis connection (same config, separate socket) |
|
|
452
|
+
| `ping` | `(): Promise<string>` | Sends `PING`; returns `'PONG'` on success |
|
|
453
|
+
| `connect` | `(): Promise<boolean>` | Connects the client; resolves `false` if already connected/connecting/ready |
|
|
454
|
+
| `disconnect` | `(): Promise<boolean>` | Graceful `QUIT`; resolves `false` if already ended/closed |
|
|
455
|
+
|
|
456
|
+
### IRedisKey - key lifecycle and counters
|
|
457
|
+
|
|
458
|
+
| Method | Signature | Behavior |
|
|
459
|
+
|--------|-----------|----------|
|
|
460
|
+
| `exists` | `(opts: { keys: string[] }): Promise<number>` | Returns the count of keys that exist; empty `keys` returns `0` without calling Redis |
|
|
461
|
+
| `expire` | `(opts: { key: string; seconds: number }): Promise<boolean>` | Sets expiry in seconds; `true` if applied |
|
|
462
|
+
| `expireAt` | `(opts: { key: string; atEpochSeconds: number }): Promise<boolean>` | Sets expiry at an epoch second timestamp; `true` if applied |
|
|
463
|
+
| `ttl` | `(opts: { key: string }): Promise<number>` | Returns remaining TTL in seconds; `-1` = no expiry; `-2` = key missing |
|
|
464
|
+
| `persist` | `(opts: { key: string }): Promise<boolean>` | Removes expiry; `true` if the timeout was removed |
|
|
465
|
+
| `incr` | `(opts: { key: string }): Promise<number>` | Atomically increments integer at key by 1; returns new value |
|
|
466
|
+
| `decr` | `(opts: { key: string }): Promise<number>` | Atomically decrements integer at key by 1; returns new value |
|
|
467
|
+
| `incrBy` | `(opts: { key: string; value: number }): Promise<number>` | Atomically increments by `value`; returns new value |
|
|
468
|
+
| `decrBy` | `(opts: { key: string; value: number }): Promise<number>` | Atomically decrements by `value`; returns new value |
|
|
469
|
+
|
|
470
|
+
### IRedisKeyValue - string key-value
|
|
471
|
+
|
|
472
|
+
| Method | Signature | Behavior |
|
|
473
|
+
|--------|-----------|----------|
|
|
474
|
+
| `set<T>` | `(opts: { key: string; value: T; options?: { log?: boolean; expiresIn?: number } }): Promise<void>` | JSON-serializes `value` and writes it; `expiresIn` is in **milliseconds** (uses `PX`); `log: true` emits an info log |
|
|
475
|
+
| `get<T>` | `(opts: { key: string; transform?: (input: string) => T }): Promise<T \| null>` | Returns raw string or applies `transform`; `null` if key missing |
|
|
476
|
+
| `del` | `(opts: { keys: string[] }): Promise<number>` | Deletes one or more keys; empty `keys` returns `0` |
|
|
477
|
+
| `keys` | `(opts: { key: string }): Promise<string[]>` | Runs Redis `KEYS` with a glob pattern; avoid on large keyspaces - prefer `SCAN` via `execute` |
|
|
478
|
+
| `getString` | `(opts: { key: string }): Promise<string \| null>` | Alias for `get` without transform |
|
|
479
|
+
| `getStrings` | `(opts: { keys: string[] }): Promise<(string \| null)[]>` | Alias for `mGet` without transform |
|
|
480
|
+
| `getObject<T>` | `(opts: { key: string }): Promise<T \| null>` | `get` with `JSON.parse` transform |
|
|
481
|
+
| `getObjects` | `(opts: { keys: string[] }): Promise<(unknown \| null)[]>` | `mGet` with `JSON.parse` transform |
|
|
482
|
+
| `mSet<T>` | `(opts: { payload: Array<{ key: string; value: T }>; options?: { log?: boolean } }): Promise<void>` | Bulk write; each value is JSON-serialized; empty `payload` is a no-op |
|
|
483
|
+
| `mGet<T>` | `(opts: { keys: string[]; transform?: (input: string) => T }): Promise<(T \| null)[]>` | Bulk read with optional transform; empty `keys` returns `[]` |
|
|
484
|
+
|
|
485
|
+
### IRedisHash - hash maps
|
|
486
|
+
|
|
487
|
+
| Method | Signature | Behavior |
|
|
488
|
+
|--------|-----------|----------|
|
|
489
|
+
| `hSet<T>` | `(opts: { key: string; value: T; options?: { log?: boolean } }): Promise<number>` | Sets all fields in a hash object; returns number of **new** fields added |
|
|
490
|
+
| `hGetAll` | `(opts: { key: string; transform?: <T, R>(input: T) => R }): Promise<unknown>` | Returns all fields and values of a hash; applies optional transform |
|
|
491
|
+
| `hGet` | `(opts: { key: string; field: string }): Promise<string \| null>` | Returns the value of a single hash field |
|
|
492
|
+
| `hDel` | `(opts: { key: string; fields: string[] }): Promise<number>` | Deletes one or more hash fields; empty `fields` returns `0` |
|
|
493
|
+
| `hExists` | `(opts: { key: string; field: string }): Promise<boolean>` | `true` if the field exists in the hash |
|
|
494
|
+
| `hKeys` | `(opts: { key: string }): Promise<string[]>` | Returns all field names in the hash |
|
|
495
|
+
| `hVals` | `(opts: { key: string }): Promise<string[]>` | Returns all field values in the hash |
|
|
496
|
+
| `hIncrBy` | `(opts: { key: string; field: string; value: number }): Promise<number>` | Atomically increments a numeric hash field; returns new value |
|
|
497
|
+
| `hLen` | `(opts: { key: string }): Promise<number>` | Returns the number of fields in the hash |
|
|
498
|
+
|
|
499
|
+
### IRedisSet - sets
|
|
500
|
+
|
|
501
|
+
| Method | Signature | Behavior |
|
|
502
|
+
|--------|-----------|----------|
|
|
503
|
+
| `sAdd` | `(opts: { key: string; members: Array<string \| number> }): Promise<number>` | Adds members to a set; returns count of new members; empty `members` returns `0` |
|
|
504
|
+
| `sRem` | `(opts: { key: string; members: Array<string \| number> }): Promise<number>` | Removes members from a set; returns count removed; empty `members` returns `0` |
|
|
505
|
+
| `sMembers` | `(opts: { key: string }): Promise<string[]>` | Returns all members of the set |
|
|
506
|
+
| `sIsMember` | `(opts: { key: string; member: string \| number }): Promise<boolean>` | `true` if `member` belongs to the set |
|
|
507
|
+
| `sCard` | `(opts: { key: string }): Promise<number>` | Returns the number of members in the set |
|
|
508
|
+
|
|
509
|
+
### IRedisList - lists
|
|
510
|
+
|
|
511
|
+
| Method | Signature | Behavior |
|
|
512
|
+
|--------|-----------|----------|
|
|
513
|
+
| `lPush` | `(opts: { key: string; values: Array<string \| number> }): Promise<number>` | Prepends values to the list head; returns list length after push; empty `values` returns `0` |
|
|
514
|
+
| `rPush` | `(opts: { key: string; values: Array<string \| number> }): Promise<number>` | Appends values to the list tail; returns list length after push; empty `values` returns `0` |
|
|
515
|
+
| `lPop` | `(opts: { key: string }): Promise<string \| null>` | Removes and returns the head element; `null` if list is empty |
|
|
516
|
+
| `rPop` | `(opts: { key: string }): Promise<string \| null>` | Removes and returns the tail element; `null` if list is empty |
|
|
517
|
+
| `lRange` | `(opts: { key: string; start: number; stop: number }): Promise<string[]>` | Returns elements from `start` to `stop` (inclusive, 0-indexed, `-1` = last) |
|
|
518
|
+
| `lLen` | `(opts: { key: string }): Promise<number>` | Returns the number of elements in the list |
|
|
519
|
+
|
|
520
|
+
### IRedisPubSub - publish/subscribe
|
|
521
|
+
|
|
522
|
+
| Method | Signature | Behavior |
|
|
523
|
+
|--------|-----------|----------|
|
|
524
|
+
| `publish<T>` | `(opts: { topics: string[]; payload: T; useCompress?: boolean }): Promise<void>` | JSON-serializes `payload` into a `Buffer`; optionally zlib-deflates it; publishes to each topic; skips empty/blank topics (logs error, does not throw) |
|
|
525
|
+
| `subscribe` | `(opts: { topic: string }): void` | Subscribes the client to `topic`; on subscription error the helper **logs** it and does not throw |
|
|
526
|
+
| `unsubscribe` | `(opts: { topic: string }): void` | Unsubscribes from `topic`; on error the helper **logs** it and does not throw |
|
|
527
|
+
|
|
528
|
+
> [!IMPORTANT]
|
|
529
|
+
> A subscribed ioredis connection enters subscriber mode and cannot run regular commands. Use `duplicateClient()` to obtain a separate connection for pub/sub.
|
|
530
|
+
|
|
531
|
+
```typescript
|
|
532
|
+
// Correct pattern - separate connections for data and pub/sub
|
|
533
|
+
const dataClient = new RedisSingleHelper({ name: 'data', host, port, password });
|
|
534
|
+
const subClient = new RedisSingleHelper({ name: 'sub', host, port, password });
|
|
535
|
+
|
|
536
|
+
subClient.subscribe({ topic: 'events' });
|
|
537
|
+
subClient.getClient().on('message', (channel, message) => {
|
|
538
|
+
const parsed = JSON.parse(message.toString());
|
|
539
|
+
console.log(channel, parsed);
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
await dataClient.set({ key: 'foo', value: 'bar' });
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
### IRedisJson - RedisJSON module
|
|
546
|
+
|
|
547
|
+
Requires the [RedisJSON module](https://redis.io/docs/stack/json/) on the server.
|
|
548
|
+
|
|
549
|
+
| Method | Signature | Behavior |
|
|
550
|
+
|--------|-----------|----------|
|
|
551
|
+
| `jSet<T>` | `(opts: { key: string; path: string; value: T }): Promise<string \| null>` | Sets a JSON document at `path` (`JSON.SET`); value is `JSON.stringify`-ed |
|
|
552
|
+
| `jGet<T>` | `(opts: { key: string; path?: string }): Promise<T \| null>` | Retrieves the document or sub-path (`JSON.GET`); `path` defaults to `'$'` |
|
|
553
|
+
| `jDelete` | `(opts: { key: string; path?: string }): Promise<number>` | Deletes the document or sub-path (`JSON.DEL`); `path` defaults to `'$'`; returns count deleted |
|
|
554
|
+
| `jNumberIncreaseBy` | `(opts: { key: string; path: string; value: number }): Promise<string \| null>` | Increments a numeric field by `value` (`JSON.NUMINCRBY`) |
|
|
555
|
+
| `jStringAppend` | `(opts: { key: string; path: string; value: string }): Promise<number[] \| null>` | Appends `value` to a string field (`JSON.STRAPPEND`); returns new string lengths |
|
|
556
|
+
| `jPush<T>` | `(opts: { key: string; path: string; value: T }): Promise<number[] \| null>` | Appends `value` to an array field (`JSON.ARRAPPEND`); value is `JSON.stringify`-ed; returns new array lengths |
|
|
557
|
+
| `jPop<T>` | `(opts: { key: string; path: string }): Promise<T \| null>` | Pops the last element from an array field (`JSON.ARRPOP`) |
|
|
558
|
+
|
|
559
|
+
### IRedisCommand - raw escape hatch
|
|
560
|
+
|
|
561
|
+
| Method | Signature | Behavior |
|
|
562
|
+
|--------|-----------|----------|
|
|
563
|
+
| `execute<R>` | `(command: string, parameters?: Array<string \| number \| Buffer>): Promise<R>` | Calls any ioredis command directly via `client.call(command, parameters)` |
|
|
564
|
+
|
|
565
|
+
```typescript
|
|
566
|
+
// Use SCAN instead of KEYS on large keyspaces
|
|
567
|
+
const [cursor, keys] = await redis.execute<[string, string[]]>(
|
|
568
|
+
'SCAN',
|
|
569
|
+
[0, 'MATCH', 'user:*', 'COUNT', 100],
|
|
570
|
+
);
|
|
571
|
+
|
|
572
|
+
// Fetch server info
|
|
573
|
+
const info = await redis.execute<string>('INFO');
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
## Using the Helper Across IGNIS
|
|
577
|
+
|
|
578
|
+
All three topologies implement `IRedisHelper` and are interchangeable in every integration below. Switch topology by changing the helper you construct; the consumer code does not change.
|
|
579
|
+
|
|
580
|
+
### BullMQ (BullMQHelper)
|
|
581
|
+
|
|
582
|
+
`BullMQHelper` accepts a `redisConnection: IRedisHelper`. Internally it:
|
|
583
|
+
- Calls `redisConnection.duplicateClient()` to create dedicated `Queue` and `Worker` connections (BullMQ requires separate connections per role).
|
|
584
|
+
- Calls `redisConnection.getClient() instanceof Cluster` to detect cluster topology and adjust BullMQ configuration.
|
|
585
|
+
|
|
586
|
+
`RedisSingleHelper` (and `RedisSentinelHelper`) are BullMQ-compatible out of the box because the framework sets `maxRetriesPerRequest: null` in `buildDefaultOpts`.
|
|
587
|
+
|
|
588
|
+
```typescript
|
|
589
|
+
import { BullMQHelper } from '@venizia/ignis-helpers/bullmq';
|
|
590
|
+
import { RedisSingleHelper } from '@venizia/ignis-helpers';
|
|
591
|
+
|
|
592
|
+
const redis = new RedisSingleHelper({ name: 'queue-redis', host, port, password });
|
|
593
|
+
|
|
594
|
+
const queue = BullMQHelper.newInstance({
|
|
595
|
+
queueName: 'email',
|
|
596
|
+
role: 'queue',
|
|
597
|
+
redisConnection: redis,
|
|
598
|
+
});
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
### Socket.IO component (SocketIOServerHelper)
|
|
602
|
+
|
|
603
|
+
- **Resolved from a binding key.** The Socket.IO component resolves an `AbstractRedisHelper` from `@app/socket-io/redis-connection`.
|
|
604
|
+
- **Three dedicated connections.** `SocketIOServerHelper` calls `duplicateClient()` three times - once each for the pub channel, sub channel, and emitter adapter.
|
|
605
|
+
- **Any topology works.** Bind single, cluster, or Sentinel - the consumer code is identical:
|
|
606
|
+
|
|
607
|
+
```typescript
|
|
608
|
+
import { AbstractRedisHelper, RedisSentinelHelper } from '@venizia/ignis-helpers';
|
|
609
|
+
|
|
610
|
+
// In your Application preConfigure:
|
|
611
|
+
const redis = new RedisSentinelHelper({ name: 'socket-redis', masterName: 'mymaster', sentinels, password });
|
|
612
|
+
this.bind<AbstractRedisHelper>({ key: '@app/socket-io/redis-connection' }).to(redis);
|
|
613
|
+
```
|
|
614
|
+
|
|
615
|
+
See the Socket.IO component documentation for the full component registration and adapter setup.
|
|
616
|
+
|
|
617
|
+
### WebSocket component (WebSocket server and emitter)
|
|
618
|
+
|
|
619
|
+
- **Resolved from a binding key.** The WebSocket component resolves an `AbstractRedisHelper` from `@app/websocket/redis-connection`.
|
|
620
|
+
- **Two dedicated connections.** `WebSocketServerHelper` calls `duplicateClient()` for its pub and sub connections; the WebSocket emitter calls `duplicateClient()` for its own pub connection.
|
|
621
|
+
- **Any topology works.** Bind single, cluster, or Sentinel:
|
|
622
|
+
|
|
623
|
+
```typescript
|
|
624
|
+
import { AbstractRedisHelper, RedisClusterHelper } from '@venizia/ignis-helpers';
|
|
625
|
+
|
|
626
|
+
const redis = new RedisClusterHelper({ name: 'ws-redis', nodes });
|
|
627
|
+
this.bind<AbstractRedisHelper>({ key: '@app/websocket/redis-connection' }).to(redis);
|
|
628
|
+
```
|
|
629
|
+
|
|
630
|
+
See the WebSocket component documentation for the full component registration.
|
|
631
|
+
|
|
632
|
+
### Casbin authorization enforcer
|
|
633
|
+
|
|
634
|
+
- **Configured via options.** The cached Casbin enforcer (`ICasbinEnforcerCachedRedis`) accepts `connection: IRedisHelper` inside its `options`.
|
|
635
|
+
- **Uses only the typed API.** It calls the helper's `get`, `set` (with `options.expiresIn`), and `del` to read, write, and invalidate cached policy keys - it never reaches the raw client.
|
|
636
|
+
- **Any topology works** as the `connection`:
|
|
637
|
+
|
|
638
|
+
```typescript
|
|
639
|
+
import type { IRedisHelper } from '@venizia/ignis-helpers';
|
|
640
|
+
|
|
641
|
+
// Shape of the cached-enforcer config (see the Authorization component docs for full setup):
|
|
642
|
+
const cached = {
|
|
643
|
+
use: true,
|
|
644
|
+
driver: CasbinEnforcerCachedDrivers.REDIS,
|
|
645
|
+
options: {
|
|
646
|
+
connection: redis as IRedisHelper, // any RedisSingleHelper / RedisClusterHelper / RedisSentinelHelper
|
|
647
|
+
expiresIn: 300_000, // cached-policy TTL in milliseconds
|
|
648
|
+
keyFn: ({ user }) => `authz:policy:${user.id}`,
|
|
649
|
+
},
|
|
650
|
+
};
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
### Binding into an application
|
|
654
|
+
|
|
655
|
+
```typescript
|
|
656
|
+
import { RedisSingleHelper } from '@venizia/ignis-helpers';
|
|
657
|
+
import { BaseApplication } from '@venizia/ignis';
|
|
658
|
+
|
|
659
|
+
class MyApp extends BaseApplication {
|
|
660
|
+
async preConfigure() {
|
|
661
|
+
const redis = new RedisSingleHelper({
|
|
662
|
+
name: 'cache',
|
|
663
|
+
host: process.env.REDIS_HOST!,
|
|
664
|
+
port: Number(process.env.REDIS_PORT),
|
|
665
|
+
password: process.env.REDIS_PASSWORD!,
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
// Bind so components and services can resolve it
|
|
669
|
+
this.bind<RedisSingleHelper>({ key: 'helpers.RedisCache' }).to(redis);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
```
|
|
673
|
+
|
|
674
|
+
## Production Notes
|
|
675
|
+
|
|
676
|
+
- **Use a singleton per logical connection.** Construct the helper once at startup and share it. Do not construct a new helper per request - each construction opens a new connection pool.
|
|
677
|
+
- **`duplicateClient()` for Pub/Sub.** A subscribed ioredis connection cannot run normal commands. Always call `duplicateClient()` to get a dedicated subscriber connection and keep the main client for data operations.
|
|
678
|
+
- **Sentinel for HA; Cluster for sharding.** These are different problems. Sentinel gives you automatic failover for a single logical master. Cluster shards data across nodes. They are not interchangeable.
|
|
679
|
+
- **TTL unit reminder:** `set.options.expiresIn` is **milliseconds**; `expire.seconds` is **seconds**; `expireAt.atEpochSeconds` is a Unix epoch in **seconds**. Mixing these up causes unexpected key expirations.
|
|
680
|
+
- **Sentinel `sentinel auth-pass` is a server-side requirement.** If your data nodes require a password, configure `sentinel auth-pass <group> <password>` in sentinel.conf in addition to the app-side `password` field. Missing it causes false failovers even when `password` is correct.
|
|
681
|
+
- **Avoid `keys()` in production.** The Redis `KEYS` command scans the entire keyspace and blocks the server. Use `execute('SCAN', [...])` for production pattern matching.
|
|
682
|
+
|
|
683
|
+
## Import Reference
|
|
684
|
+
|
|
685
|
+
```typescript
|
|
686
|
+
import {
|
|
687
|
+
// Classes
|
|
688
|
+
AbstractRedisHelper,
|
|
689
|
+
RedisSingleHelper,
|
|
690
|
+
RedisClusterHelper,
|
|
691
|
+
RedisSentinelHelper,
|
|
692
|
+
// Factory
|
|
693
|
+
createRedisHelper,
|
|
694
|
+
RedisModes,
|
|
695
|
+
// Sentinel role const-class
|
|
696
|
+
RedisSentinelRoles,
|
|
697
|
+
} from '@venizia/ignis-helpers';
|
|
698
|
+
|
|
699
|
+
import type {
|
|
700
|
+
// Interface
|
|
701
|
+
IRedisHelper,
|
|
702
|
+
// Option types
|
|
703
|
+
IRedisSingleHelperOptions,
|
|
704
|
+
IRedisSingleHelperProps,
|
|
705
|
+
IRedisClusterHelperOptions,
|
|
706
|
+
IRedisClusterHelperProps,
|
|
707
|
+
IRedisSentinelHelperOptions,
|
|
708
|
+
IRedisSentinelHelperProps,
|
|
709
|
+
IRedisHelperCallbacks,
|
|
710
|
+
// Client + enum types
|
|
711
|
+
TRedisClient,
|
|
712
|
+
TRedisMode,
|
|
713
|
+
TRedisSentinelRole,
|
|
714
|
+
} from '@venizia/ignis-helpers';
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
## See also
|
|
718
|
+
|
|
719
|
+
- [Redis overview](/extensions/helpers/redis/) - introduction and the most common tasks
|
|
720
|
+
- [Queue Helper](/extensions/helpers/queue/) - `BullMQHelper` uses the Redis helper as its connection backend
|
|
721
|
+
- [Socket.IO Component](/extensions/components/socket-io/) - uses `duplicateClient` for pub/sub adapter
|
|
722
|
+
- [WebSocket Component](/extensions/components/websocket/) - uses `duplicateClient` for pub/sub channels
|
|
723
|
+
- [Authorization Component](/extensions/components/authorization/) - Casbin enforcer uses the helper's `del`/`get`/`set` for cache operations
|
|
724
|
+
- [Migrating to the new Redis Helper API](/guides/migrations/redis-helpers-migration) - renames and breaking changes from the pre-refactor API
|
|
725
|
+
- [ioredis documentation](https://github.com/redis/ioredis) - underlying Redis client
|
|
726
|
+
- [Redis Sentinel documentation](https://redis.io/docs/management/sentinel/) - Sentinel architecture reference
|
|
727
|
+
- [RedisJSON documentation](https://redis.io/docs/stack/json/) - required for `j*` methods
|