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,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.RedisStreams = void 0;
|
|
7
|
+
const log4js_api_1 = __importDefault(require("@log4js-node/log4js-api"));
|
|
8
|
+
const redis_client_1 = require("./redis-client");
|
|
9
|
+
const stream_consumer_1 = require("./stream-consumer");
|
|
10
|
+
const events_1 = require("./events");
|
|
11
|
+
class RedisStreams {
|
|
12
|
+
peerName;
|
|
13
|
+
groups = new Map();
|
|
14
|
+
config;
|
|
15
|
+
constructor(peerName, config) {
|
|
16
|
+
this.peerName = peerName;
|
|
17
|
+
this.config = RedisStreams.buildConfig(peerName, config);
|
|
18
|
+
}
|
|
19
|
+
_producerRedis;
|
|
20
|
+
getProducerRedis() {
|
|
21
|
+
if (!this._producerRedis) {
|
|
22
|
+
this._producerRedis = (0, redis_client_1.getNewRedisClient)(this.config.redis, this.config.clusterOptions);
|
|
23
|
+
}
|
|
24
|
+
return this._producerRedis;
|
|
25
|
+
}
|
|
26
|
+
getConsumerRedis() {
|
|
27
|
+
return (0, redis_client_1.getNewRedisClient)(this.config.redis, this.config.clusterOptions);
|
|
28
|
+
}
|
|
29
|
+
static buildConfig(peerName, config) {
|
|
30
|
+
let clusterNodes;
|
|
31
|
+
if (config?.redis && 'cluster' in config.redis) {
|
|
32
|
+
clusterNodes = (0, redis_client_1.parseClusterString)(config.redis.cluster);
|
|
33
|
+
}
|
|
34
|
+
const redis = clusterNodes
|
|
35
|
+
? clusterNodes
|
|
36
|
+
: ((config?.redis && !('cluster' in config.redis)) ? config.redis : (0, redis_client_1.getDefaultRedisConfigs)());
|
|
37
|
+
return {
|
|
38
|
+
redis: redis,
|
|
39
|
+
logger: config?.logger ?? log4js_api_1.default.getLogger(peerName),
|
|
40
|
+
...(config?.deadLetters ? { deadLetters: config.deadLetters } : {}),
|
|
41
|
+
...(config?.clusterOptions ? { clusterOptions: config.clusterOptions } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
buildConsumerConfigs(streamName, groupName, config) {
|
|
45
|
+
const base = {
|
|
46
|
+
claimIdleTime: 15000,
|
|
47
|
+
groupName,
|
|
48
|
+
batchSize: 5,
|
|
49
|
+
mode: 'parallel',
|
|
50
|
+
readBlockTime: 5000,
|
|
51
|
+
peerName: this.peerName,
|
|
52
|
+
maxLen: 100000,
|
|
53
|
+
streamName,
|
|
54
|
+
deadLetters: this.config.deadLetters
|
|
55
|
+
? {
|
|
56
|
+
maxRetries: this.config.deadLetters.maxRetries,
|
|
57
|
+
handler: async (...events) => {
|
|
58
|
+
/* istanbul ignore next */
|
|
59
|
+
if (!this.config.deadLetters)
|
|
60
|
+
return;
|
|
61
|
+
const pipeline = this.getProducerRedis().pipeline();
|
|
62
|
+
this.doProduce(pipeline, this.config.deadLetters.stream, this.config.deadLetters.maxSize, ...events);
|
|
63
|
+
await pipeline.exec();
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
: undefined,
|
|
67
|
+
};
|
|
68
|
+
return Object.assign(base, config ?? {});
|
|
69
|
+
}
|
|
70
|
+
registerConsumer(streamName, groupName, handlers, config) {
|
|
71
|
+
const handler = async (id, event, eventObj) => {
|
|
72
|
+
let handle = handlers.get(event);
|
|
73
|
+
if (!handle)
|
|
74
|
+
handle = handlers.get('*');
|
|
75
|
+
if (!handle)
|
|
76
|
+
return;
|
|
77
|
+
return handle(id, eventObj);
|
|
78
|
+
};
|
|
79
|
+
return new stream_consumer_1.StreamConsumer(this.getConsumerRedis(), handler, config);
|
|
80
|
+
}
|
|
81
|
+
getStreamsMap(groupName) {
|
|
82
|
+
let streams = this.groups.get(groupName);
|
|
83
|
+
if (!streams) {
|
|
84
|
+
streams = new Map();
|
|
85
|
+
this.groups.set(groupName, streams);
|
|
86
|
+
}
|
|
87
|
+
return streams;
|
|
88
|
+
}
|
|
89
|
+
group(groupName) {
|
|
90
|
+
const streams = this.getStreamsMap(groupName);
|
|
91
|
+
return {
|
|
92
|
+
stream: (streamName, config) => {
|
|
93
|
+
const existing = streams.get(streamName);
|
|
94
|
+
if (existing)
|
|
95
|
+
return existing;
|
|
96
|
+
const newStream = this.buildStream(streamName, groupName, config);
|
|
97
|
+
streams.set(streamName, newStream);
|
|
98
|
+
return newStream;
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
buildStream(streamName, groupName, config) {
|
|
103
|
+
const handlers = new Map();
|
|
104
|
+
const readyConfigs = this.buildConsumerConfigs(streamName, groupName, config);
|
|
105
|
+
const consumer = this.registerConsumer(streamName, groupName, handlers, readyConfigs);
|
|
106
|
+
const consume = async () => {
|
|
107
|
+
await consumer.init();
|
|
108
|
+
consumer.start();
|
|
109
|
+
return {
|
|
110
|
+
stop: () => consumer.dispose(),
|
|
111
|
+
continue: () => { consumer.start(); },
|
|
112
|
+
};
|
|
113
|
+
};
|
|
114
|
+
const handle = ((event, handler) => {
|
|
115
|
+
handlers.set(event, handler);
|
|
116
|
+
return { handle, consume };
|
|
117
|
+
});
|
|
118
|
+
// Per-stream pipeline — isolated, not shared across streams
|
|
119
|
+
let _currentPipeline;
|
|
120
|
+
const getRedisPipeline = () => {
|
|
121
|
+
if (!_currentPipeline)
|
|
122
|
+
_currentPipeline = this.getProducerRedis().multi();
|
|
123
|
+
return _currentPipeline;
|
|
124
|
+
};
|
|
125
|
+
const produceMany = (...events) => {
|
|
126
|
+
const pipeline = this.doProduce(getRedisPipeline(), streamName, readyConfigs.maxLen, ...events);
|
|
127
|
+
return {
|
|
128
|
+
produceMany,
|
|
129
|
+
flush: async () => {
|
|
130
|
+
_currentPipeline = undefined;
|
|
131
|
+
await pipeline.exec();
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
const produce = (...events) => {
|
|
136
|
+
if (events.length === 1 && events[0].wait) {
|
|
137
|
+
const pipeline = this.doProduce(this.getProducerRedis().pipeline(), streamName, readyConfigs.maxLen, ...events);
|
|
138
|
+
return {
|
|
139
|
+
wait: async (timeout) => {
|
|
140
|
+
const redis = this.getConsumerRedis();
|
|
141
|
+
const waitEvent = events[0];
|
|
142
|
+
const channel = `${waitEvent.name}_${waitEvent.time}_${waitEvent.wait.source}`;
|
|
143
|
+
let timerId;
|
|
144
|
+
let msgHandler;
|
|
145
|
+
const cleanup = () => {
|
|
146
|
+
if (msgHandler)
|
|
147
|
+
redis.off('message', msgHandler);
|
|
148
|
+
redis.unsubscribe(channel);
|
|
149
|
+
redis.disconnect();
|
|
150
|
+
/* istanbul ignore next */
|
|
151
|
+
if (timerId)
|
|
152
|
+
clearTimeout(timerId);
|
|
153
|
+
};
|
|
154
|
+
try {
|
|
155
|
+
const reply = await new Promise(async (resolve, reject) => {
|
|
156
|
+
timerId = setTimeout(() => reject(new Error('Timeout')), timeout);
|
|
157
|
+
await redis.subscribe(channel);
|
|
158
|
+
msgHandler = (_channel, data) => resolve(JSON.parse(data)['reply']);
|
|
159
|
+
redis.on('message', msgHandler);
|
|
160
|
+
await pipeline.exec();
|
|
161
|
+
});
|
|
162
|
+
return reply;
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
cleanup();
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const pipeline = this.doProduce(this.getProducerRedis().pipeline(), streamName, readyConfigs.maxLen, ...events);
|
|
171
|
+
return pipeline.exec().then(() => { });
|
|
172
|
+
};
|
|
173
|
+
const streamObj = {
|
|
174
|
+
consume,
|
|
175
|
+
handle,
|
|
176
|
+
produceMany,
|
|
177
|
+
produce,
|
|
178
|
+
with: (events) => (0, events_1.augmentEvents)(events, streamObj),
|
|
179
|
+
};
|
|
180
|
+
return streamObj;
|
|
181
|
+
}
|
|
182
|
+
doProduce(pipeline, stream, maxLen, ...events) {
|
|
183
|
+
if (events.length === 0)
|
|
184
|
+
return pipeline;
|
|
185
|
+
for (const one of events) {
|
|
186
|
+
const eventString = JSON.stringify(one);
|
|
187
|
+
if (typeof maxLen === 'number') {
|
|
188
|
+
pipeline = pipeline.xadd(stream, 'MAXLEN', '~', String(maxLen), '*', one.name, eventString);
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
pipeline = pipeline.xadd(stream, '*', one.name, eventString);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return pipeline;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
exports.RedisStreams = RedisStreams;
|
|
198
|
+
//# sourceMappingURL=redis-streams.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-streams.js","sourceRoot":"","sources":["../src/redis-streams.ts"],"names":[],"mappings":";;;;;;AAAA,yEAAoD;AACpD,iDAA0H;AAC1H,uDAAmE;AACnE,qCAAyC;AAiBzC,MAAa,YAAY;IAKQ;IAHZ,MAAM,GAAkD,IAAI,GAAG,EAAE,CAAC;IAClE,MAAM,CAAqB;IAE9C,YAA+B,QAAgB,EAAE,MAAyC;QAA3D,aAAQ,GAAR,QAAQ,CAAQ;QAC7C,IAAI,CAAC,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC3D,CAAC;IAEO,cAAc,CAA2B;IACvC,gBAAgB;QACxB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE;YACxB,IAAI,CAAC,cAAc,GAAG,IAAA,gCAAiB,EAAC,IAAI,CAAC,MAAM,CAAC,KAAoB,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;SACvG;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;IAC7B,CAAC;IAES,gBAAgB;QACxB,OAAO,IAAA,gCAAiB,EAAC,IAAI,CAAC,MAAM,CAAC,KAAoB,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IACzF,CAAC;IAEO,MAAM,CAAC,WAAW,CACxB,QAAgB,EAChB,MAAyC;QAEzC,IAAI,YAA0D,CAA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BAAgB,EAAE,CAAC,QAAQ,EAAE,EAClC,UAAU,EACV,YAAY,CAAC,MAAM,EACnB,GAAG,MAAM,CACV,CAAC;YACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QACxC,CAAC,CAAC;QAEF,MAAM,SAAS,GAAwB;YACrC,OAAO;YACP,MAAM;YACN,WAAW;YACX,OAAO;YACP,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,IAAA,sBAAa,EAAC,MAAM,EAAE,SAAS,CAAC;SACnD,CAAC;QAEF,OAAO,SAAS,CAAC;IACnB,CAAC;IAEO,SAAS,CACf,QAAsB,EACtB,MAAc,EACd,MAAe,EACf,GAAG,MAAmB;QAEtB,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,QAAQ,CAAC;QACzC,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;YACxB,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;YACxC,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;gBAC9B,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,EAAE,WAAW,CAAQ,CAAC;aACpG;iBAAM;gBACL,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,EAAE,WAAW,CAAQ,CAAC;aACrE;SACF;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF;AApOD,oCAoOC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import loggerFactory from '@log4js-node/log4js-api';
|
|
2
|
+
import { IRedisClient } from './redis-client';
|
|
3
|
+
import { ConsumerBuffer } from './consumer-buffer';
|
|
4
|
+
import { ConsumerConfigs, IEvent, IWaitEvent } from './types';
|
|
5
|
+
export declare type EventProcessor = <T>(id: string, event: string, eventObj: IEvent<T> | IWaitEvent<T>) => Promise<any>;
|
|
6
|
+
export declare class StreamConsumer {
|
|
7
|
+
protected readonly redis: IRedisClient;
|
|
8
|
+
protected readonly processEvent: EventProcessor;
|
|
9
|
+
protected readonly config: ConsumerConfigs;
|
|
10
|
+
protected logger: loggerFactory.Logger;
|
|
11
|
+
protected disposing: boolean;
|
|
12
|
+
protected lastReadId: string;
|
|
13
|
+
protected checkBacklog: boolean;
|
|
14
|
+
protected readonly buffer: ConsumerBuffer;
|
|
15
|
+
protected readingLoop: Promise<void>;
|
|
16
|
+
constructor(redis: IRedisClient, processEvent: EventProcessor, config: ConsumerConfigs);
|
|
17
|
+
get size(): number;
|
|
18
|
+
init(): Promise<void>;
|
|
19
|
+
start(): Promise<void>;
|
|
20
|
+
protected tryReading(): Promise<void>;
|
|
21
|
+
lastTimePendingCheck: number;
|
|
22
|
+
protected doClaim(): Promise<boolean>;
|
|
23
|
+
protected doRead(): Promise<boolean>;
|
|
24
|
+
protected processMessage<T>(id: string, message: string[]): Promise<any>;
|
|
25
|
+
dispose(): Promise<void>;
|
|
26
|
+
protected removeConsumer(): Promise<void>;
|
|
27
|
+
publishDeadLetters(...messages: [string, string[]][]): Promise<void>;
|
|
28
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.StreamConsumer = void 0;
|
|
7
|
+
const log4js_api_1 = __importDefault(require("@log4js-node/log4js-api"));
|
|
8
|
+
const consumer_buffer_1 = require("./consumer-buffer");
|
|
9
|
+
class StreamConsumer {
|
|
10
|
+
redis;
|
|
11
|
+
processEvent;
|
|
12
|
+
config;
|
|
13
|
+
logger;
|
|
14
|
+
disposing = false;
|
|
15
|
+
lastReadId = '0-0';
|
|
16
|
+
checkBacklog = true;
|
|
17
|
+
buffer;
|
|
18
|
+
readingLoop = Promise.resolve();
|
|
19
|
+
constructor(redis, processEvent, config) {
|
|
20
|
+
this.redis = redis;
|
|
21
|
+
this.processEvent = processEvent;
|
|
22
|
+
this.config = config;
|
|
23
|
+
this.logger = config.logger
|
|
24
|
+
?? log4js_api_1.default.getLogger(config.streamName + ':Consumer');
|
|
25
|
+
if (!this.config.batchSize)
|
|
26
|
+
this.config.batchSize = 5;
|
|
27
|
+
this.buffer = new consumer_buffer_1.ConsumerBuffer({
|
|
28
|
+
ack: async (...ids) => {
|
|
29
|
+
await this.redis.xack(this.config.streamName, this.config.groupName, ...ids);
|
|
30
|
+
},
|
|
31
|
+
error: async (id, message, error) => {
|
|
32
|
+
this.logger.error(`Error during processMessage on stream '${this.config.streamName}' with id '${id}'`, error);
|
|
33
|
+
},
|
|
34
|
+
process: (id, message) => this.processMessage(id, message),
|
|
35
|
+
mode: this.config.mode ?? 'parallel',
|
|
36
|
+
size: this.config.batchSize,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
get size() {
|
|
40
|
+
return this.buffer.size;
|
|
41
|
+
}
|
|
42
|
+
async init() {
|
|
43
|
+
await this.redis.xgroup('CREATE', this.config.streamName, this.config.groupName, '$', 'MKSTREAM').catch((err) => {
|
|
44
|
+
if (!err.message.includes('BUSYGROUP')) {
|
|
45
|
+
this.logger.error(err);
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
this.logger.trace('Ready...');
|
|
50
|
+
}
|
|
51
|
+
async start() {
|
|
52
|
+
this.logger.trace('Started...');
|
|
53
|
+
this.readingLoop = this.tryReading();
|
|
54
|
+
await this.readingLoop;
|
|
55
|
+
}
|
|
56
|
+
async tryReading() {
|
|
57
|
+
while (!this.disposing) {
|
|
58
|
+
try {
|
|
59
|
+
const claimedAnything = await this.doClaim();
|
|
60
|
+
if (claimedAnything && !this.disposing)
|
|
61
|
+
continue;
|
|
62
|
+
const dataAvailable = await this.doRead();
|
|
63
|
+
if (dataAvailable && !this.disposing)
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
this.logger.error('Error while tryReading', err);
|
|
68
|
+
if (err && typeof err.message === 'string' && err.message.includes('NOGROUP')) {
|
|
69
|
+
this.checkBacklog = true;
|
|
70
|
+
this.lastReadId = '0-0';
|
|
71
|
+
await this.init();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
lastTimePendingCheck = 0;
|
|
77
|
+
async doClaim() {
|
|
78
|
+
if (this.lastTimePendingCheck + this.config.claimIdleTime >= Date.now())
|
|
79
|
+
return false;
|
|
80
|
+
const allPending = await this.redis.xpending(this.config.streamName, this.config.groupName, '-', '+', this.config.batchSize);
|
|
81
|
+
this.lastTimePendingCheck = Date.now();
|
|
82
|
+
const result = allPending.filter(([, , idleTime]) => idleTime >= this.config.claimIdleTime);
|
|
83
|
+
if (!result.length)
|
|
84
|
+
return false;
|
|
85
|
+
const toBeClaimedMessages = result.map(([id]) => id);
|
|
86
|
+
const streamsEntries = await this.redis.xclaim(this.config.streamName, this.config.groupName, this.config.peerName, this.config.claimIdleTime, ...toBeClaimedMessages);
|
|
87
|
+
const deadMessages = result.reduce((acc, [id, , , counter]) => {
|
|
88
|
+
const threshold = this.config.deadLetters?.maxRetries ?? Number.MAX_VALUE;
|
|
89
|
+
return counter >= threshold ? acc.add(id) : acc;
|
|
90
|
+
}, new Set());
|
|
91
|
+
if (this.config.deadLetters && deadMessages.size) {
|
|
92
|
+
const deadIds = Array.from(deadMessages);
|
|
93
|
+
this.logger.trace('Dead Letters', JSON.stringify(deadIds));
|
|
94
|
+
const deadEntries = streamsEntries.filter(entry => Array.isArray(entry) && entry.length && deadMessages.has(entry[0]));
|
|
95
|
+
await this.publishDeadLetters(...deadEntries);
|
|
96
|
+
await this.redis.xack(this.config.streamName, this.config.groupName, ...deadIds);
|
|
97
|
+
}
|
|
98
|
+
const goodEntries = streamsEntries.filter(entry => Array.isArray(entry) && entry.length && !deadMessages.has(entry[0]));
|
|
99
|
+
if (goodEntries.length) {
|
|
100
|
+
this.logger.info('Claimed', goodEntries.length);
|
|
101
|
+
await this.buffer.add(...goodEntries);
|
|
102
|
+
}
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
async doRead() {
|
|
106
|
+
const streamsEntries = await this.redis.xreadgroup('GROUP', this.config.groupName, this.config.peerName, 'COUNT', this.config.batchSize, 'BLOCK', this.config.readBlockTime, 'STREAMS', this.config.streamName, this.checkBacklog ? this.lastReadId : '>');
|
|
107
|
+
if (!streamsEntries || streamsEntries.length === 0) {
|
|
108
|
+
this.checkBacklog = false;
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
for (const [, streamEntries] of streamsEntries) {
|
|
112
|
+
if (streamEntries.length === 0) {
|
|
113
|
+
this.checkBacklog = false;
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
this.lastReadId = streamEntries[streamEntries.length - 1][0];
|
|
117
|
+
await this.buffer.add(...streamEntries);
|
|
118
|
+
}
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
async processMessage(id, message) {
|
|
122
|
+
let event;
|
|
123
|
+
let eventObj;
|
|
124
|
+
try {
|
|
125
|
+
let value;
|
|
126
|
+
[event, value] = message;
|
|
127
|
+
eventObj = JSON.parse(value);
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
return this.logger.error('Error while parsing message. Corrupted or wrong-formatted stream message.', id, message, err);
|
|
131
|
+
}
|
|
132
|
+
const result = await this.processEvent(id, event, eventObj);
|
|
133
|
+
if (eventObj.wait) {
|
|
134
|
+
const channel = `${eventObj.name}_${eventObj.time}_${eventObj.wait.source}`;
|
|
135
|
+
await this.redis.publish(channel, JSON.stringify({
|
|
136
|
+
reply: result,
|
|
137
|
+
wait: eventObj.wait,
|
|
138
|
+
}));
|
|
139
|
+
}
|
|
140
|
+
return result;
|
|
141
|
+
}
|
|
142
|
+
async dispose() {
|
|
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
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async publishDeadLetters(...messages) {
|
|
159
|
+
if (!this.config.deadLetters)
|
|
160
|
+
return;
|
|
161
|
+
const finalEvents = messages.map(([id, message]) => ({
|
|
162
|
+
name: 'deadMessage',
|
|
163
|
+
v: '1.0.0',
|
|
164
|
+
time: Date.now(),
|
|
165
|
+
data: {
|
|
166
|
+
id,
|
|
167
|
+
message,
|
|
168
|
+
stream: this.config.streamName,
|
|
169
|
+
group: this.config.groupName,
|
|
170
|
+
},
|
|
171
|
+
by: { userId: this.config.peerName },
|
|
172
|
+
}));
|
|
173
|
+
await this.config.deadLetters.handler(...finalEvents);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
exports.StreamConsumer = StreamConsumer;
|
|
177
|
+
//# sourceMappingURL=stream-consumer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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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M,CAAC,SAAS,EACrB,IAAI,CAAC,MAAM,CAAC,QAAQ,CACrB,CAAC;YACF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,6BAA6B,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;SACxE;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,4BAA4B,IAAI,CAAC,MAAM,CAAC,QAAQ,iBAAiB,IAAI,CAAC,MAAM,CAAC,SAAS,GAAG,EACzF,GAAG,CACJ,CAAC;SACH;IACH,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,GAAG,QAA8B;QACxD,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW;YAAE,OAAO;QAErC,MAAM,WAAW,GAAsB,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;YACtE,IAAI,EAAE,aAAa;YACnB,CAAC,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
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import loggerFactory from '@log4js-node/log4js-api';
|
|
2
|
+
import type { ClusterOptions } from 'ioredis';
|
|
3
|
+
export interface IEvent<T> {
|
|
4
|
+
time: number;
|
|
5
|
+
name: string;
|
|
6
|
+
v: string;
|
|
7
|
+
data: T;
|
|
8
|
+
}
|
|
9
|
+
export interface IWaitEvent<T> extends IEvent<T> {
|
|
10
|
+
wait: {
|
|
11
|
+
source: string;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export declare type DeadLetterEvent = IEvent<{
|
|
15
|
+
id: string;
|
|
16
|
+
message: string[];
|
|
17
|
+
stream: string;
|
|
18
|
+
group: string;
|
|
19
|
+
}>;
|
|
20
|
+
export declare type RedisStreamsConfig = {
|
|
21
|
+
redis: {
|
|
22
|
+
host: string;
|
|
23
|
+
port: number;
|
|
24
|
+
} | {
|
|
25
|
+
host: string;
|
|
26
|
+
port: number;
|
|
27
|
+
}[];
|
|
28
|
+
clusterOptions?: ClusterOptions;
|
|
29
|
+
logger: loggerFactory.Logger;
|
|
30
|
+
deadLetters?: {
|
|
31
|
+
stream: string;
|
|
32
|
+
maxRetries: number;
|
|
33
|
+
maxSize: number;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
export declare type RedisStreamsInputConfig = Omit<RedisStreamsConfig, 'redis'> & {
|
|
37
|
+
redis: {
|
|
38
|
+
host: string;
|
|
39
|
+
port: number;
|
|
40
|
+
} | {
|
|
41
|
+
cluster: string;
|
|
42
|
+
};
|
|
43
|
+
clusterOptions?: ClusterOptions;
|
|
44
|
+
};
|
|
45
|
+
export declare type StreamConfigs = {
|
|
46
|
+
readBlockTime: number;
|
|
47
|
+
claimIdleTime: number;
|
|
48
|
+
batchSize: number;
|
|
49
|
+
mode: 'parallel' | 'serial';
|
|
50
|
+
maxLen: number;
|
|
51
|
+
};
|
|
52
|
+
export declare type ConsumerConfigs = StreamConfigs & {
|
|
53
|
+
peerName: string;
|
|
54
|
+
streamName: string;
|
|
55
|
+
groupName: string;
|
|
56
|
+
logger?: loggerFactory.Logger;
|
|
57
|
+
deadLetters?: {
|
|
58
|
+
handler: (...event: DeadLetterEvent[]) => Promise<void>;
|
|
59
|
+
maxRetries: number;
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
export declare type NamedEventHandler<E = IEvent<any>> = (id: string, event: E) => Promise<any>;
|
|
63
|
+
export declare type ConsumeFunctions = {
|
|
64
|
+
consume: () => Promise<{
|
|
65
|
+
stop: () => Promise<void>;
|
|
66
|
+
continue: () => void;
|
|
67
|
+
}>;
|
|
68
|
+
};
|
|
69
|
+
declare type NamedEvent<T, N extends string> = IEvent<T> & {
|
|
70
|
+
name: N;
|
|
71
|
+
};
|
|
72
|
+
declare type NamedWaitEvent<T, N extends string, ReplyType = any> = IWaitEvent<T> & {
|
|
73
|
+
name: N;
|
|
74
|
+
};
|
|
75
|
+
export declare type ProduceFunc = (...events: IEvent<any>[]) => {
|
|
76
|
+
produceMany: ProduceFunc;
|
|
77
|
+
flush: () => Promise<void>;
|
|
78
|
+
};
|
|
79
|
+
export declare type StreamGroupConsumer = ConsumeFunctions & {
|
|
80
|
+
handle: HandleFunction<any>;
|
|
81
|
+
produce: (...events: (IEvent<any> | IWaitEvent<any>)[]) => Promise<void> | {
|
|
82
|
+
wait: (timeout: number) => Promise<any>;
|
|
83
|
+
};
|
|
84
|
+
produceMany: ProduceFunc;
|
|
85
|
+
with: <O extends AllowedFactories<O>>(events: O) => WithTypedHandlers<O>;
|
|
86
|
+
};
|
|
87
|
+
export declare type ConsumerGroup = {
|
|
88
|
+
stream: (streamName: string, config?: Partial<StreamConfigs>) => StreamGroupConsumer;
|
|
89
|
+
};
|
|
90
|
+
declare type _ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
|
|
91
|
+
declare type ReplyTypeOf<T> = T extends NamedWaitEvent<any, string, infer Reply> ? Reply : any;
|
|
92
|
+
declare type DataOfHandler<T> = T extends (...args: any[]) => IEvent<infer R> ? R : any;
|
|
93
|
+
declare type ArgsOf<T> = T extends (...args: infer Args) => any ? Args : never;
|
|
94
|
+
export declare type AllowedFactories<T> = {
|
|
95
|
+
[name in keyof T]: (...args: any[]) => IEvent<DataOfHandler<T[name]>> | IWaitEvent<DataOfHandler<T[name]>>;
|
|
96
|
+
};
|
|
97
|
+
export declare type HandleFunction<T> = <N extends keyof T | '*'>(event: N, handler: NamedEventHandler<N extends keyof T ? _ReturnType<T[N]> : IEvent<any>>) => {
|
|
98
|
+
handle: HandleFunction<T>;
|
|
99
|
+
} & ConsumeFunctions;
|
|
100
|
+
declare type WithTypedHandlers<T> = PromisifiedFunctionsMap<T> & {
|
|
101
|
+
handle: HandleFunction<T>;
|
|
102
|
+
} & Omit<StreamGroupConsumer, 'handle'>;
|
|
103
|
+
declare type PromisifiedFunctionsMap<T> = {
|
|
104
|
+
[func in keyof T]: (...args: ArgsOf<T[func]>) => _ReturnType<T[func]> extends {
|
|
105
|
+
wait: {
|
|
106
|
+
source: string;
|
|
107
|
+
};
|
|
108
|
+
} ? {
|
|
109
|
+
wait: (timeout: number) => Promise<ReplyTypeOf<_ReturnType<T[func]>>>;
|
|
110
|
+
} : Promise<void>;
|
|
111
|
+
};
|
|
112
|
+
export type { NamedEvent, NamedWaitEvent, WithTypedHandlers, PromisifiedFunctionsMap };
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|