ioredis-streams 1.3.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/.claude/settings.local.json +8 -0
- package/README.md +75 -3
- package/coverage.js +11 -0
- package/dist/consumer-buffer.d.ts +16 -0
- package/dist/consumer-buffer.js +53 -0
- package/dist/consumer-buffer.js.map +1 -0
- package/dist/events.d.ts +15 -0
- package/dist/events.js +30 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +5 -134
- package/dist/index.js +9 -452
- package/dist/index.js.map +1 -1
- package/dist/redis-client.d.ts +32 -0
- package/dist/redis-client.js +46 -0
- package/dist/redis-client.js.map +1 -0
- package/dist/redis-streams.d.ts +19 -0
- package/dist/redis-streams.js +198 -0
- package/dist/redis-streams.js.map +1 -0
- package/dist/stream-consumer.d.ts +28 -0
- package/dist/stream-consumer.js +177 -0
- package/dist/stream-consumer.js.map +1 -0
- package/dist/types.d.ts +112 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/docs/api.md +393 -0
- package/docs/configuration.md +129 -0
- package/docs/dead-letters.md +132 -0
- package/docs/examples.md +334 -0
- package/docs/superpowers/specs/2026-04-04-refactor-design.md +60 -0
- package/package.json +27 -5
- package/src/consumer-buffer.ts +60 -0
- package/src/events.ts +35 -0
- package/src/index.ts +18 -609
- package/src/redis-client.ts +64 -0
- package/src/redis-streams.ts +249 -0
- package/src/stream-consumer.ts +241 -0
- package/src/types.ts +115 -0
- package/test/consumer-buffer.spec.ts +154 -0
- package/test/events.spec.ts +104 -0
- package/test/helpers/fake-redis.ts +60 -0
- package/test/mocha.opts +2 -1
- package/test/redis-client.spec.ts +122 -0
- package/test/redis-streams.spec.ts +494 -0
- package/test/setup.ts +3 -0
- package/test/stream-consumer.spec.ts +493 -0
- package/.nycrc +0 -20
package/docs/api.md
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
# API Reference
|
|
2
|
+
|
|
3
|
+
## Table of Contents
|
|
4
|
+
|
|
5
|
+
- [RedisStreams](#redisstreams)
|
|
6
|
+
- [ConsumerGroup](#consumergroup)
|
|
7
|
+
- [StreamGroupConsumer](#streamgroupconsumer)
|
|
8
|
+
- [event()](#event)
|
|
9
|
+
- [eventWithReply()](#eventwithreply)
|
|
10
|
+
- [getNewRedisClient()](#getnewredisclient)
|
|
11
|
+
- [getExistingRedisClient()](#getexistingredisclient)
|
|
12
|
+
- [Types](#types)
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## RedisStreams
|
|
17
|
+
|
|
18
|
+
The main entry point. Manages Redis connections and provides access to consumer groups.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
class RedisStreams {
|
|
22
|
+
constructor(peerName: string, config?: Partial<RedisStreamsInputConfig>)
|
|
23
|
+
group(groupName: string): ConsumerGroup
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Constructor
|
|
28
|
+
|
|
29
|
+
| Parameter | Type | Description |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| `peerName` | `string` | Unique name for this service instance. Used as the consumer name in Redis and for logging. |
|
|
32
|
+
| `config` | `Partial<RedisStreamsInputConfig>` | Optional. Redis connection, logger, dead letter config. Falls back to env vars if omitted. |
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
// Minimal — reads REDIS_HOST and REDIS_PORT from env
|
|
36
|
+
const streams = new RedisStreams('order-service');
|
|
37
|
+
|
|
38
|
+
// With explicit config
|
|
39
|
+
const streams = new RedisStreams('order-service', {
|
|
40
|
+
redis: { host: 'localhost', port: 6379 },
|
|
41
|
+
deadLetters: {
|
|
42
|
+
stream: 'dead-letters',
|
|
43
|
+
maxRetries: 3,
|
|
44
|
+
maxSize: 10000,
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### `.group(groupName)`
|
|
50
|
+
|
|
51
|
+
Returns a `ConsumerGroup` scoped to the given consumer group name.
|
|
52
|
+
|
|
53
|
+
| Parameter | Type | Description |
|
|
54
|
+
|---|---|---|
|
|
55
|
+
| `groupName` | `string` | The Redis consumer group name. Created automatically if it doesn't exist. |
|
|
56
|
+
|
|
57
|
+
**Returns:** `ConsumerGroup`
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const group = streams.group('payments-processors');
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## ConsumerGroup
|
|
66
|
+
|
|
67
|
+
Scoped to a single consumer group. Use it to access individual streams within that group.
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
type ConsumerGroup = {
|
|
71
|
+
stream(streamName: string, config?: Partial<StreamConfigs>): StreamGroupConsumer
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### `.stream(streamName, config?)`
|
|
76
|
+
|
|
77
|
+
Returns a `StreamGroupConsumer` for the given stream. Calling this multiple times with the same `streamName` returns the same instance.
|
|
78
|
+
|
|
79
|
+
| Parameter | Type | Description |
|
|
80
|
+
|---|---|---|
|
|
81
|
+
| `streamName` | `string` | The Redis stream key. |
|
|
82
|
+
| `config` | `Partial<StreamConfigs>` | Optional per-stream tuning. See [Stream Tuning Options](./configuration.md#stream-tuning-options). |
|
|
83
|
+
|
|
84
|
+
**Returns:** `StreamGroupConsumer`
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
const stream = streams
|
|
88
|
+
.group('payments-processors')
|
|
89
|
+
.stream('payments', { batchSize: 10, mode: 'serial' });
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## StreamGroupConsumer
|
|
95
|
+
|
|
96
|
+
The core object. Produces events to a stream and registers handlers to consume them.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
type StreamGroupConsumer = {
|
|
100
|
+
produce(...events: IEvent<any>[]): Promise<void>
|
|
101
|
+
produce(event: IWaitEvent<any>): { wait(timeout: number): Promise<any> }
|
|
102
|
+
produceMany(...events: IEvent<any>[]): { produceMany: ProduceFunc; flush(): Promise<void> }
|
|
103
|
+
handle(event: string | '*', handler: NamedEventHandler): { handle, consume }
|
|
104
|
+
consume(): Promise<{ stop(): Promise<void>; continue(): void }>
|
|
105
|
+
with<O>(events: O): WithTypedHandlers<O>
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### `.produce(...events)`
|
|
110
|
+
|
|
111
|
+
Publishes one or more events to the stream immediately.
|
|
112
|
+
|
|
113
|
+
- For regular events: returns `Promise<void>`
|
|
114
|
+
- For a single `IWaitEvent`: returns `{ wait(timeout): Promise<ReplyType> }` — see [Request/Reply](./examples.md#requestreply-pattern)
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
// Produce one event
|
|
118
|
+
await stream.produce({ name: 'order.placed', v: '1.0.0', time: Date.now(), data: { orderId: '99' } });
|
|
119
|
+
|
|
120
|
+
// Produce multiple events in one call
|
|
121
|
+
await stream.produce(
|
|
122
|
+
{ name: 'order.placed', v: '1.0.0', time: Date.now(), data: { orderId: '99' } },
|
|
123
|
+
{ name: 'order.placed', v: '1.0.0', time: Date.now(), data: { orderId: '100' } },
|
|
124
|
+
);
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### `.produceMany(...events)`
|
|
128
|
+
|
|
129
|
+
Batches events into a Redis pipeline. Call `.flush()` to execute.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
stream
|
|
133
|
+
.produceMany(event1)
|
|
134
|
+
.produceMany(event2)
|
|
135
|
+
.produceMany(event3);
|
|
136
|
+
|
|
137
|
+
// Nothing is written until flush()
|
|
138
|
+
await stream.produceMany(event4).flush();
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### `.handle(eventName, handler)`
|
|
142
|
+
|
|
143
|
+
Registers a handler for a named event. Chain multiple `.handle()` calls.
|
|
144
|
+
|
|
145
|
+
| Parameter | Type | Description |
|
|
146
|
+
|---|---|---|
|
|
147
|
+
| `eventName` | `string \| '*'` | Event name to match, or `'*'` to catch all events not matched by a named handler. |
|
|
148
|
+
| `handler` | `(id: string, event: IEvent<T>) => Promise<any>` | Async function called with the message ID and parsed event. |
|
|
149
|
+
|
|
150
|
+
**Returns:** `{ handle, consume }` — chainable
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
stream
|
|
154
|
+
.handle('order.placed', async (id, event) => {
|
|
155
|
+
await db.orders.insert(event.data);
|
|
156
|
+
})
|
|
157
|
+
.handle('order.cancelled', async (id, event) => {
|
|
158
|
+
await db.orders.cancel(event.data.orderId);
|
|
159
|
+
})
|
|
160
|
+
.handle('*', async (id, event) => {
|
|
161
|
+
console.warn('Unhandled event:', event.name);
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
The `id` parameter is the Redis stream entry ID (e.g. `1693000000000-0`). Messages are automatically acknowledged after your handler resolves. If the handler throws, the message is **not** acknowledged and will be re-delivered.
|
|
166
|
+
|
|
167
|
+
### `.consume()`
|
|
168
|
+
|
|
169
|
+
Starts the consumer loop. Must be called after all `.handle()` registrations.
|
|
170
|
+
|
|
171
|
+
**Returns:** `Promise<{ stop(): Promise<void>; continue(): void }>`
|
|
172
|
+
|
|
173
|
+
| Method | Description |
|
|
174
|
+
|---|---|
|
|
175
|
+
| `stop()` | Gracefully stops reading new messages, waits for in-flight/buffered messages to finish processing, then removes the consumer from the Redis consumer group (`XGROUP DELCONSUMER`). Always `await` it — e.g. before your process exits on `SIGTERM` — so the consumer is actually deregistered instead of being left behind (which would otherwise happen every time a pod restarts or is deleted). |
|
|
176
|
+
| `continue()` | Resumes a stopped consumer without re-initializing. |
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
const { stop, continue: resume } = await stream.consume();
|
|
180
|
+
|
|
181
|
+
// Later
|
|
182
|
+
await stop();
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### `.with(eventFactories)`
|
|
186
|
+
|
|
187
|
+
Augments the stream object with typed producer methods derived from your event factories. This is the recommended way to produce events — it gives you full TypeScript inference.
|
|
188
|
+
|
|
189
|
+
| Parameter | Type | Description |
|
|
190
|
+
|---|---|---|
|
|
191
|
+
| `eventFactories` | `AllowedFactories<O>` | An object whose values are event factory functions (created via `event()` or `eventWithReply()`). |
|
|
192
|
+
|
|
193
|
+
**Returns:** `WithTypedHandlers<O>` — the stream object extended with a typed method for each factory
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
const OrderEvents = {
|
|
197
|
+
...event('order.placed').of<{ orderId: string; total: number }>(),
|
|
198
|
+
...event('order.cancelled').of<{ orderId: string }>(),
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const stream = streams
|
|
202
|
+
.group('order-processors')
|
|
203
|
+
.stream('orders')
|
|
204
|
+
.with(OrderEvents);
|
|
205
|
+
|
|
206
|
+
// Now you get typed, auto-completing produce methods:
|
|
207
|
+
await stream['order.placed']({ orderId: '42', total: 99.99 });
|
|
208
|
+
await stream['order.cancelled']({ orderId: '42' });
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## event()
|
|
214
|
+
|
|
215
|
+
Creates a typed event factory for a named event.
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
function event<N extends string>(name: N, version?: string): {
|
|
219
|
+
of<T>(): { [name]: (data: T, time?: number) => IEvent<T> }
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
| Parameter | Type | Default | Description |
|
|
224
|
+
|---|---|---|---|
|
|
225
|
+
| `name` | `string` | — | The event name. Used as the Redis stream field key. |
|
|
226
|
+
| `version` | `string` | `'1.0.0'` | Semantic version of the event schema. |
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
import { event } from 'ioredis-streams';
|
|
230
|
+
|
|
231
|
+
const UserEvents = {
|
|
232
|
+
...event('user.created').of<{ userId: string; email: string }>(),
|
|
233
|
+
...event('user.deleted', '2.0.0').of<{ userId: string }>(),
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
// UserEvents.['user.created']({ userId: '1', email: 'a@b.com' })
|
|
237
|
+
// → { name: 'user.created', v: '1.0.0', time: <now>, data: { userId: '1', email: 'a@b.com' } }
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Use the spread (`...`) syntax when combining multiple `event()` factories into one object for `.with()`.
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## eventWithReply()
|
|
245
|
+
|
|
246
|
+
Creates a typed event factory for a request/reply event. The consumer that handles this event can return a value which the producer receives via `.wait()`.
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
function eventWithReply<N extends string>(name: N, source: string, version?: string): {
|
|
250
|
+
of<T, ReplyType>(): { [name]: (data: T, time?: number) => IWaitEvent<T> }
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
| Parameter | Type | Default | Description |
|
|
255
|
+
|---|---|---|---|
|
|
256
|
+
| `name` | `string` | — | The event name. |
|
|
257
|
+
| `source` | `string` | — | A unique identifier for the reply channel (e.g. your service name or a request ID). |
|
|
258
|
+
| `version` | `string` | `'1.0.0'` | Semantic version. |
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
import { eventWithReply } from 'ioredis-streams';
|
|
262
|
+
|
|
263
|
+
const PricingEvents = {
|
|
264
|
+
...eventWithReply('pricing.calculate', 'order-service').of<
|
|
265
|
+
{ items: string[] },
|
|
266
|
+
{ total: number } // ReplyType
|
|
267
|
+
>(),
|
|
268
|
+
};
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
See [Request/Reply Pattern](./examples.md#requestreply-pattern) for a full example.
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
## getNewRedisClient()
|
|
276
|
+
|
|
277
|
+
Creates and returns a new ioredis client (or cluster client). Each call creates a new connection.
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
function getNewRedisClient(
|
|
281
|
+
config?: RedisConfig,
|
|
282
|
+
clusterOptions?: ClusterOptions,
|
|
283
|
+
): IRedisClient
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
import { getNewRedisClient } from 'ioredis-streams';
|
|
288
|
+
|
|
289
|
+
const client = getNewRedisClient({ host: 'localhost', port: 6379 });
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
## getExistingRedisClient()
|
|
295
|
+
|
|
296
|
+
Returns a cached singleton Redis client. The first call creates it; subsequent calls return the same instance.
|
|
297
|
+
|
|
298
|
+
> **Note:** This is a legacy export kept for backwards compatibility. Prefer `getNewRedisClient` for explicit connection management.
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
function getExistingRedisClient(
|
|
302
|
+
config?: RedisConfig,
|
|
303
|
+
clusterOptions?: ClusterOptions,
|
|
304
|
+
): IRedisClient
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
---
|
|
308
|
+
|
|
309
|
+
## Types
|
|
310
|
+
|
|
311
|
+
### `IEvent<T>`
|
|
312
|
+
|
|
313
|
+
The base event shape. All events produced and consumed by this library conform to this interface.
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
interface IEvent<T> {
|
|
317
|
+
name: string; // Event name / type identifier
|
|
318
|
+
v: string; // Schema version (e.g. '1.0.0')
|
|
319
|
+
time: number; // Unix timestamp in ms
|
|
320
|
+
data: T; // Event payload
|
|
321
|
+
}
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
### `IWaitEvent<T>`
|
|
325
|
+
|
|
326
|
+
Extends `IEvent<T>` with a `wait` field that enables the request/reply pattern.
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
interface IWaitEvent<T> extends IEvent<T> {
|
|
330
|
+
wait: { source: string };
|
|
331
|
+
}
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
### `DeadLetterEvent`
|
|
335
|
+
|
|
336
|
+
The shape of events written to the dead letter stream.
|
|
337
|
+
|
|
338
|
+
```ts
|
|
339
|
+
type DeadLetterEvent = IEvent<{
|
|
340
|
+
id: string; // Original Redis stream entry ID
|
|
341
|
+
message: string[]; // Raw stream message fields
|
|
342
|
+
stream: string; // Source stream name
|
|
343
|
+
group: string; // Consumer group name
|
|
344
|
+
}>;
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
### `RedisStreamsInputConfig`
|
|
348
|
+
|
|
349
|
+
```ts
|
|
350
|
+
type RedisStreamsInputConfig = {
|
|
351
|
+
redis: { host: string; port: number } | { cluster: string };
|
|
352
|
+
clusterOptions?: ClusterOptions;
|
|
353
|
+
logger?: loggerFactory.Logger;
|
|
354
|
+
deadLetters?: {
|
|
355
|
+
stream: string;
|
|
356
|
+
maxRetries: number;
|
|
357
|
+
maxSize: number;
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### `StreamConfigs`
|
|
363
|
+
|
|
364
|
+
Per-stream tuning options passed to `.stream(name, config)`.
|
|
365
|
+
|
|
366
|
+
```ts
|
|
367
|
+
type StreamConfigs = {
|
|
368
|
+
mode: 'parallel' | 'serial';
|
|
369
|
+
batchSize: number;
|
|
370
|
+
readBlockTime: number;
|
|
371
|
+
claimIdleTime: number;
|
|
372
|
+
maxLen: number;
|
|
373
|
+
}
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
### `NamedEventHandler<E>`
|
|
377
|
+
|
|
378
|
+
The signature for event handler functions passed to `.handle()`.
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
type NamedEventHandler<E = IEvent<any>> = (id: string, event: E) => Promise<any>;
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
### `ProduceFunc`
|
|
385
|
+
|
|
386
|
+
The return type of `.produceMany()`. Supports chaining and deferred execution.
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
type ProduceFunc = (...events: IEvent<any>[]) => {
|
|
390
|
+
produceMany: ProduceFunc;
|
|
391
|
+
flush: () => Promise<void>;
|
|
392
|
+
}
|
|
393
|
+
```
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# Configuration
|
|
2
|
+
|
|
3
|
+
## Redis Connection
|
|
4
|
+
|
|
5
|
+
`RedisStreams` resolves its Redis connection in this order:
|
|
6
|
+
|
|
7
|
+
1. **Explicit config** passed to the constructor
|
|
8
|
+
2. **Environment variables** (fallback when no config is passed)
|
|
9
|
+
|
|
10
|
+
### Environment Variables
|
|
11
|
+
|
|
12
|
+
| Variable | Description | Example |
|
|
13
|
+
|---|---|---|
|
|
14
|
+
| `REDIS_HOST` | Redis host | `localhost` |
|
|
15
|
+
| `REDIS_PORT` | Redis port | `6379` |
|
|
16
|
+
| `REDIS_CLUSTER` | Comma-separated list of cluster nodes | `host1:6379,host2:6380` |
|
|
17
|
+
|
|
18
|
+
If `REDIS_CLUSTER` is set it takes precedence over `REDIS_HOST`/`REDIS_PORT`.
|
|
19
|
+
|
|
20
|
+
### Passing Config Explicitly
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { RedisStreams } from 'ioredis-streams';
|
|
24
|
+
|
|
25
|
+
// Single node
|
|
26
|
+
const streams = new RedisStreams('my-service', {
|
|
27
|
+
redis: { host: 'localhost', port: 6379 },
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// Cluster via connection string
|
|
31
|
+
const streams = new RedisStreams('my-service', {
|
|
32
|
+
redis: { cluster: 'node1:6379,node2:6380,node3:6381' },
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Redis Cluster with Custom Options
|
|
37
|
+
|
|
38
|
+
Pass `clusterOptions` to control TLS, NAT mapping, retry strategies, and other ioredis `ClusterOptions`:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { RedisStreams } from 'ioredis-streams';
|
|
42
|
+
|
|
43
|
+
const streams = new RedisStreams('my-service', {
|
|
44
|
+
redis: { cluster: 'node1:6379,node2:6380' },
|
|
45
|
+
clusterOptions: {
|
|
46
|
+
redisOptions: {
|
|
47
|
+
tls: {},
|
|
48
|
+
password: process.env.REDIS_PASSWORD,
|
|
49
|
+
},
|
|
50
|
+
enableReadyCheck: true,
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Logger
|
|
58
|
+
|
|
59
|
+
The library uses `@log4js-node/log4js-api` for logging. By default it creates a logger named after the `peerName` you pass to the constructor. You can supply your own:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import loggerFactory from '@log4js-node/log4js-api';
|
|
63
|
+
import { RedisStreams } from 'ioredis-streams';
|
|
64
|
+
|
|
65
|
+
const logger = loggerFactory.getLogger('custom-name');
|
|
66
|
+
|
|
67
|
+
const streams = new RedisStreams('my-service', { logger });
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Stream Tuning Options
|
|
73
|
+
|
|
74
|
+
These can be set per-stream when calling `.stream(name, options)`:
|
|
75
|
+
|
|
76
|
+
| Option | Type | Default | Description |
|
|
77
|
+
|---|---|---|---|
|
|
78
|
+
| `mode` | `'parallel' \| 'serial'` | `'parallel'` | Whether messages in a batch are processed concurrently or one at a time |
|
|
79
|
+
| `batchSize` | `number` | `5` | How many messages to read per poll |
|
|
80
|
+
| `readBlockTime` | `number` (ms) | `5000` | How long to block waiting for new messages |
|
|
81
|
+
| `claimIdleTime` | `number` (ms) | `15000` | How long a message must be idle before another consumer can claim it |
|
|
82
|
+
| `maxLen` | `number` | `100000` | Maximum number of entries the stream will hold (trimmed with `MAXLEN ~`) |
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
const stream = streams
|
|
86
|
+
.group('my-group')
|
|
87
|
+
.stream('orders', {
|
|
88
|
+
mode: 'serial', // process one at a time
|
|
89
|
+
batchSize: 10,
|
|
90
|
+
readBlockTime: 2000,
|
|
91
|
+
claimIdleTime: 30000,
|
|
92
|
+
maxLen: 50000,
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Dead Letter Queue
|
|
99
|
+
|
|
100
|
+
Configure globally on the `RedisStreams` instance. Messages that fail more than `maxRetries` times are forwarded to the dead letter stream.
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
const streams = new RedisStreams('my-service', {
|
|
104
|
+
redis: { host: 'localhost', port: 6379 },
|
|
105
|
+
deadLetters: {
|
|
106
|
+
stream: 'dead-letters', // stream name to write failed messages to
|
|
107
|
+
maxRetries: 3, // number of delivery attempts before moving to dead letters
|
|
108
|
+
maxSize: 10000, // max entries in the dead letter stream
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
See [Dead Letters](./dead-letters.md) for full details on consuming and handling dead letter events.
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## Bringing Your Own Redis Client
|
|
118
|
+
|
|
119
|
+
If you already manage a Redis connection elsewhere, you can use it directly:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { getNewRedisClient, getExistingRedisClient } from 'ioredis-streams';
|
|
123
|
+
|
|
124
|
+
// Always creates a new connection
|
|
125
|
+
const client = getNewRedisClient({ host: 'localhost', port: 6379 });
|
|
126
|
+
|
|
127
|
+
// Returns a cached singleton (legacy, kept for backwards compatibility)
|
|
128
|
+
const shared = getExistingRedisClient({ host: 'localhost', port: 6379 });
|
|
129
|
+
```
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Dead Letters
|
|
2
|
+
|
|
3
|
+
When a message fails to process and is retried more times than `maxRetries` allows, it is moved to a **dead letter stream** instead of being retried indefinitely. This prevents poison-pill messages from blocking your consumer forever.
|
|
4
|
+
|
|
5
|
+
## How It Works
|
|
6
|
+
|
|
7
|
+
1. A consumer reads a message and the handler throws an error
|
|
8
|
+
2. The message is not acknowledged — Redis keeps it in the **Pending Entry List (PEL)** for the group
|
|
9
|
+
3. On the next poll cycle, another consumer (or the same one) claims idle messages via `XCLAIM`
|
|
10
|
+
4. Each time a message is claimed and retried, Redis increments its delivery counter
|
|
11
|
+
5. When the delivery counter reaches `maxRetries`, the message is written to the dead letter stream and acknowledged (removed from the PEL)
|
|
12
|
+
|
|
13
|
+
## Configuration
|
|
14
|
+
|
|
15
|
+
Enable dead letters on the `RedisStreams` instance:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { RedisStreams } from 'ioredis-streams';
|
|
19
|
+
|
|
20
|
+
const streams = new RedisStreams('my-service', {
|
|
21
|
+
redis: { host: 'localhost', port: 6379 },
|
|
22
|
+
deadLetters: {
|
|
23
|
+
stream: 'dead-letters', // name of the Redis stream to write dead letters to
|
|
24
|
+
maxRetries: 3, // delivery attempts before a message is considered dead
|
|
25
|
+
maxSize: 10000, // MAXLEN applied to the dead letter stream itself
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
> `maxRetries` counts **total delivery attempts**, not just failures. A message delivered 3 times (regardless of whether it errored each time) will be moved to dead letters on the 3rd claim cycle.
|
|
31
|
+
|
|
32
|
+
## Consuming Dead Letters
|
|
33
|
+
|
|
34
|
+
The dead letter stream is a regular Redis stream. Consume it the same way you consume any other stream:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { RedisStreams } from 'ioredis-streams';
|
|
38
|
+
import type { DeadLetterEvent } from 'ioredis-streams';
|
|
39
|
+
|
|
40
|
+
const streams = new RedisStreams('dead-letter-processor', {
|
|
41
|
+
redis: { host: 'localhost', port: 6379 },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const dlqStream = streams
|
|
45
|
+
.group('dlq-processors')
|
|
46
|
+
.stream('dead-letters'); // must match the stream name configured above
|
|
47
|
+
|
|
48
|
+
dlqStream.handle('deadMessage', async (id, event: DeadLetterEvent) => {
|
|
49
|
+
const { stream, group, message, id: originalId } = event.data;
|
|
50
|
+
|
|
51
|
+
console.error('Dead letter received:', {
|
|
52
|
+
originalId,
|
|
53
|
+
fromStream: stream,
|
|
54
|
+
fromGroup: group,
|
|
55
|
+
rawMessage: message,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Options:
|
|
59
|
+
// 1. Log to an alerting system (PagerDuty, Datadog, etc.)
|
|
60
|
+
// 2. Store in a database for manual review
|
|
61
|
+
// 3. Attempt manual replay after fixing the underlying bug
|
|
62
|
+
await alerting.notify(`Dead letter in ${stream}/${group}: ${originalId}`);
|
|
63
|
+
await db.deadLetters.insert({ originalId, stream, group, message, receivedAt: new Date() });
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
await dlqStream.consume();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Dead Letter Event Shape
|
|
70
|
+
|
|
71
|
+
Every message written to the dead letter stream has this structure:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
type DeadLetterEvent = IEvent<{
|
|
75
|
+
id: string; // The original Redis entry ID (e.g. '1693000000000-0')
|
|
76
|
+
message: string[]; // The raw Redis stream message fields [fieldName, jsonValue]
|
|
77
|
+
stream: string; // The source stream name
|
|
78
|
+
group: string; // The consumer group name
|
|
79
|
+
}>;
|
|
80
|
+
|
|
81
|
+
// Top-level fields (inherited from IEvent):
|
|
82
|
+
// name: 'deadMessage'
|
|
83
|
+
// v: '1.0.0'
|
|
84
|
+
// time: <unix ms when the dead letter was written>
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Replaying a Dead Letter
|
|
88
|
+
|
|
89
|
+
To replay a dead letter, parse the original event from `message` and re-produce it to the source stream:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
dlqStream.handle('deadMessage', async (id, event: DeadLetterEvent) => {
|
|
93
|
+
const { stream, message } = event.data;
|
|
94
|
+
|
|
95
|
+
// message is [eventName, jsonPayload]
|
|
96
|
+
const [eventName, jsonPayload] = message;
|
|
97
|
+
const originalEvent = JSON.parse(jsonPayload);
|
|
98
|
+
|
|
99
|
+
// Re-produce to the original stream
|
|
100
|
+
const sourceStream = streams.group('my-group').stream(stream);
|
|
101
|
+
await sourceStream.produce(originalEvent);
|
|
102
|
+
|
|
103
|
+
console.log(`Replayed ${eventName} back to ${stream}`);
|
|
104
|
+
});
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
> **Warning:** Only replay dead letters after the underlying bug is fixed. Replaying before the fix will result in the message becoming a dead letter again.
|
|
108
|
+
|
|
109
|
+
## Tuning Retry Behaviour
|
|
110
|
+
|
|
111
|
+
The `claimIdleTime` stream config controls how long a message must be idle before it can be claimed. Combined with `maxRetries`, this determines the total time before a message is dead-lettered:
|
|
112
|
+
|
|
113
|
+
```
|
|
114
|
+
max time before dead letter ≈ maxRetries × claimIdleTime
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Example with defaults (`maxRetries: 3`, `claimIdleTime: 15000ms`):
|
|
118
|
+
- Message fails on first delivery
|
|
119
|
+
- After 15s idle it is claimed and retried (attempt 2)
|
|
120
|
+
- After another 15s idle it is claimed and retried (attempt 3)
|
|
121
|
+
- On the 3rd claim it is moved to dead letters → ~30s total
|
|
122
|
+
|
|
123
|
+
Adjust `claimIdleTime` per stream to match the expected processing time of your handlers:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const stream = streams
|
|
127
|
+
.group('slow-jobs')
|
|
128
|
+
.stream('background-tasks', {
|
|
129
|
+
claimIdleTime: 60000, // allow 60s before claiming — handler may be slow
|
|
130
|
+
maxRetries: 5, // try 5 times before dead-lettering
|
|
131
|
+
});
|
|
132
|
+
```
|