ioredis-streams 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 +75 -3
- package/dist/stream-consumer.d.ts +2 -0
- package/dist/stream-consumer.js +16 -1
- package/dist/stream-consumer.js.map +1 -1
- package/dist/types.d.ts +1 -1
- 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/package.json +2 -2
- package/src/stream-consumer.ts +24 -1
- package/src/types.ts +1 -1
- package/test/events.spec.ts +1 -1
- package/test/redis-streams.spec.ts +22 -3
- package/test/stream-consumer.spec.ts +41 -0
package/README.md
CHANGED
|
@@ -1,5 +1,77 @@
|
|
|
1
1
|
# ioredis-streams
|
|
2
|
-
redis streams with events handlers
|
|
3
2
|
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/ioredis-streams)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
|
|
6
|
+
A TypeScript library for working with **Redis Streams** using consumer groups, typed events, and a fluent API. Built on top of [ioredis](https://github.com/luin/ioredis).
|
|
7
|
+
|
|
8
|
+
## Features
|
|
9
|
+
|
|
10
|
+
- Fluent, chainable API for producing and consuming stream events
|
|
11
|
+
- Fully typed event factories with TypeScript generics
|
|
12
|
+
- Consumer groups with **parallel** or **serial** processing modes
|
|
13
|
+
- Automatic backlog recovery and idle message claiming
|
|
14
|
+
- Request/reply pattern with `eventWithReply` and `.wait()`
|
|
15
|
+
- Dead letter queue for messages that exceed retry limits
|
|
16
|
+
- Redis Cluster support
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install ioredis-streams
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Quick Start
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { RedisStreams, event } from 'ioredis-streams';
|
|
28
|
+
|
|
29
|
+
// Define typed event factories
|
|
30
|
+
const UserEvents = {
|
|
31
|
+
...event('user.created').of<{ userId: string; email: string }>(),
|
|
32
|
+
...event('user.deleted').of<{ userId: string }>(),
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// Create the streams client (reads REDIS_HOST / REDIS_PORT from env by default)
|
|
36
|
+
const streams = new RedisStreams('my-service');
|
|
37
|
+
|
|
38
|
+
// Get a typed stream handle
|
|
39
|
+
const userStream = streams
|
|
40
|
+
.group('user-processors')
|
|
41
|
+
.stream('users')
|
|
42
|
+
.with(UserEvents);
|
|
43
|
+
|
|
44
|
+
// Produce an event
|
|
45
|
+
await userStream['user.created']({ userId: '42', email: 'zaid@example.com' });
|
|
46
|
+
|
|
47
|
+
// Consume events
|
|
48
|
+
userStream
|
|
49
|
+
.handle('user.created', async (id, event) => {
|
|
50
|
+
console.log('New user:', event.data.userId);
|
|
51
|
+
})
|
|
52
|
+
.handle('user.deleted', async (id, event) => {
|
|
53
|
+
console.log('Deleted user:', event.data.userId);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const { stop } = await userStream.consume();
|
|
57
|
+
|
|
58
|
+
// Later, to shut down gracefully:
|
|
59
|
+
stop();
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Documentation
|
|
63
|
+
|
|
64
|
+
| Topic | Description |
|
|
65
|
+
|---|---|
|
|
66
|
+
| [Configuration](docs/configuration.md) | Redis connection, env vars, cluster setup, stream tuning |
|
|
67
|
+
| [API Reference](docs/api.md) | All classes, methods, and TypeScript types |
|
|
68
|
+
| [Examples](docs/examples.md) | Real-world patterns: pub/sub, request/reply, batch producing |
|
|
69
|
+
| [Dead Letters](docs/dead-letters.md) | Handling messages that exceed retry limits |
|
|
70
|
+
|
|
71
|
+
## Author
|
|
72
|
+
|
|
73
|
+
**Zaid Al-Omari**
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT
|
|
@@ -12,6 +12,7 @@ export declare class StreamConsumer {
|
|
|
12
12
|
protected lastReadId: string;
|
|
13
13
|
protected checkBacklog: boolean;
|
|
14
14
|
protected readonly buffer: ConsumerBuffer;
|
|
15
|
+
protected readingLoop: Promise<void>;
|
|
15
16
|
constructor(redis: IRedisClient, processEvent: EventProcessor, config: ConsumerConfigs);
|
|
16
17
|
get size(): number;
|
|
17
18
|
init(): Promise<void>;
|
|
@@ -22,5 +23,6 @@ export declare class StreamConsumer {
|
|
|
22
23
|
protected doRead(): Promise<boolean>;
|
|
23
24
|
protected processMessage<T>(id: string, message: string[]): Promise<any>;
|
|
24
25
|
dispose(): Promise<void>;
|
|
26
|
+
protected removeConsumer(): Promise<void>;
|
|
25
27
|
publishDeadLetters(...messages: [string, string[]][]): Promise<void>;
|
|
26
28
|
}
|
package/dist/stream-consumer.js
CHANGED
|
@@ -15,6 +15,7 @@ class StreamConsumer {
|
|
|
15
15
|
lastReadId = '0-0';
|
|
16
16
|
checkBacklog = true;
|
|
17
17
|
buffer;
|
|
18
|
+
readingLoop = Promise.resolve();
|
|
18
19
|
constructor(redis, processEvent, config) {
|
|
19
20
|
this.redis = redis;
|
|
20
21
|
this.processEvent = processEvent;
|
|
@@ -49,7 +50,8 @@ class StreamConsumer {
|
|
|
49
50
|
}
|
|
50
51
|
async start() {
|
|
51
52
|
this.logger.trace('Started...');
|
|
52
|
-
|
|
53
|
+
this.readingLoop = this.tryReading();
|
|
54
|
+
await this.readingLoop;
|
|
53
55
|
}
|
|
54
56
|
async tryReading() {
|
|
55
57
|
while (!this.disposing) {
|
|
@@ -139,6 +141,19 @@ class StreamConsumer {
|
|
|
139
141
|
}
|
|
140
142
|
async dispose() {
|
|
141
143
|
this.disposing = true;
|
|
144
|
+
// Wait for the in-flight read/claim iteration (and everything it buffered) to finish
|
|
145
|
+
// before deregistering, so we don't delete the consumer out from under active work.
|
|
146
|
+
await this.readingLoop;
|
|
147
|
+
await this.removeConsumer();
|
|
148
|
+
}
|
|
149
|
+
async removeConsumer() {
|
|
150
|
+
try {
|
|
151
|
+
await this.redis.xgroup('DELCONSUMER', this.config.streamName, this.config.groupName, this.config.peerName);
|
|
152
|
+
this.logger.trace('Consumer removed from group', this.config.peerName);
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
this.logger.error(`Error removing consumer '${this.config.peerName}' from group '${this.config.groupName}'`, err);
|
|
156
|
+
}
|
|
142
157
|
}
|
|
143
158
|
async publishDeadLetters(...messages) {
|
|
144
159
|
if (!this.config.deadLetters)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-consumer.js","sourceRoot":"","sources":["../src/stream-consumer.ts"],"names":[],"mappings":";;;;;;AAAA,yEAAoD;AAEpD,uDAAmD;AASnD,MAAa,cAAc;
|
|
1
|
+
{"version":3,"file":"stream-consumer.js","sourceRoot":"","sources":["../src/stream-consumer.ts"],"names":[],"mappings":";;;;;;AAAA,yEAAoD;AAEpD,uDAAmD;AASnD,MAAa,cAAc;IAYJ;IACA;IACA;IAZX,MAAM,CAAuB;IAC7B,SAAS,GAAG,KAAK,CAAC;IAElB,UAAU,GAAG,KAAK,CAAC;IACnB,YAAY,GAAG,IAAI,CAAC;IAEX,MAAM,CAAiB;IAChC,WAAW,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAEzD,YACqB,KAAmB,EACnB,YAA4B,EAC5B,MAAuB;QAFvB,UAAK,GAAL,KAAK,CAAc;QACnB,iBAAY,GAAZ,YAAY,CAAgB;QAC5B,WAAM,GAAN,MAAM,CAAiB;QAE1C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;eACtB,oBAAa,CAAC,SAAS,CAAC,MAAM,CAAC,UAAU,GAAG,WAAW,CAAC,CAAC;QAE9D,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS;YAAE,IAAI,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC;QAEtD,IAAI,CAAC,MAAM,GAAG,IAAI,gCAAc,CAAC;YAC/B,GA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C,EAAE,OAAO;YACV,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE;YAChB,IAAI,EAAE;gBACJ,EAAE;gBACF,OAAO;gBACP,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU;gBAC9B,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS;aAC7B;YACD,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;SAC7B,CAAA,CAAC,CAAC;QAEX,MAAM,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,CAAC;IACxD,CAAC;CACF;AArOD,wCAqOC"}
|
package/dist/types.d.ts
CHANGED
|
@@ -62,7 +62,7 @@ export declare type ConsumerConfigs = StreamConfigs & {
|
|
|
62
62
|
export declare type NamedEventHandler<E = IEvent<any>> = (id: string, event: E) => Promise<any>;
|
|
63
63
|
export declare type ConsumeFunctions = {
|
|
64
64
|
consume: () => Promise<{
|
|
65
|
-
stop: () => void
|
|
65
|
+
stop: () => Promise<void>;
|
|
66
66
|
continue: () => void;
|
|
67
67
|
}>;
|
|
68
68
|
};
|
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
|
+
```
|
package/docs/examples.md
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
# Examples
|
|
2
|
+
|
|
3
|
+
## Table of Contents
|
|
4
|
+
|
|
5
|
+
- [Basic Produce & Consume](#basic-produce--consume)
|
|
6
|
+
- [Typed Events with `.with()`](#typed-events-with-with)
|
|
7
|
+
- [Handling All Events with `*`](#handling-all-events-with-)
|
|
8
|
+
- [Serial Processing Mode](#serial-processing-mode)
|
|
9
|
+
- [Batch Producing with `produceMany`](#batch-producing-with-producemany)
|
|
10
|
+
- [Request/Reply Pattern](#requestreply-pattern)
|
|
11
|
+
- [Multiple Streams in One Group](#multiple-streams-in-one-group)
|
|
12
|
+
- [Redis Cluster](#redis-cluster)
|
|
13
|
+
- [Graceful Shutdown](#graceful-shutdown)
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Basic Produce & Consume
|
|
18
|
+
|
|
19
|
+
The simplest end-to-end example: one producer, one consumer.
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { RedisStreams } from 'ioredis-streams';
|
|
23
|
+
|
|
24
|
+
const streams = new RedisStreams('my-service', {
|
|
25
|
+
redis: { host: 'localhost', port: 6379 },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const stream = streams.group('notifications').stream('alerts');
|
|
29
|
+
|
|
30
|
+
// Register handlers before consuming
|
|
31
|
+
stream.handle('alert.sent', async (id, event) => {
|
|
32
|
+
console.log(`[${id}] Alert sent to`, event.data.recipient);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// Start consuming
|
|
36
|
+
await stream.consume();
|
|
37
|
+
|
|
38
|
+
// Produce an event (can happen in any order relative to consume)
|
|
39
|
+
await stream.produce({
|
|
40
|
+
name: 'alert.sent',
|
|
41
|
+
v: '1.0.0',
|
|
42
|
+
time: Date.now(),
|
|
43
|
+
data: { recipient: 'ops-team', message: 'Disk usage at 90%' },
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Typed Events with `.with()`
|
|
50
|
+
|
|
51
|
+
Use `event()` factories and `.with()` to get TypeScript inference on both producing and handling.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { RedisStreams, event } from 'ioredis-streams';
|
|
55
|
+
|
|
56
|
+
// Define event schemas once
|
|
57
|
+
const OrderEvents = {
|
|
58
|
+
...event('order.placed').of<{ orderId: string; total: number; currency: string }>(),
|
|
59
|
+
...event('order.shipped').of<{ orderId: string; trackingCode: string }>(),
|
|
60
|
+
...event('order.cancelled').of<{ orderId: string; reason: string }>(),
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const streams = new RedisStreams('order-service');
|
|
64
|
+
|
|
65
|
+
const stream = streams
|
|
66
|
+
.group('order-processors')
|
|
67
|
+
.stream('orders')
|
|
68
|
+
.with(OrderEvents);
|
|
69
|
+
|
|
70
|
+
// Typed produce — data shape is enforced at compile time
|
|
71
|
+
await stream['order.placed']({ orderId: 'ORD-1', total: 49.99, currency: 'USD' });
|
|
72
|
+
await stream['order.shipped']({ orderId: 'ORD-1', trackingCode: 'TRK-XYZ' });
|
|
73
|
+
|
|
74
|
+
// Typed handle — event.data is fully inferred
|
|
75
|
+
stream
|
|
76
|
+
.handle('order.placed', async (id, event) => {
|
|
77
|
+
// event.data: { orderId: string; total: number; currency: string }
|
|
78
|
+
await db.orders.create(event.data);
|
|
79
|
+
})
|
|
80
|
+
.handle('order.shipped', async (id, event) => {
|
|
81
|
+
// event.data: { orderId: string; trackingCode: string }
|
|
82
|
+
await notifications.send(`Order ${event.data.orderId} shipped`);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
await stream.consume();
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Handling All Events with `*`
|
|
91
|
+
|
|
92
|
+
Use `'*'` as a catch-all handler for events that have no specific handler registered. Runs after named handlers are checked.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
stream
|
|
96
|
+
.handle('order.placed', async (id, event) => {
|
|
97
|
+
await db.orders.create(event.data);
|
|
98
|
+
})
|
|
99
|
+
.handle('*', async (id, event) => {
|
|
100
|
+
// Catches order.shipped, order.cancelled, and anything else
|
|
101
|
+
console.log('Unhandled event type:', event.name, event.data);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
await stream.consume();
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
> The `'*'` handler only fires if no named handler matched. If you register both `'order.placed'` and `'*'`, an `order.placed` event will only call the named handler.
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## Serial Processing Mode
|
|
112
|
+
|
|
113
|
+
By default, messages in each batch are processed in **parallel**. Switch to `serial` mode to guarantee ordering — each message waits for the previous one to finish before processing begins.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
const stream = streams
|
|
117
|
+
.group('inventory')
|
|
118
|
+
.stream('stock-updates', {
|
|
119
|
+
mode: 'serial', // one at a time, in order
|
|
120
|
+
batchSize: 1, // read one message per poll for strict FIFO
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
stream.handle('stock.adjusted', async (id, event) => {
|
|
124
|
+
// Guaranteed not to run concurrently with another stock.adjusted handler
|
|
125
|
+
await db.inventory.adjust(event.data);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
await stream.consume();
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
> **When to use serial mode:** Database writes with ordering guarantees, state machines, or any workflow where two concurrent messages would produce incorrect results.
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
|
|
135
|
+
## Batch Producing with `produceMany`
|
|
136
|
+
|
|
137
|
+
Use `produceMany` to buffer multiple events into a single Redis pipeline and flush them atomically.
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import { RedisStreams, event } from 'ioredis-streams';
|
|
141
|
+
|
|
142
|
+
const MetricEvents = {
|
|
143
|
+
...event('metric.recorded').of<{ name: string; value: number; tags: Record<string, string> }>(),
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const streams = new RedisStreams('metrics-service');
|
|
147
|
+
const stream = streams.group('metrics').stream('metrics').with(MetricEvents);
|
|
148
|
+
|
|
149
|
+
// Queue events — nothing is written to Redis yet
|
|
150
|
+
const batch = stream
|
|
151
|
+
.produceMany(MetricEvents['metric.recorded']({ name: 'cpu', value: 72, tags: { host: 'web-1' } }))
|
|
152
|
+
.produceMany(MetricEvents['metric.recorded']({ name: 'mem', value: 55, tags: { host: 'web-1' } }))
|
|
153
|
+
.produceMany(MetricEvents['metric.recorded']({ name: 'disk', value: 90, tags: { host: 'web-1' } }));
|
|
154
|
+
|
|
155
|
+
// Write all three in one round-trip
|
|
156
|
+
await batch.flush();
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
> **Why use `produceMany`?** It reduces round-trips to Redis when you need to publish several events at once, e.g. at the end of a request lifecycle or a batch job.
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## Request/Reply Pattern
|
|
164
|
+
|
|
165
|
+
Use `eventWithReply` when you need a synchronous-feeling response from a consumer. The producer publishes an event and awaits a reply over a Redis Pub/Sub channel. The consumer's handler return value becomes the reply.
|
|
166
|
+
|
|
167
|
+
### Producer service
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
import { RedisStreams, eventWithReply } from 'ioredis-streams';
|
|
171
|
+
|
|
172
|
+
const PricingEvents = {
|
|
173
|
+
...eventWithReply('pricing.calculate', 'order-service').of<
|
|
174
|
+
{ items: Array<{ sku: string; qty: number }> },
|
|
175
|
+
{ total: number; breakdown: Record<string, number> }
|
|
176
|
+
>(),
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const streams = new RedisStreams('order-service');
|
|
180
|
+
const stream = streams
|
|
181
|
+
.group('pricing')
|
|
182
|
+
.stream('pricing-requests')
|
|
183
|
+
.with(PricingEvents);
|
|
184
|
+
|
|
185
|
+
// Produce the event and wait up to 5 seconds for the reply
|
|
186
|
+
const reply = await stream['pricing.calculate']({
|
|
187
|
+
items: [{ sku: 'SKU-A', qty: 2 }, { sku: 'SKU-B', qty: 1 }],
|
|
188
|
+
}).wait(5000);
|
|
189
|
+
|
|
190
|
+
console.log('Total:', reply.total);
|
|
191
|
+
// → Total: 149.97
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Consumer service
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import { RedisStreams } from 'ioredis-streams';
|
|
198
|
+
|
|
199
|
+
const streams = new RedisStreams('pricing-service');
|
|
200
|
+
const stream = streams.group('pricing').stream('pricing-requests');
|
|
201
|
+
|
|
202
|
+
stream.handle('pricing.calculate', async (id, event) => {
|
|
203
|
+
const { items } = event.data;
|
|
204
|
+
const breakdown: Record<string, number> = {};
|
|
205
|
+
let total = 0;
|
|
206
|
+
|
|
207
|
+
for (const item of items) {
|
|
208
|
+
const price = await pricingDb.getPrice(item.sku) * item.qty;
|
|
209
|
+
breakdown[item.sku] = price;
|
|
210
|
+
total += price;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Whatever you return here is sent back to the producer's .wait() call
|
|
214
|
+
return { total, breakdown };
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
await stream.consume();
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
> **Timeouts:** If the consumer does not reply within the timeout passed to `.wait(ms)`, a `Timeout` error is thrown. Always wrap `.wait()` in try/catch for production use.
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
try {
|
|
224
|
+
const reply = await stream['pricing.calculate']({ items }).wait(5000);
|
|
225
|
+
} catch (err) {
|
|
226
|
+
if (err.message === 'Timeout') {
|
|
227
|
+
// handle timeout
|
|
228
|
+
}
|
|
229
|
+
throw err;
|
|
230
|
+
}
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
## Multiple Streams in One Group
|
|
236
|
+
|
|
237
|
+
A single consumer group can consume from multiple streams. Each stream gets its own handlers.
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import { RedisStreams, event } from 'ioredis-streams';
|
|
241
|
+
|
|
242
|
+
const streams = new RedisStreams('warehouse-service');
|
|
243
|
+
const group = streams.group('warehouse-processors');
|
|
244
|
+
|
|
245
|
+
// Stream 1: orders
|
|
246
|
+
const ordersStream = group.stream('orders').with({
|
|
247
|
+
...event('order.placed').of<{ orderId: string }>(),
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
ordersStream
|
|
251
|
+
.handle('order.placed', async (id, event) => {
|
|
252
|
+
await warehouse.reserveStock(event.data.orderId);
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
await ordersStream.consume();
|
|
256
|
+
|
|
257
|
+
// Stream 2: returns
|
|
258
|
+
const returnsStream = group.stream('returns').with({
|
|
259
|
+
...event('return.initiated').of<{ orderId: string; reason: string }>(),
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
returnsStream
|
|
263
|
+
.handle('return.initiated', async (id, event) => {
|
|
264
|
+
await warehouse.processReturn(event.data.orderId);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
await returnsStream.consume();
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
## Redis Cluster
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import { RedisStreams, event } from 'ioredis-streams';
|
|
276
|
+
|
|
277
|
+
const streams = new RedisStreams('my-service', {
|
|
278
|
+
redis: {
|
|
279
|
+
cluster: 'redis-node-1:6379,redis-node-2:6379,redis-node-3:6379',
|
|
280
|
+
},
|
|
281
|
+
clusterOptions: {
|
|
282
|
+
redisOptions: {
|
|
283
|
+
password: process.env.REDIS_PASSWORD,
|
|
284
|
+
tls: {},
|
|
285
|
+
},
|
|
286
|
+
scaleReads: 'slave',
|
|
287
|
+
},
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
const stream = streams
|
|
291
|
+
.group('my-group')
|
|
292
|
+
.stream('my-stream')
|
|
293
|
+
.with({
|
|
294
|
+
...event('job.queued').of<{ jobId: string }>(),
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
await stream['job.queued']({ jobId: 'job-123' });
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## Graceful Shutdown
|
|
303
|
+
|
|
304
|
+
Stop the consumer cleanly on process exit to avoid mid-flight message loss.
|
|
305
|
+
|
|
306
|
+
`stop()` stops reading, waits for in-flight/buffered messages to finish processing
|
|
307
|
+
and be acked, and then removes the consumer from the Redis consumer group (via
|
|
308
|
+
`XGROUP DELCONSUMER`) so it stops showing up in `XINFO CONSUMERS` and no longer
|
|
309
|
+
holds a name that a replacement pod would need. **Always `await` it** before the
|
|
310
|
+
process exits (e.g. on pod termination) — otherwise the process may exit before
|
|
311
|
+
the consumer is removed.
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
import { RedisStreams, event } from 'ioredis-streams';
|
|
315
|
+
|
|
316
|
+
const streams = new RedisStreams('my-service');
|
|
317
|
+
const stream = streams.group('workers').stream('tasks');
|
|
318
|
+
|
|
319
|
+
stream.handle('task.run', async (id, event) => {
|
|
320
|
+
await runTask(event.data);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
const { stop } = await stream.consume();
|
|
324
|
+
|
|
325
|
+
// Graceful shutdown on SIGTERM / SIGINT (e.g. Kubernetes pod termination)
|
|
326
|
+
const shutdown = async () => {
|
|
327
|
+
console.log('Shutting down...');
|
|
328
|
+
await stop(); // finishes in-flight work, then deregisters the consumer
|
|
329
|
+
process.exit(0);
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
process.on('SIGTERM', shutdown);
|
|
333
|
+
process.on('SIGINT', shutdown);
|
|
334
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ioredis-streams",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"author": "Zaid Al-Omari",
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"chai-as-promised": "^8.0.2",
|
|
58
58
|
"eslint": "^7.0.0",
|
|
59
59
|
"mocha": "^11.7.5",
|
|
60
|
-
"nyc": "^
|
|
60
|
+
"nyc": "^18.0.0",
|
|
61
61
|
"sinon": "^9.0.2",
|
|
62
62
|
"sinon-chai": "^3.5.0",
|
|
63
63
|
"source-map-support": "^0.5.19",
|
package/src/stream-consumer.ts
CHANGED
|
@@ -18,6 +18,7 @@ export class StreamConsumer {
|
|
|
18
18
|
protected checkBacklog = true;
|
|
19
19
|
|
|
20
20
|
protected readonly buffer: ConsumerBuffer;
|
|
21
|
+
protected readingLoop: Promise<void> = Promise.resolve();
|
|
21
22
|
|
|
22
23
|
constructor(
|
|
23
24
|
protected readonly redis: IRedisClient,
|
|
@@ -67,7 +68,8 @@ export class StreamConsumer {
|
|
|
67
68
|
|
|
68
69
|
async start(): Promise<void> {
|
|
69
70
|
this.logger.trace('Started...');
|
|
70
|
-
|
|
71
|
+
this.readingLoop = this.tryReading();
|
|
72
|
+
await this.readingLoop;
|
|
71
73
|
}
|
|
72
74
|
|
|
73
75
|
protected async tryReading(): Promise<void> {
|
|
@@ -195,6 +197,27 @@ export class StreamConsumer {
|
|
|
195
197
|
|
|
196
198
|
async dispose(): Promise<void> {
|
|
197
199
|
this.disposing = true;
|
|
200
|
+
// Wait for the in-flight read/claim iteration (and everything it buffered) to finish
|
|
201
|
+
// before deregistering, so we don't delete the consumer out from under active work.
|
|
202
|
+
await this.readingLoop;
|
|
203
|
+
await this.removeConsumer();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
protected async removeConsumer(): Promise<void> {
|
|
207
|
+
try {
|
|
208
|
+
await this.redis.xgroup(
|
|
209
|
+
'DELCONSUMER',
|
|
210
|
+
this.config.streamName,
|
|
211
|
+
this.config.groupName,
|
|
212
|
+
this.config.peerName,
|
|
213
|
+
);
|
|
214
|
+
this.logger.trace('Consumer removed from group', this.config.peerName);
|
|
215
|
+
} catch (err) {
|
|
216
|
+
this.logger.error(
|
|
217
|
+
`Error removing consumer '${this.config.peerName}' from group '${this.config.groupName}'`,
|
|
218
|
+
err,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
198
221
|
}
|
|
199
222
|
|
|
200
223
|
async publishDeadLetters(...messages: [string, string[]][]): Promise<void> {
|
package/src/types.ts
CHANGED
package/test/events.spec.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { StreamGroupConsumer, IEvent } from '../src/types';
|
|
|
6
6
|
|
|
7
7
|
function makeStream(produce: sinon.SinonStub = sinon.stub().resolves()): StreamGroupConsumer {
|
|
8
8
|
const s: StreamGroupConsumer = {
|
|
9
|
-
consume: async () => ({ stop: () => {}, continue: () => {} }),
|
|
9
|
+
consume: async () => ({ stop: async () => {}, continue: () => {} }),
|
|
10
10
|
handle: (() => ({ handle: s.handle, consume: s.consume })) as any,
|
|
11
11
|
produce,
|
|
12
12
|
produceMany: () => ({ produceMany: s.produceMany, flush: async () => {} }),
|
|
@@ -85,6 +85,14 @@ describe('RedisStreams - buildConfig', () => {
|
|
|
85
85
|
expect((rs as any).config.deadLetters.maxRetries).to.equal(3);
|
|
86
86
|
});
|
|
87
87
|
|
|
88
|
+
it('stores clusterOptions when provided', () => {
|
|
89
|
+
const rs = new TestRedisStreams(createFakeRedis(), [], {
|
|
90
|
+
redis: { cluster: 'n1:7001' },
|
|
91
|
+
clusterOptions: { scaleReads: 'slave' },
|
|
92
|
+
});
|
|
93
|
+
expect((rs as any).config.clusterOptions).to.deep.equal({ scaleReads: 'slave' });
|
|
94
|
+
});
|
|
95
|
+
|
|
88
96
|
it('uses the provided logger instead of creating a default one', () => {
|
|
89
97
|
const myLogger = { trace: () => {}, info: () => {}, error: () => {}, warn: () => {} };
|
|
90
98
|
const rs = new TestRedisStreams(createFakeRedis(), [], {
|
|
@@ -367,8 +375,15 @@ describe('RedisStreams - consume() and continue()', () => {
|
|
|
367
375
|
expect(stop).to.be.a('function');
|
|
368
376
|
expect(cont).to.be.a('function');
|
|
369
377
|
|
|
370
|
-
|
|
378
|
+
// let the (fire-and-forget) start() reach the blocked xreadgroup call and assign `unblock`
|
|
379
|
+
await new Promise(r => setTimeout(r, 0));
|
|
380
|
+
|
|
381
|
+
// stop() now waits for the in-flight (blocked) read to finish before resolving
|
|
382
|
+
const stopping = stop();
|
|
371
383
|
unblock();
|
|
384
|
+
await stopping;
|
|
385
|
+
|
|
386
|
+
expect(fakeConsumer.xgroup.calledWith('DELCONSUMER')).to.be.true;
|
|
372
387
|
});
|
|
373
388
|
|
|
374
389
|
it('continue() calls start() again on the consumer', async () => {
|
|
@@ -384,11 +399,15 @@ describe('RedisStreams - consume() and continue()', () => {
|
|
|
384
399
|
});
|
|
385
400
|
|
|
386
401
|
const { stop, continue: cont } = await stream.consume();
|
|
387
|
-
|
|
402
|
+
// let the (fire-and-forget) start() reach the blocked xreadgroup call and assign `unblock`
|
|
403
|
+
await new Promise(r => setTimeout(r, 0));
|
|
404
|
+
const stopping = stop();
|
|
388
405
|
unblock();
|
|
406
|
+
await stopping;
|
|
389
407
|
// after stop, calling continue re-invokes start (exits immediately since disposing=true)
|
|
390
408
|
cont();
|
|
391
|
-
|
|
409
|
+
const createCalls = fakeConsumer.xgroup.getCalls().filter((c: any) => c.args[0] === 'CREATE');
|
|
410
|
+
expect(createCalls.length).to.equal(1); // only one init
|
|
392
411
|
});
|
|
393
412
|
});
|
|
394
413
|
|
|
@@ -423,6 +423,47 @@ describe('StreamConsumer', () => {
|
|
|
423
423
|
await consumer.dispose();
|
|
424
424
|
expect(consumer.testDisposing).to.be.true;
|
|
425
425
|
});
|
|
426
|
+
|
|
427
|
+
it('removes the consumer from the group via XGROUP DELCONSUMER', async () => {
|
|
428
|
+
const fake = createFakeRedis();
|
|
429
|
+
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
430
|
+
await consumer.dispose();
|
|
431
|
+
expect(fake.xgroup.calledWith('DELCONSUMER', 'my-stream', 'my-group', 'peer-1')).to.be.true;
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
it('waits for the in-flight reading loop to finish before removing the consumer', async () => {
|
|
435
|
+
const fake = createFakeRedis();
|
|
436
|
+
fake.xpending.resolves([]);
|
|
437
|
+
let unblock!: () => void;
|
|
438
|
+
fake.xreadgroup.callsFake(async () => {
|
|
439
|
+
await new Promise<void>(r => { unblock = r; });
|
|
440
|
+
return null;
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
444
|
+
consumer.lastTimePendingCheck = Date.now(); // skip claim
|
|
445
|
+
|
|
446
|
+
const started = consumer.start();
|
|
447
|
+
// give start() a tick to enter tryReading() and register the in-flight xreadgroup call
|
|
448
|
+
await new Promise(r => setTimeout(r, 0));
|
|
449
|
+
|
|
450
|
+
const disposing = consumer.dispose();
|
|
451
|
+
// DELCONSUMER must not fire while the read is still blocked
|
|
452
|
+
expect(fake.xgroup.calledWith('DELCONSUMER')).to.be.false;
|
|
453
|
+
|
|
454
|
+
unblock();
|
|
455
|
+
await started;
|
|
456
|
+
await disposing;
|
|
457
|
+
|
|
458
|
+
expect(fake.xgroup.calledWith('DELCONSUMER', 'my-stream', 'my-group', 'peer-1')).to.be.true;
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
it('logs and swallows errors from XGROUP DELCONSUMER instead of throwing', async () => {
|
|
462
|
+
const fake = createFakeRedis();
|
|
463
|
+
fake.xgroup.rejects(new Error('connection closed'));
|
|
464
|
+
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
465
|
+
await expect(consumer.dispose()).to.eventually.not.be.rejected;
|
|
466
|
+
});
|
|
426
467
|
});
|
|
427
468
|
|
|
428
469
|
describe('publishDeadLetters()', () => {
|