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
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import loggerFactory from '@log4js-node/log4js-api';
|
|
2
|
+
import { IRedisClient, RedisConfig, getDefaultRedisConfigs, getNewRedisClient, parseClusterString } from './redis-client';
|
|
3
|
+
import { StreamConsumer, EventProcessor } from './stream-consumer';
|
|
4
|
+
import { augmentEvents } from './events';
|
|
5
|
+
import {
|
|
6
|
+
AllowedFactories,
|
|
7
|
+
ConsumerConfigs,
|
|
8
|
+
ConsumerGroup,
|
|
9
|
+
DeadLetterEvent,
|
|
10
|
+
HandleFunction,
|
|
11
|
+
IEvent,
|
|
12
|
+
IWaitEvent,
|
|
13
|
+
NamedEventHandler,
|
|
14
|
+
ProduceFunc,
|
|
15
|
+
RedisStreamsConfig,
|
|
16
|
+
RedisStreamsInputConfig,
|
|
17
|
+
StreamConfigs,
|
|
18
|
+
StreamGroupConsumer,
|
|
19
|
+
} from './types';
|
|
20
|
+
|
|
21
|
+
export class RedisStreams {
|
|
22
|
+
|
|
23
|
+
protected readonly groups: Map<string, Map<string, StreamGroupConsumer>> = new Map();
|
|
24
|
+
protected readonly config: RedisStreamsConfig;
|
|
25
|
+
|
|
26
|
+
constructor(protected readonly peerName: string, config?: Partial<RedisStreamsInputConfig>) {
|
|
27
|
+
this.config = RedisStreams.buildConfig(peerName, config);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
private _producerRedis: IRedisClient | undefined;
|
|
31
|
+
protected getProducerRedis(): IRedisClient {
|
|
32
|
+
if (!this._producerRedis) {
|
|
33
|
+
this._producerRedis = getNewRedisClient(this.config.redis as RedisConfig, this.config.clusterOptions);
|
|
34
|
+
}
|
|
35
|
+
return this._producerRedis;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
protected getConsumerRedis(): IRedisClient {
|
|
39
|
+
return getNewRedisClient(this.config.redis as RedisConfig, this.config.clusterOptions);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private static buildConfig(
|
|
43
|
+
peerName: string,
|
|
44
|
+
config?: Partial<RedisStreamsInputConfig>,
|
|
45
|
+
): RedisStreamsConfig {
|
|
46
|
+
let clusterNodes: { host: string; port: number }[] | undefined;
|
|
47
|
+
if (config?.redis && 'cluster' in config.redis) {
|
|
48
|
+
clusterNodes = parseClusterString((config.redis as { cluster: string }).cluster);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const redis = clusterNodes
|
|
52
|
+
? clusterNodes
|
|
53
|
+
: ((config?.redis && !('cluster' in config.redis)) ? config.redis : getDefaultRedisConfigs());
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
redis: redis as any,
|
|
57
|
+
logger: config?.logger ?? loggerFactory.getLogger(peerName),
|
|
58
|
+
...(config?.deadLetters ? { deadLetters: config.deadLetters } : {}),
|
|
59
|
+
...(config?.clusterOptions ? { clusterOptions: config.clusterOptions } : {}),
|
|
60
|
+
} as RedisStreamsConfig;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private buildConsumerConfigs(
|
|
64
|
+
streamName: string,
|
|
65
|
+
groupName: string,
|
|
66
|
+
config?: Partial<StreamConfigs>,
|
|
67
|
+
): ConsumerConfigs {
|
|
68
|
+
const base: ConsumerConfigs = {
|
|
69
|
+
claimIdleTime: 15000,
|
|
70
|
+
groupName,
|
|
71
|
+
batchSize: 5,
|
|
72
|
+
mode: 'parallel',
|
|
73
|
+
readBlockTime: 5000,
|
|
74
|
+
peerName: this.peerName,
|
|
75
|
+
maxLen: 100000,
|
|
76
|
+
streamName,
|
|
77
|
+
deadLetters: this.config.deadLetters
|
|
78
|
+
? {
|
|
79
|
+
maxRetries: this.config.deadLetters.maxRetries,
|
|
80
|
+
handler: async (...events: DeadLetterEvent[]) => {
|
|
81
|
+
/* istanbul ignore next */
|
|
82
|
+
if (!this.config.deadLetters) return;
|
|
83
|
+
const pipeline = this.getProducerRedis().pipeline();
|
|
84
|
+
this.doProduce(pipeline, this.config.deadLetters.stream, this.config.deadLetters.maxSize, ...events);
|
|
85
|
+
await pipeline.exec();
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
: undefined,
|
|
89
|
+
};
|
|
90
|
+
return Object.assign(base, config ?? {});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
protected registerConsumer(
|
|
94
|
+
streamName: string,
|
|
95
|
+
groupName: string,
|
|
96
|
+
handlers: Map<string, NamedEventHandler>,
|
|
97
|
+
config: ConsumerConfigs,
|
|
98
|
+
): StreamConsumer {
|
|
99
|
+
const handler: EventProcessor = async <T>(id: string, event: string, eventObj: IEvent<T>) => {
|
|
100
|
+
let handle = handlers.get(event);
|
|
101
|
+
if (!handle) handle = handlers.get('*');
|
|
102
|
+
if (!handle) return;
|
|
103
|
+
return handle(id, eventObj);
|
|
104
|
+
};
|
|
105
|
+
return new StreamConsumer(this.getConsumerRedis(), handler, config);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private getStreamsMap(groupName: string): Map<string, StreamGroupConsumer> {
|
|
109
|
+
let streams = this.groups.get(groupName);
|
|
110
|
+
if (!streams) {
|
|
111
|
+
streams = new Map();
|
|
112
|
+
this.groups.set(groupName, streams);
|
|
113
|
+
}
|
|
114
|
+
return streams;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
group(groupName: string): ConsumerGroup {
|
|
118
|
+
const streams = this.getStreamsMap(groupName);
|
|
119
|
+
return {
|
|
120
|
+
stream: (streamName: string, config?: Partial<StreamConfigs>) => {
|
|
121
|
+
const existing = streams.get(streamName);
|
|
122
|
+
if (existing) return existing;
|
|
123
|
+
const newStream = this.buildStream(streamName, groupName, config);
|
|
124
|
+
streams.set(streamName, newStream);
|
|
125
|
+
return newStream;
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private buildStream(
|
|
131
|
+
streamName: string,
|
|
132
|
+
groupName: string,
|
|
133
|
+
config?: Partial<StreamConfigs>,
|
|
134
|
+
): StreamGroupConsumer {
|
|
135
|
+
const handlers = new Map<string, NamedEventHandler>();
|
|
136
|
+
const readyConfigs = this.buildConsumerConfigs(streamName, groupName, config);
|
|
137
|
+
const consumer = this.registerConsumer(streamName, groupName, handlers, readyConfigs);
|
|
138
|
+
|
|
139
|
+
const consume = async () => {
|
|
140
|
+
await consumer.init();
|
|
141
|
+
consumer.start();
|
|
142
|
+
return {
|
|
143
|
+
stop: () => consumer.dispose(),
|
|
144
|
+
continue: () => { consumer.start(); },
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const handle = ((event: string | '*', handler: NamedEventHandler<any>) => {
|
|
149
|
+
handlers.set(event as string, handler);
|
|
150
|
+
return { handle, consume };
|
|
151
|
+
}) as HandleFunction<any>;
|
|
152
|
+
|
|
153
|
+
// Per-stream pipeline — isolated, not shared across streams
|
|
154
|
+
let _currentPipeline: IRedisClient | undefined;
|
|
155
|
+
const getRedisPipeline = (): IRedisClient => {
|
|
156
|
+
if (!_currentPipeline) _currentPipeline = this.getProducerRedis().multi();
|
|
157
|
+
return _currentPipeline;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const produceMany: ProduceFunc = <T>(...events: IEvent<T>[]) => {
|
|
161
|
+
const pipeline = this.doProduce(getRedisPipeline(), streamName, readyConfigs.maxLen, ...events);
|
|
162
|
+
return {
|
|
163
|
+
produceMany,
|
|
164
|
+
flush: async () => {
|
|
165
|
+
_currentPipeline = undefined;
|
|
166
|
+
await pipeline.exec();
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const produce = <T, R = any>(...events: (IEvent<T> | IWaitEvent<T>)[]) => {
|
|
172
|
+
if (events.length === 1 && (events[0] as IWaitEvent<T>).wait) {
|
|
173
|
+
const pipeline = this.doProduce(
|
|
174
|
+
this.getProducerRedis().pipeline(),
|
|
175
|
+
streamName,
|
|
176
|
+
readyConfigs.maxLen,
|
|
177
|
+
...events,
|
|
178
|
+
);
|
|
179
|
+
return {
|
|
180
|
+
wait: async (timeout: number): Promise<R> => {
|
|
181
|
+
const redis = this.getConsumerRedis();
|
|
182
|
+
const waitEvent = events[0] as IWaitEvent<T>;
|
|
183
|
+
const channel = `${waitEvent.name}_${waitEvent.time}_${waitEvent.wait!.source}`;
|
|
184
|
+
|
|
185
|
+
let timerId: NodeJS.Timeout | undefined;
|
|
186
|
+
let msgHandler: ((...args: any[]) => void) | undefined;
|
|
187
|
+
|
|
188
|
+
const cleanup = () => {
|
|
189
|
+
if (msgHandler) redis.off('message', msgHandler);
|
|
190
|
+
redis.unsubscribe(channel);
|
|
191
|
+
redis.disconnect();
|
|
192
|
+
/* istanbul ignore next */
|
|
193
|
+
if (timerId) clearTimeout(timerId);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
try {
|
|
197
|
+
const reply = await new Promise<R>(async (resolve, reject) => {
|
|
198
|
+
timerId = setTimeout(() => reject(new Error('Timeout')), timeout);
|
|
199
|
+
await redis.subscribe(channel);
|
|
200
|
+
msgHandler = (_channel: string, data: string) => resolve(JSON.parse(data)['reply']);
|
|
201
|
+
redis.on('message', msgHandler);
|
|
202
|
+
await pipeline.exec();
|
|
203
|
+
});
|
|
204
|
+
return reply;
|
|
205
|
+
} finally {
|
|
206
|
+
cleanup();
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const pipeline = this.doProduce(
|
|
213
|
+
this.getProducerRedis().pipeline(),
|
|
214
|
+
streamName,
|
|
215
|
+
readyConfigs.maxLen,
|
|
216
|
+
...events,
|
|
217
|
+
);
|
|
218
|
+
return pipeline.exec().then(() => {});
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const streamObj: StreamGroupConsumer = {
|
|
222
|
+
consume,
|
|
223
|
+
handle,
|
|
224
|
+
produceMany,
|
|
225
|
+
produce,
|
|
226
|
+
with: (events) => augmentEvents(events, streamObj),
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
return streamObj;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
private doProduce<T>(
|
|
233
|
+
pipeline: IRedisClient,
|
|
234
|
+
stream: string,
|
|
235
|
+
maxLen?: number,
|
|
236
|
+
...events: IEvent<T>[]
|
|
237
|
+
): IRedisClient {
|
|
238
|
+
if (events.length === 0) return pipeline;
|
|
239
|
+
for (const one of events) {
|
|
240
|
+
const eventString = JSON.stringify(one);
|
|
241
|
+
if (typeof maxLen === 'number') {
|
|
242
|
+
pipeline = pipeline.xadd(stream, 'MAXLEN', '~', String(maxLen), '*', one.name, eventString) as any;
|
|
243
|
+
} else {
|
|
244
|
+
pipeline = pipeline.xadd(stream, '*', one.name, eventString) as any;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return pipeline;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import loggerFactory from '@log4js-node/log4js-api';
|
|
2
|
+
import { IRedisClient } from './redis-client';
|
|
3
|
+
import { ConsumerBuffer } from './consumer-buffer';
|
|
4
|
+
import { ConsumerConfigs, DeadLetterEvent, IEvent, IWaitEvent } from './types';
|
|
5
|
+
|
|
6
|
+
export type EventProcessor = <T>(
|
|
7
|
+
id: string,
|
|
8
|
+
event: string,
|
|
9
|
+
eventObj: IEvent<T> | IWaitEvent<T>
|
|
10
|
+
) => Promise<any>;
|
|
11
|
+
|
|
12
|
+
export class StreamConsumer {
|
|
13
|
+
|
|
14
|
+
protected logger: loggerFactory.Logger;
|
|
15
|
+
protected disposing = false;
|
|
16
|
+
|
|
17
|
+
protected lastReadId = '0-0';
|
|
18
|
+
protected checkBacklog = true;
|
|
19
|
+
|
|
20
|
+
protected readonly buffer: ConsumerBuffer;
|
|
21
|
+
protected readingLoop: Promise<void> = Promise.resolve();
|
|
22
|
+
|
|
23
|
+
constructor(
|
|
24
|
+
protected readonly redis: IRedisClient,
|
|
25
|
+
protected readonly processEvent: EventProcessor,
|
|
26
|
+
protected readonly config: ConsumerConfigs,
|
|
27
|
+
) {
|
|
28
|
+
this.logger = config.logger
|
|
29
|
+
?? loggerFactory.getLogger(config.streamName + ':Consumer');
|
|
30
|
+
|
|
31
|
+
if (!this.config.batchSize) this.config.batchSize = 5;
|
|
32
|
+
|
|
33
|
+
this.buffer = new ConsumerBuffer({
|
|
34
|
+
ack: async (...ids: string[]) => {
|
|
35
|
+
await this.redis.xack(this.config.streamName, this.config.groupName, ...ids);
|
|
36
|
+
},
|
|
37
|
+
error: async (id: string, message: string[], error: Error) => {
|
|
38
|
+
this.logger.error(
|
|
39
|
+
`Error during processMessage on stream '${this.config.streamName}' with id '${id}'`,
|
|
40
|
+
error,
|
|
41
|
+
);
|
|
42
|
+
},
|
|
43
|
+
process: (id: string, message: string[]) => this.processMessage(id, message),
|
|
44
|
+
mode: this.config.mode ?? 'parallel',
|
|
45
|
+
size: this.config.batchSize,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
get size(): number {
|
|
50
|
+
return this.buffer.size;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async init(): Promise<void> {
|
|
54
|
+
await this.redis.xgroup(
|
|
55
|
+
'CREATE',
|
|
56
|
+
this.config.streamName,
|
|
57
|
+
this.config.groupName,
|
|
58
|
+
'$',
|
|
59
|
+
'MKSTREAM',
|
|
60
|
+
).catch((err: Error) => {
|
|
61
|
+
if (!err.message.includes('BUSYGROUP')) {
|
|
62
|
+
this.logger.error(err);
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
this.logger.trace('Ready...');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async start(): Promise<void> {
|
|
70
|
+
this.logger.trace('Started...');
|
|
71
|
+
this.readingLoop = this.tryReading();
|
|
72
|
+
await this.readingLoop;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
protected async tryReading(): Promise<void> {
|
|
76
|
+
while (!this.disposing) {
|
|
77
|
+
try {
|
|
78
|
+
const claimedAnything = await this.doClaim();
|
|
79
|
+
if (claimedAnything && !this.disposing) continue;
|
|
80
|
+
const dataAvailable = await this.doRead();
|
|
81
|
+
if (dataAvailable && !this.disposing) continue;
|
|
82
|
+
} catch (err: any) {
|
|
83
|
+
this.logger.error('Error while tryReading', err);
|
|
84
|
+
if (err && typeof err.message === 'string' && err.message.includes('NOGROUP')) {
|
|
85
|
+
this.checkBacklog = true;
|
|
86
|
+
this.lastReadId = '0-0';
|
|
87
|
+
await this.init();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
lastTimePendingCheck = 0;
|
|
94
|
+
|
|
95
|
+
protected async doClaim(): Promise<boolean> {
|
|
96
|
+
if (this.lastTimePendingCheck + this.config.claimIdleTime >= Date.now()) return false;
|
|
97
|
+
|
|
98
|
+
const allPending: [string, string, number, number][] = await this.redis.xpending(
|
|
99
|
+
this.config.streamName,
|
|
100
|
+
this.config.groupName,
|
|
101
|
+
'-', '+', this.config.batchSize!,
|
|
102
|
+
);
|
|
103
|
+
this.lastTimePendingCheck = Date.now();
|
|
104
|
+
|
|
105
|
+
const result = allPending.filter(([, , idleTime]) => idleTime >= this.config.claimIdleTime);
|
|
106
|
+
if (!result.length) return false;
|
|
107
|
+
|
|
108
|
+
const toBeClaimedMessages = result.map(([id]) => id);
|
|
109
|
+
const streamsEntries: [string, string[]][] = await this.redis.xclaim(
|
|
110
|
+
this.config.streamName,
|
|
111
|
+
this.config.groupName,
|
|
112
|
+
this.config.peerName,
|
|
113
|
+
this.config.claimIdleTime,
|
|
114
|
+
...toBeClaimedMessages,
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
const deadMessages = result.reduce((acc, [id, , , counter]) => {
|
|
118
|
+
const threshold = this.config.deadLetters?.maxRetries ?? Number.MAX_VALUE;
|
|
119
|
+
return counter >= threshold ? acc.add(id) : acc;
|
|
120
|
+
}, new Set<string>());
|
|
121
|
+
|
|
122
|
+
if (this.config.deadLetters && deadMessages.size) {
|
|
123
|
+
const deadIds = Array.from(deadMessages);
|
|
124
|
+
this.logger.trace('Dead Letters', JSON.stringify(deadIds));
|
|
125
|
+
const deadEntries = streamsEntries.filter(
|
|
126
|
+
entry => Array.isArray(entry) && entry.length && deadMessages.has(entry[0]),
|
|
127
|
+
);
|
|
128
|
+
await this.publishDeadLetters(...deadEntries);
|
|
129
|
+
await this.redis.xack(this.config.streamName, this.config.groupName, ...deadIds);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const goodEntries = streamsEntries.filter(
|
|
133
|
+
entry => Array.isArray(entry) && entry.length && !deadMessages.has(entry[0]),
|
|
134
|
+
);
|
|
135
|
+
if (goodEntries.length) {
|
|
136
|
+
this.logger.info('Claimed', goodEntries.length);
|
|
137
|
+
await this.buffer.add(...goodEntries);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
protected async doRead(): Promise<boolean> {
|
|
144
|
+
const streamsEntries: [string, [string, string[]][]][] = await this.redis.xreadgroup(
|
|
145
|
+
'GROUP', this.config.groupName,
|
|
146
|
+
this.config.peerName,
|
|
147
|
+
'COUNT', this.config.batchSize,
|
|
148
|
+
'BLOCK', this.config.readBlockTime,
|
|
149
|
+
'STREAMS', this.config.streamName,
|
|
150
|
+
this.checkBacklog ? this.lastReadId : '>',
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
if (!streamsEntries || streamsEntries.length === 0) {
|
|
154
|
+
this.checkBacklog = false;
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
for (const [, streamEntries] of streamsEntries) {
|
|
159
|
+
if (streamEntries.length === 0) {
|
|
160
|
+
this.checkBacklog = false;
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
this.lastReadId = streamEntries[streamEntries.length - 1][0];
|
|
164
|
+
await this.buffer.add(...streamEntries);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
protected async processMessage<T>(id: string, message: string[]): Promise<any> {
|
|
171
|
+
let event: string;
|
|
172
|
+
let eventObj: IEvent<T> | IWaitEvent<T>;
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
let value: string;
|
|
176
|
+
[event, value] = message;
|
|
177
|
+
eventObj = JSON.parse(value);
|
|
178
|
+
} catch (err) {
|
|
179
|
+
return this.logger.error(
|
|
180
|
+
'Error while parsing message. Corrupted or wrong-formatted stream message.',
|
|
181
|
+
id, message, err,
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const result = await this.processEvent(id, event, eventObj);
|
|
186
|
+
|
|
187
|
+
if ((eventObj as IWaitEvent<T>).wait) {
|
|
188
|
+
const channel = `${eventObj.name}_${eventObj.time}_${(eventObj as IWaitEvent<T>).wait!.source}`;
|
|
189
|
+
await this.redis.publish(channel, JSON.stringify({
|
|
190
|
+
reply: result,
|
|
191
|
+
wait: (eventObj as IWaitEvent<T>).wait,
|
|
192
|
+
}));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async dispose(): Promise<void> {
|
|
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
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async publishDeadLetters(...messages: [string, string[]][]): Promise<void> {
|
|
224
|
+
if (!this.config.deadLetters) return;
|
|
225
|
+
|
|
226
|
+
const finalEvents: DeadLetterEvent[] = messages.map(([id, message]) => ({
|
|
227
|
+
name: 'deadMessage',
|
|
228
|
+
v: '1.0.0',
|
|
229
|
+
time: Date.now(),
|
|
230
|
+
data: {
|
|
231
|
+
id,
|
|
232
|
+
message,
|
|
233
|
+
stream: this.config.streamName,
|
|
234
|
+
group: this.config.groupName,
|
|
235
|
+
},
|
|
236
|
+
by: { userId: this.config.peerName },
|
|
237
|
+
} as any));
|
|
238
|
+
|
|
239
|
+
await this.config.deadLetters.handler(...finalEvents);
|
|
240
|
+
}
|
|
241
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import loggerFactory from '@log4js-node/log4js-api';
|
|
2
|
+
import type { ClusterOptions } from 'ioredis';
|
|
3
|
+
|
|
4
|
+
export interface IEvent<T> {
|
|
5
|
+
time: number;
|
|
6
|
+
name: string;
|
|
7
|
+
v: string;
|
|
8
|
+
data: T;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface IWaitEvent<T> extends IEvent<T> {
|
|
12
|
+
wait: { source: string };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type DeadLetterEvent = IEvent<{
|
|
16
|
+
id: string;
|
|
17
|
+
message: string[];
|
|
18
|
+
stream: string;
|
|
19
|
+
group: string;
|
|
20
|
+
}>;
|
|
21
|
+
|
|
22
|
+
export type RedisStreamsConfig = {
|
|
23
|
+
redis: { host: string; port: number } | { host: string; port: number }[];
|
|
24
|
+
clusterOptions?: ClusterOptions;
|
|
25
|
+
logger: loggerFactory.Logger;
|
|
26
|
+
deadLetters?: {
|
|
27
|
+
stream: string;
|
|
28
|
+
maxRetries: number;
|
|
29
|
+
maxSize: number;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type RedisStreamsInputConfig = Omit<RedisStreamsConfig, 'redis'> & {
|
|
34
|
+
redis:
|
|
35
|
+
| { host: string; port: number }
|
|
36
|
+
| { cluster: string };
|
|
37
|
+
clusterOptions?: ClusterOptions;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type StreamConfigs = {
|
|
41
|
+
readBlockTime: number;
|
|
42
|
+
claimIdleTime: number;
|
|
43
|
+
batchSize: number;
|
|
44
|
+
mode: 'parallel' | 'serial';
|
|
45
|
+
maxLen: number;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type ConsumerConfigs = StreamConfigs & {
|
|
49
|
+
peerName: string;
|
|
50
|
+
streamName: string;
|
|
51
|
+
groupName: string;
|
|
52
|
+
logger?: loggerFactory.Logger;
|
|
53
|
+
deadLetters?: {
|
|
54
|
+
handler: (...event: DeadLetterEvent[]) => Promise<void>;
|
|
55
|
+
maxRetries: number;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export type NamedEventHandler<E = IEvent<any>> = (id: string, event: E) => Promise<any>;
|
|
60
|
+
|
|
61
|
+
export type ConsumeFunctions = {
|
|
62
|
+
consume: () => Promise<{
|
|
63
|
+
stop: () => Promise<void>;
|
|
64
|
+
continue: () => void;
|
|
65
|
+
}>;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
type NamedEvent<T, N extends string> = IEvent<T> & { name: N };
|
|
69
|
+
type NamedWaitEvent<T, N extends string, ReplyType = any> = IWaitEvent<T> & { name: N };
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
71
|
+
type _ReplyType = any; // kept for NamedWaitEvent ReplyType usage below
|
|
72
|
+
|
|
73
|
+
export type ProduceFunc = (...events: IEvent<any>[]) => {
|
|
74
|
+
produceMany: ProduceFunc;
|
|
75
|
+
flush: () => Promise<void>;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export type StreamGroupConsumer = ConsumeFunctions & {
|
|
79
|
+
handle: HandleFunction<any>;
|
|
80
|
+
produce: (...events: (IEvent<any> | IWaitEvent<any>)[]) => Promise<void> | {
|
|
81
|
+
wait: (timeout: number) => Promise<any>;
|
|
82
|
+
};
|
|
83
|
+
produceMany: ProduceFunc;
|
|
84
|
+
with: <O extends AllowedFactories<O>>(events: O) => WithTypedHandlers<O>;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export type ConsumerGroup = {
|
|
88
|
+
stream: (streamName: string, config?: Partial<StreamConfigs>) => StreamGroupConsumer;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
type _ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
|
|
92
|
+
type ReplyTypeOf<T> = T extends NamedWaitEvent<any, string, infer Reply> ? Reply : any;
|
|
93
|
+
type DataOfHandler<T> = T extends (...args: any[]) => IEvent<infer R> ? R : any;
|
|
94
|
+
type ArgsOf<T> = T extends (...args: infer Args) => any ? Args : never;
|
|
95
|
+
|
|
96
|
+
export type AllowedFactories<T> = {
|
|
97
|
+
[name in keyof T]: (...args: any[]) => IEvent<DataOfHandler<T[name]>> | IWaitEvent<DataOfHandler<T[name]>>;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export type HandleFunction<T> = <N extends keyof T | '*'>(
|
|
101
|
+
event: N,
|
|
102
|
+
handler: NamedEventHandler<N extends keyof T ? _ReturnType<T[N]> : IEvent<any>>
|
|
103
|
+
) => { handle: HandleFunction<T> } & ConsumeFunctions;
|
|
104
|
+
|
|
105
|
+
type WithTypedHandlers<T> = PromisifiedFunctionsMap<T> & {
|
|
106
|
+
handle: HandleFunction<T>;
|
|
107
|
+
} & Omit<StreamGroupConsumer, 'handle'>;
|
|
108
|
+
|
|
109
|
+
type PromisifiedFunctionsMap<T> = {
|
|
110
|
+
[func in keyof T]: (...args: ArgsOf<T[func]>) => _ReturnType<T[func]> extends { wait: { source: string } }
|
|
111
|
+
? { wait: (timeout: number) => Promise<ReplyTypeOf<_ReturnType<T[func]>>> }
|
|
112
|
+
: Promise<void>;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export type { NamedEvent, NamedWaitEvent, WithTypedHandlers, PromisifiedFunctionsMap };
|