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/src/index.ts
CHANGED
|
@@ -1,609 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
if (!redisPort) {
|
|
21
|
-
throw new Error('No redis connection provided (REDIS_PORT) ...')
|
|
22
|
-
}
|
|
23
|
-
return {
|
|
24
|
-
host: process.env.REDIS_HOST || '',
|
|
25
|
-
port: parseInt(process.env.REDIS_PORT || '0')
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
let _redisClient: Redis.Redis | Redis.Cluster;
|
|
30
|
-
export const getExistingRedisClient = (config = getDefaultRedisConfigs()) => {
|
|
31
|
-
if (!_redisClient) {
|
|
32
|
-
if (config instanceof Array) {
|
|
33
|
-
_redisClient = new Redis.Cluster(config);
|
|
34
|
-
} else {
|
|
35
|
-
_redisClient = new Redis(config);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
return _redisClient;
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
export const getNewRedisClient = (config = getDefaultRedisConfigs()) => {
|
|
42
|
-
if (config instanceof Array) {
|
|
43
|
-
return new Redis.Cluster(config);
|
|
44
|
-
} else {
|
|
45
|
-
return new Redis(config);
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
export interface IEvent<T> {
|
|
50
|
-
time: number;
|
|
51
|
-
name: string;
|
|
52
|
-
v: string;
|
|
53
|
-
data: T;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export interface IWaitEvent<T> extends IEvent<T> {
|
|
57
|
-
wait: { source: string };
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export class RedisStreams {
|
|
61
|
-
|
|
62
|
-
protected groups: Map<string, Map<string, StreamGroupConsumer>> = new Map();
|
|
63
|
-
protected config: RedisStreamsConfig;
|
|
64
|
-
|
|
65
|
-
constructor(protected peerName: string, config?: Partial<RedisStreamsInputConfig>) {
|
|
66
|
-
this.config = RedisStreams.getDefaultConfigs(peerName, config);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
private getConsumerRedis() {
|
|
70
|
-
return getNewRedisClient(this.config.redis);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
private getProducerRedis() {
|
|
74
|
-
return getExistingRedisClient(this.config.redis);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
private static getDefaultConfigs(peerName: string, config?: Partial<RedisStreamsInputConfig>) {
|
|
78
|
-
let cluster: string | undefined;
|
|
79
|
-
if (config?.redis && 'cluster' in config.redis) {
|
|
80
|
-
cluster = (config!.redis! as { cluster: string }).cluster;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
return <RedisStreamsConfig>Object.assign(<RedisStreamsConfig>{
|
|
84
|
-
redis: getDefaultRedisConfigs(),
|
|
85
|
-
logger: loggerFactory.getLogger(peerName),
|
|
86
|
-
}, config || {},
|
|
87
|
-
{ ...(cluster ? { redis: parseClusterString(cluster) } : {}) });
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
private buildConsumerConfigs(streamName: string, groupName: string, config?: Partial<StreamConfigs>) {
|
|
91
|
-
return <ConsumerConfigs>Object.assign(<ConsumerConfigs>{
|
|
92
|
-
claimIdleTime: 15000,
|
|
93
|
-
groupName,
|
|
94
|
-
batchSize: 5,
|
|
95
|
-
mode: 'parallel',
|
|
96
|
-
readBlockTime: 5000,
|
|
97
|
-
peerName: this.peerName!,
|
|
98
|
-
maxLen: 100000,
|
|
99
|
-
streamName,
|
|
100
|
-
deadLetters: this.config.deadLetters ? {
|
|
101
|
-
maxRetries: this.config.deadLetters.maxRetries,
|
|
102
|
-
handler: async (...events) => {
|
|
103
|
-
if (!this.config.deadLetters) return;
|
|
104
|
-
const redis = this.getProducerRedis().pipeline();
|
|
105
|
-
this.doProduce(redis, this.config.deadLetters.stream, this.config.deadLetters.maxSize, ...events);
|
|
106
|
-
await redis.exec();
|
|
107
|
-
}
|
|
108
|
-
} : undefined
|
|
109
|
-
}, config || {});
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
private register(streamName: string, groupName: string, handlers: Map<string, NamedEventHandler>, config: ConsumerConfigs) {
|
|
113
|
-
const handler = async <T>(id: string, event: string | '*', eventObj: IEvent<T>) => {
|
|
114
|
-
let handle = handlers.get(event);
|
|
115
|
-
if (!handle) handle = handlers.get('*');
|
|
116
|
-
if (!handle) {
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
return handle(id, eventObj);
|
|
120
|
-
};
|
|
121
|
-
const newStream = new StreamConsumer(this.getConsumerRedis(), handler, config);
|
|
122
|
-
return newStream;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
private getStreamsMap(groupName: string) {
|
|
126
|
-
let streams = this.groups.get(groupName);
|
|
127
|
-
if (!streams) {
|
|
128
|
-
streams = new Map<string, any>();
|
|
129
|
-
this.groups.set(groupName, streams);
|
|
130
|
-
}
|
|
131
|
-
return streams;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
group(groupName: string) {
|
|
135
|
-
const streams = this.getStreamsMap(groupName);
|
|
136
|
-
return <ConsumerGroup>{
|
|
137
|
-
stream: (streamName: string, config?: Partial<StreamConfigs>) => {
|
|
138
|
-
const stream = streams.get(streamName);
|
|
139
|
-
if (stream) return stream;
|
|
140
|
-
const newStream = this.stream(streamName, groupName, config);
|
|
141
|
-
streams.set(streamName, newStream);
|
|
142
|
-
return newStream;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
private stream(streamName: string, groupName: string, config?: Partial<StreamConfigs>) {
|
|
148
|
-
const handlers = new Map<string, NamedEventHandler>();
|
|
149
|
-
const readyConfigs = this.buildConsumerConfigs(streamName, groupName, config);
|
|
150
|
-
const stream = this.register(streamName, groupName, handlers, readyConfigs);
|
|
151
|
-
const consume = async () => {
|
|
152
|
-
await stream.init();
|
|
153
|
-
stream.start();
|
|
154
|
-
return {
|
|
155
|
-
stop: () => stream.dispose(),
|
|
156
|
-
continue: () => { stream.start(); return; }
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
const handle = <T extends IEvent<D>, D>(event: string | '*', handler: NamedEventHandler<T>) => {
|
|
160
|
-
handlers.set(event, <NamedEventHandler>handler);
|
|
161
|
-
return { handle, consume };
|
|
162
|
-
};
|
|
163
|
-
const produceMany = <T>(...events: IEvent<T>[]) => {
|
|
164
|
-
const redis = this.doProduce(this.getRedisPipeline(), streamName, readyConfigs.maxLen, ...events);
|
|
165
|
-
return {
|
|
166
|
-
produceMany,
|
|
167
|
-
flush: async () => {
|
|
168
|
-
this._currentPipeline = undefined;
|
|
169
|
-
await redis.exec();
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
const produce = <T, R = any>(...events: (IEvent<T> | IWaitEvent<T>)[]) => {
|
|
174
|
-
if (events.length === 1 && events[0]['wait']) {
|
|
175
|
-
const pipeline = this.doProduce(this.getProducerRedis().pipeline(), streamName, readyConfigs.maxLen, ...events);
|
|
176
|
-
return {
|
|
177
|
-
wait: async (timeout: number) => {
|
|
178
|
-
const redis = this.getConsumerRedis();
|
|
179
|
-
const channel = events[0].name + '_' + events[0].time + '_' + events[0]['wait']?.['source'];
|
|
180
|
-
let id: NodeJS.Timeout | undefined;
|
|
181
|
-
let handler: ((...args: any[]) => void) | undefined;
|
|
182
|
-
const cleanup = () => {
|
|
183
|
-
if (handler) redis.off('message', handler);
|
|
184
|
-
redis.unsubscribe(channel);
|
|
185
|
-
redis.disconnect();
|
|
186
|
-
if (id) clearTimeout(id);
|
|
187
|
-
}
|
|
188
|
-
try {
|
|
189
|
-
const reply = await new Promise<R>(async (resolve, reject) => {
|
|
190
|
-
id = setTimeout(() => reject(new Error('Timeout')), timeout);
|
|
191
|
-
await redis.subscribe(channel);
|
|
192
|
-
handler = (commingChannel, data) => resolve(JSON.parse(data)['reply']);
|
|
193
|
-
redis.on('message', handler);
|
|
194
|
-
await pipeline.exec();
|
|
195
|
-
});
|
|
196
|
-
return reply;
|
|
197
|
-
} finally {
|
|
198
|
-
cleanup();
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
} else {
|
|
203
|
-
const r1 = this.doProduce(this.getProducerRedis().pipeline(), streamName, readyConfigs.maxLen, ...events);
|
|
204
|
-
return r1.exec().then(r => { return; });
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
const newStream = <StreamGroupConsumer>{
|
|
209
|
-
consume,
|
|
210
|
-
handle,
|
|
211
|
-
produceMany,
|
|
212
|
-
produce,
|
|
213
|
-
with: (events) => augmentEvents(events, newStream)
|
|
214
|
-
}
|
|
215
|
-
return newStream;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
private _currentPipeline: Pipeline | undefined;
|
|
219
|
-
private getRedisPipeline() {
|
|
220
|
-
if (!this._currentPipeline) this._currentPipeline = this.getProducerRedis().multi();
|
|
221
|
-
return this._currentPipeline;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
private doProduce<T>(redis: Pipeline, stream: string, maxLen?: number, ...events: IEvent<T>[]) {
|
|
225
|
-
if (events.length === 0) return redis;
|
|
226
|
-
for (const one of events) {
|
|
227
|
-
const eventString = JSON.stringify(one);
|
|
228
|
-
if (typeof maxLen === 'number') {
|
|
229
|
-
redis = redis.xadd(stream, 'MAXLEN', '~', String(maxLen), '*', one.name, eventString);
|
|
230
|
-
} else {
|
|
231
|
-
redis = redis.xadd(stream, '*', one.name, eventString);
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
return redis;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
type EventProccessor = <T>(id: string, event: string, eventObj: IEvent<T> | IWaitEvent<T>) => Promise<any>;
|
|
239
|
-
class StreamConsumer {
|
|
240
|
-
|
|
241
|
-
protected logger!: loggerFactory.Logger;
|
|
242
|
-
private disposing = false;
|
|
243
|
-
|
|
244
|
-
private lastReadId = '0-0';
|
|
245
|
-
private checkBacklog = true;
|
|
246
|
-
|
|
247
|
-
private buffer: ConsumerBuffer;
|
|
248
|
-
|
|
249
|
-
constructor(
|
|
250
|
-
protected redis: Redis.Redis | Redis.Cluster,
|
|
251
|
-
protected processEvent: EventProccessor,
|
|
252
|
-
protected config: ConsumerConfigs) {
|
|
253
|
-
|
|
254
|
-
if (this.config.logger) this.logger = this.config.logger;
|
|
255
|
-
else this.logger = loggerFactory.getLogger(this.config.streamName + ':Consumer');
|
|
256
|
-
if (!this.config.batchSize) this.config.batchSize = 5;
|
|
257
|
-
this.buffer = new ConsumerBuffer({
|
|
258
|
-
ack: async (...ids: string[]) => {
|
|
259
|
-
await this.redis.xack(
|
|
260
|
-
this.config.streamName,
|
|
261
|
-
this.config.groupName, ...ids
|
|
262
|
-
);
|
|
263
|
-
},
|
|
264
|
-
error: async (id: string, message: string[], error: Error) => {
|
|
265
|
-
this.logger.error(`Error during processMessage on stream '${this.config.streamName}' with id '${id}'`, error);
|
|
266
|
-
},
|
|
267
|
-
process: async (id: string, message: string[]) => {
|
|
268
|
-
return this.processMessage(id, message);
|
|
269
|
-
},
|
|
270
|
-
mode: this.config.mode || 'parallel',
|
|
271
|
-
size: this.config.batchSize
|
|
272
|
-
});
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
async init() {
|
|
276
|
-
await this.redis.xgroup(
|
|
277
|
-
'CREATE',
|
|
278
|
-
this.config.streamName,
|
|
279
|
-
this.config.groupName,
|
|
280
|
-
'$',
|
|
281
|
-
'MKSTREAM'
|
|
282
|
-
).catch(err => {
|
|
283
|
-
if (!err.message.includes('BUSYGROUP')) {
|
|
284
|
-
this.logger.error(err);
|
|
285
|
-
throw err;
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
this.logger.trace('Ready...');
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
async start() {
|
|
292
|
-
this.logger.trace('Started...');
|
|
293
|
-
await this.tryReading()
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
protected async tryReading() {
|
|
297
|
-
while (!this.disposing) {
|
|
298
|
-
try {
|
|
299
|
-
const claimedAnything = await this.doClaim()
|
|
300
|
-
if (claimedAnything && !this.disposing) continue;
|
|
301
|
-
const dataAvaliable = await this.doRead();
|
|
302
|
-
if (dataAvaliable && !this.disposing) continue;
|
|
303
|
-
} catch (err: any) {
|
|
304
|
-
this.logger.error('Error while tryReading', err);
|
|
305
|
-
if (err && typeof err.message === 'string' && err.message.includes('NOGROUP')) {
|
|
306
|
-
await this.init()
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
lastTimePendingCheck = 0;
|
|
313
|
-
private async doClaim() {
|
|
314
|
-
if (this.lastTimePendingCheck + this.config.claimIdleTime >= Date.now()) return false;
|
|
315
|
-
const result: ([string, string, number, number])[] = await this.redis.xpending(
|
|
316
|
-
this.config.streamName,
|
|
317
|
-
this.config.groupName,
|
|
318
|
-
'IDLE', this.config.claimIdleTime,
|
|
319
|
-
'-', '+', this.config.batchSize!
|
|
320
|
-
);
|
|
321
|
-
this.lastTimePendingCheck = Date.now();
|
|
322
|
-
if (!result.length) return false;
|
|
323
|
-
|
|
324
|
-
const toBeClaimedMessages = result.map(([id]) => id);
|
|
325
|
-
const streamsEntries = await this.redis.xclaim(
|
|
326
|
-
this.config.streamName,
|
|
327
|
-
this.config.groupName,
|
|
328
|
-
this.config.peerName,
|
|
329
|
-
this.config.claimIdleTime,
|
|
330
|
-
...toBeClaimedMessages,
|
|
331
|
-
);
|
|
332
|
-
|
|
333
|
-
const deadMessages = result.reduce((p, [id, , , counter]) => {
|
|
334
|
-
return (counter >= (this.config.deadLetters?.maxRetries || Number.MAX_VALUE)) ? p.add(id) : p;
|
|
335
|
-
}, new Set<string>());
|
|
336
|
-
|
|
337
|
-
if (this.config.deadLetters && deadMessages.size) {
|
|
338
|
-
const deadIds = Array.from(deadMessages);
|
|
339
|
-
this.logger.trace('Dead Letters', JSON.stringify(deadIds));
|
|
340
|
-
const deadStreamsEntries = streamsEntries.filter(entry => (entry instanceof Array) && entry.length && deadMessages.has(entry[0]));
|
|
341
|
-
await this.publishDeadLetters(...deadStreamsEntries);
|
|
342
|
-
await this.redis.xack(this.config.streamName,
|
|
343
|
-
this.config.groupName, ...deadIds);
|
|
344
|
-
}
|
|
345
|
-
const goodStreamsEntries = streamsEntries.filter((entry => (entry instanceof Array) && entry.length && !deadMessages.has(entry[0])));
|
|
346
|
-
if (goodStreamsEntries.length) {
|
|
347
|
-
this.logger.info('Claimed', goodStreamsEntries.length);
|
|
348
|
-
await this.buffer.add(...goodStreamsEntries);
|
|
349
|
-
}
|
|
350
|
-
return true;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
protected async doRead() {
|
|
354
|
-
const streamsEntries = await this.redis.xreadgroup(
|
|
355
|
-
'GROUP', this.config.groupName,
|
|
356
|
-
this.config.peerName,
|
|
357
|
-
'COUNT', this.config.batchSize,
|
|
358
|
-
'BLOCK', this.config.readBlockTime,
|
|
359
|
-
'STREAMS', this.config.streamName,
|
|
360
|
-
this.checkBacklog ? this.lastReadId : '>'
|
|
361
|
-
);
|
|
362
|
-
if (!streamsEntries || streamsEntries.length === 0) {
|
|
363
|
-
this.checkBacklog = false;
|
|
364
|
-
return false;
|
|
365
|
-
}
|
|
366
|
-
for (const [steamName, streamEntries] of streamsEntries) {
|
|
367
|
-
if (streamEntries.length === 0) {
|
|
368
|
-
this.checkBacklog = false;
|
|
369
|
-
return false;
|
|
370
|
-
}
|
|
371
|
-
this.lastReadId = streamEntries[streamEntries.length - 1][0]
|
|
372
|
-
await this.buffer.add(...streamEntries);
|
|
373
|
-
}
|
|
374
|
-
return true;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
protected async processMessage<T>(id: string, message: string[]) {
|
|
378
|
-
let event: string;
|
|
379
|
-
let eventObj: IEvent<T> | IWaitEvent<T>
|
|
380
|
-
try {
|
|
381
|
-
let value: string;
|
|
382
|
-
[event, value] = message;
|
|
383
|
-
eventObj = JSON.parse(value);
|
|
384
|
-
}
|
|
385
|
-
catch (err) {
|
|
386
|
-
//log corrupted messages
|
|
387
|
-
return this.logger.error('Error while parsing message. Corrupted or wrong-formatted stream message.', id, message, err);
|
|
388
|
-
}
|
|
389
|
-
const result = await this.processEvent(id, event, eventObj);
|
|
390
|
-
if (eventObj['wait']) {
|
|
391
|
-
const channel = eventObj.name + '_' + eventObj.time + '_' + eventObj['wait']?.['source'];
|
|
392
|
-
await this.redis.publish(channel, JSON.stringify({
|
|
393
|
-
reply: result,
|
|
394
|
-
wait: eventObj['wait']
|
|
395
|
-
}));
|
|
396
|
-
}
|
|
397
|
-
return result;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
async dispose() {
|
|
401
|
-
this.disposing = true;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
async publishDeadLetters(...messages: [string, string[]][]) {
|
|
405
|
-
if (!this.config.deadLetters) return;
|
|
406
|
-
const finalEvents = messages.map(([id, message]) => {
|
|
407
|
-
return <DeadLetterEvent>{
|
|
408
|
-
name: 'deadMessage',
|
|
409
|
-
v: '1.0.0',
|
|
410
|
-
time: Date.now(),
|
|
411
|
-
data: {
|
|
412
|
-
id,
|
|
413
|
-
message,
|
|
414
|
-
stream: this.config.streamName,
|
|
415
|
-
group: this.config.groupName,
|
|
416
|
-
},
|
|
417
|
-
by: {
|
|
418
|
-
userId: this.config.peerName,
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
});
|
|
422
|
-
await this.config.deadLetters.handler(...finalEvents);
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
class ConsumerBuffer {
|
|
427
|
-
|
|
428
|
-
buffer: [string, string[]][] = [];
|
|
429
|
-
constructor(protected configs: {
|
|
430
|
-
ack: (...id: string[]) => Promise<void>,
|
|
431
|
-
process: (id: string, message: string[]) => Promise<any>,
|
|
432
|
-
error: (id: string, message: string[], error: Error) => Promise<void>,
|
|
433
|
-
mode: 'parallel' | 'serial',
|
|
434
|
-
size: number
|
|
435
|
-
}) {
|
|
436
|
-
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
get size() {
|
|
440
|
-
return this.configs.size;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
async add(...rawMessages: [string, string[]][]) {
|
|
444
|
-
this.buffer.push(...rawMessages);
|
|
445
|
-
return this.do();
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
isDoing = false;
|
|
449
|
-
async do() {
|
|
450
|
-
if (this.isDoing) return;
|
|
451
|
-
this.isDoing = true;
|
|
452
|
-
const toBeAck: string[] = [];
|
|
453
|
-
const operations: Promise<void>[] = [];
|
|
454
|
-
while (this.buffer.length) {
|
|
455
|
-
const [id, message] = this.buffer.shift()!;
|
|
456
|
-
const operation = this.configs.process(id, message)
|
|
457
|
-
.then(_ => {
|
|
458
|
-
toBeAck.push(id);
|
|
459
|
-
})
|
|
460
|
-
.catch(err => this.configs.error(id, message, err).catch());
|
|
461
|
-
if (this.configs.mode === 'serial') {
|
|
462
|
-
await operation;
|
|
463
|
-
await this.configs.ack(id);
|
|
464
|
-
} else {
|
|
465
|
-
operations.push(operation);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
this.isDoing = false;
|
|
469
|
-
if (this.configs.mode === 'parallel') {
|
|
470
|
-
await Promise.all(operations);
|
|
471
|
-
if (toBeAck.length) {
|
|
472
|
-
await this.configs.ack(...toBeAck);
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
const augmentEvents = <T extends AllowedFactories<R>, R>(events: T, stream: StreamGroupConsumer) => {
|
|
479
|
-
return Object.keys(events).reduce((p, c) => {
|
|
480
|
-
const factory = events[c as keyof T];
|
|
481
|
-
p[c] = (...args: any[]) => stream.produce(factory(...args))
|
|
482
|
-
return p;
|
|
483
|
-
}, { ...events, ...stream })
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
export type DeadLetterEvent = IEvent<{
|
|
487
|
-
id: string,
|
|
488
|
-
message: string[],
|
|
489
|
-
stream: string,
|
|
490
|
-
group: string,
|
|
491
|
-
}>;
|
|
492
|
-
|
|
493
|
-
export type RedisStreamsConfig = {
|
|
494
|
-
redis: {
|
|
495
|
-
host: string,
|
|
496
|
-
port: number
|
|
497
|
-
},
|
|
498
|
-
logger: loggerFactory.Logger;
|
|
499
|
-
deadLetters?: {
|
|
500
|
-
stream: string;
|
|
501
|
-
maxRetries: number;
|
|
502
|
-
maxSize: number;
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
export type RedisStreamsInputConfig = Omit<RedisStreamsConfig, 'redis'> & {
|
|
507
|
-
redis: {
|
|
508
|
-
host: string;
|
|
509
|
-
port: number;
|
|
510
|
-
}
|
|
511
|
-
| {
|
|
512
|
-
cluster: string;
|
|
513
|
-
};
|
|
514
|
-
};
|
|
515
|
-
|
|
516
|
-
export type StreamConfigs = {
|
|
517
|
-
readBlockTime: number;
|
|
518
|
-
claimIdleTime: number;
|
|
519
|
-
batchSize: number;
|
|
520
|
-
mode: 'parallel' | 'serial';
|
|
521
|
-
maxLen: number;
|
|
522
|
-
};
|
|
523
|
-
|
|
524
|
-
type ConsumerConfigs = StreamConfigs & {
|
|
525
|
-
peerName: string;
|
|
526
|
-
streamName: string;
|
|
527
|
-
groupName: string;
|
|
528
|
-
logger?: loggerFactory.Logger;
|
|
529
|
-
deadLetters?: {
|
|
530
|
-
handler: (...event: DeadLetterEvent[]) => Promise<void>
|
|
531
|
-
maxRetries: number
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
export type ProduceFunc = (...events: IEvent<any>[]) => {
|
|
536
|
-
produceMany: ProduceFunc;
|
|
537
|
-
flush: () => Promise<void>;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
export type StreamGroupConsumer = ConsumeFunctions & {
|
|
541
|
-
handle: HandleFunction<any>;
|
|
542
|
-
produce: (...events: (IEvent<any> | IWaitEvent<any>)[]) => Promise<void> | {
|
|
543
|
-
wait: (timeout: number) => Promise<any>;
|
|
544
|
-
}
|
|
545
|
-
produceMany: ProduceFunc;
|
|
546
|
-
with: <O extends AllowedFactories<O>>(events: O) => WithTypedHandlers<O>;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
export type ConsumerGroup = {
|
|
550
|
-
stream: (streamName: string, config?: Partial<StreamConfigs>) => StreamGroupConsumer;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
type NamedEvent<T, N extends string> = IEvent<T> & { name: N };
|
|
554
|
-
type NamedWaitEvent<T, N extends string, ReplyType = any> = IWaitEvent<T> & { name: N };
|
|
555
|
-
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
|
|
556
|
-
type ReplyTypeOf<T> = T extends NamedWaitEvent<any, string, infer Reply> ? Reply : any
|
|
557
|
-
type DataOfHandler<T> = T extends (...args: any[]) => IEvent<infer R> ? R : any;
|
|
558
|
-
type ArgsOf<T> = T extends (...args: infer Args) => any ? Args : never;
|
|
559
|
-
|
|
560
|
-
type AllowedFactories<T> = { [name in (keyof T)]: (...args: any[]) => IEvent<DataOfHandler<T[name]>> | IWaitEvent<DataOfHandler<T[name]>> };
|
|
561
|
-
export type NamedEventHandler<E = IEvent<any>> = (id: string, event: E) => Promise<any>;
|
|
562
|
-
|
|
563
|
-
export type ConsumeFunctions = {
|
|
564
|
-
consume: () => Promise<{
|
|
565
|
-
stop: () => void;
|
|
566
|
-
continue: () => void;
|
|
567
|
-
}>;
|
|
568
|
-
}
|
|
569
|
-
export type HandleFunction<T> = <N extends (keyof T | '*') >(event: N, handler: NamedEventHandler<N extends keyof T ? ReturnType<T[N]> : IEvent<any>>) => {
|
|
570
|
-
handle: HandleFunction<T>;
|
|
571
|
-
} & ConsumeFunctions;
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
type WithTypedHandlers<T> = PromisifiedFunctionsMap<T> & {
|
|
575
|
-
handle: HandleFunction<T>
|
|
576
|
-
} & Omit<StreamGroupConsumer, 'handle'>;
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
type PromisifiedFunctionsMap<T> = {
|
|
580
|
-
[func in keyof T]: (...args: ArgsOf<T[func]>) => ReturnType<T[func]> extends { wait: { source: string } } ? { wait: (timeout: number) => Promise<ReplyTypeOf<ReturnType<T[func]>>> } : Promise<void>
|
|
581
|
-
};
|
|
582
|
-
|
|
583
|
-
export const event = <N extends string>(name: N, v = '1.0.0') => {
|
|
584
|
-
type ReturnType<T, N extends string> = {
|
|
585
|
-
[K in N]: (data: T, time?: number) => NamedEvent<T, N>;
|
|
586
|
-
};
|
|
587
|
-
return {
|
|
588
|
-
of: <T>() => {
|
|
589
|
-
return {
|
|
590
|
-
[name]: (data: T, time = Date.now()) => ({ name, v, data, time })
|
|
591
|
-
} as ReturnType<T, N>
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
export const eventWithReply = <N extends string>(name: N, source: string, v = '1.0.0') => {
|
|
597
|
-
type ReturnType<T, N extends string, ReplyType> = {
|
|
598
|
-
[K in N]: (data: T, time?: number) => NamedWaitEvent<T, N, ReplyType>;
|
|
599
|
-
};
|
|
600
|
-
return {
|
|
601
|
-
of: <T, ReplyType = any>() => {
|
|
602
|
-
return {
|
|
603
|
-
[name]: (data: T, time = Date.now()) => (<IWaitEvent<T>>{
|
|
604
|
-
name, v, data, time, wait: { source }
|
|
605
|
-
})
|
|
606
|
-
} as ReturnType<T, N, ReplyType>
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
}
|
|
1
|
+
export { RedisStreams } from './redis-streams';
|
|
2
|
+
export { getNewRedisClient, getExistingRedisClient } from './redis-client';
|
|
3
|
+
export type { IRedisClient, RedisConfig } from './redis-client';
|
|
4
|
+
export { event, eventWithReply } from './events';
|
|
5
|
+
export type {
|
|
6
|
+
IEvent,
|
|
7
|
+
IWaitEvent,
|
|
8
|
+
DeadLetterEvent,
|
|
9
|
+
RedisStreamsConfig,
|
|
10
|
+
RedisStreamsInputConfig,
|
|
11
|
+
StreamConfigs,
|
|
12
|
+
StreamGroupConsumer,
|
|
13
|
+
ConsumerGroup,
|
|
14
|
+
ConsumeFunctions,
|
|
15
|
+
HandleFunction,
|
|
16
|
+
ProduceFunc,
|
|
17
|
+
NamedEventHandler,
|
|
18
|
+
} from './types';
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import Redis, { ClusterOptions } from 'ioredis';
|
|
2
|
+
|
|
3
|
+
export interface IRedisClient {
|
|
4
|
+
xgroup(...args: any[]): Promise<any>;
|
|
5
|
+
xreadgroup(...args: any[]): Promise<any>;
|
|
6
|
+
xpending(...args: any[]): Promise<any>;
|
|
7
|
+
xclaim(...args: any[]): Promise<any>;
|
|
8
|
+
xadd(...args: any[]): Promise<any>;
|
|
9
|
+
xack(stream: string, group: string, ...ids: string[]): Promise<number>;
|
|
10
|
+
publish(channel: string, message: string): Promise<number>;
|
|
11
|
+
subscribe(channel: string): Promise<any>;
|
|
12
|
+
unsubscribe(channel: string): Promise<any>;
|
|
13
|
+
on(event: string, listener: (...args: any[]) => void): this;
|
|
14
|
+
off(event: string, listener: (...args: any[]) => void): this;
|
|
15
|
+
disconnect(): void;
|
|
16
|
+
pipeline(): IRedisClient;
|
|
17
|
+
multi(): IRedisClient;
|
|
18
|
+
exec(): Promise<any>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type RedisConfig = { host: string; port: number } | { host: string; port: number }[];
|
|
22
|
+
|
|
23
|
+
export const parseClusterString = (clusterStr: string): { host: string; port: number }[] =>
|
|
24
|
+
clusterStr
|
|
25
|
+
.split(',')
|
|
26
|
+
.map(x => x.split(':'))
|
|
27
|
+
.map(([host, port]) => ({ host, port: parseInt(port) }));
|
|
28
|
+
|
|
29
|
+
// Read env vars inside the function so tests can manipulate process.env without module re-loading
|
|
30
|
+
export const getDefaultRedisConfigs = (): RedisConfig => {
|
|
31
|
+
const redisCluster = process.env.REDIS_CLUSTER;
|
|
32
|
+
const redisHost = process.env.REDIS_HOST;
|
|
33
|
+
const redisPort = parseInt(process.env.REDIS_PORT || '0');
|
|
34
|
+
|
|
35
|
+
if (redisCluster) {
|
|
36
|
+
return parseClusterString(redisCluster);
|
|
37
|
+
}
|
|
38
|
+
if (!redisHost || redisHost === '') {
|
|
39
|
+
throw new Error('No redis connection provided (REDIS_HOST) ...');
|
|
40
|
+
}
|
|
41
|
+
if (!redisPort) {
|
|
42
|
+
throw new Error('No redis connection provided (REDIS_PORT) ...');
|
|
43
|
+
}
|
|
44
|
+
return { host: redisHost, port: redisPort };
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const getNewRedisClient = (
|
|
48
|
+
config: RedisConfig = getDefaultRedisConfigs(),
|
|
49
|
+
clusterOptions: ClusterOptions = {},
|
|
50
|
+
): IRedisClient => {
|
|
51
|
+
if (config instanceof Array) {
|
|
52
|
+
return new Redis.Cluster(config, clusterOptions) as unknown as IRedisClient;
|
|
53
|
+
}
|
|
54
|
+
return new Redis(config) as unknown as IRedisClient;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// Legacy export kept for backwards compatibility
|
|
58
|
+
export const getExistingRedisClient = (() => {
|
|
59
|
+
let _client: IRedisClient | undefined;
|
|
60
|
+
return (config: RedisConfig = getDefaultRedisConfigs(), clusterOptions: ClusterOptions = {}): IRedisClient => {
|
|
61
|
+
if (!_client) _client = getNewRedisClient(config, clusterOptions);
|
|
62
|
+
return _client;
|
|
63
|
+
};
|
|
64
|
+
})();
|