@jetit/publisher 1.0.3 → 1.0.5
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/package.json +3 -2
- package/src/README.md +43 -0
- package/src/index.d.ts +1 -0
- package/src/index.js +4 -0
- package/src/lib/publisher.d.ts +3 -0
- package/src/lib/publisher.js +9 -0
- package/src/lib/redis/groups.d.ts +2 -0
- package/src/lib/redis/groups.js +11 -0
- package/src/lib/redis/registry.d.ts +20 -0
- package/src/lib/redis/registry.js +57 -0
- package/src/lib/redis/scheduler.d.ts +15 -0
- package/src/lib/redis/scheduler.js +80 -0
- package/src/lib/redis/streams.d.ts +152 -0
- package/src/lib/redis/streams.js +392 -0
- package/src/lib/redis/types.d.ts +15 -0
- package/src/lib/redis/types.js +2 -0
- package/index.d.ts +0 -222
- package/index.js +0 -553
package/index.js
DELETED
|
@@ -1,553 +0,0 @@
|
|
|
1
|
-
define("src/lib/redis/types", ["require", "exports"], function (require, exports) {
|
|
2
|
-
"use strict";
|
|
3
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
});
|
|
5
|
-
define("src/lib/redis/registry", ["require", "exports", "ioredis"], function (require, exports, ioredis_1) {
|
|
6
|
-
"use strict";
|
|
7
|
-
var _a, _b;
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.setRedisConnectionSettings = exports.RedisRegistry = void 0;
|
|
10
|
-
class RedisRegistry {
|
|
11
|
-
static attemptConnection(connectionKey, storeRef = 0) {
|
|
12
|
-
let ref;
|
|
13
|
-
if (RedisRegistry.options.cluster) {
|
|
14
|
-
ref = new ioredis_1.Cluster(RedisRegistry.options.cluster.nodes, Object.assign(Object.assign({}, RedisRegistry.options.cluster.options), { redisOptions: {
|
|
15
|
-
db: storeRef,
|
|
16
|
-
} }));
|
|
17
|
-
}
|
|
18
|
-
ref = new ioredis_1.default(Object.assign(Object.assign({}, RedisRegistry.options.redis), { db: storeRef }));
|
|
19
|
-
RedisRegistry.registry.set(connectionKey, ref);
|
|
20
|
-
return ref;
|
|
21
|
-
}
|
|
22
|
-
static getConnection(connectionType = 'primary', storeRef = 0) {
|
|
23
|
-
const connectionKey = `${connectionType}${storeRef}`;
|
|
24
|
-
let ref = this.registry.get(connectionKey);
|
|
25
|
-
if (!ref) {
|
|
26
|
-
if (RedisRegistry.options.cluster) {
|
|
27
|
-
ref = new ioredis_1.Cluster(RedisRegistry.options.cluster.nodes, Object.assign(Object.assign({}, RedisRegistry.options.cluster.options), { redisOptions: {
|
|
28
|
-
db: storeRef,
|
|
29
|
-
} }));
|
|
30
|
-
}
|
|
31
|
-
ref = new ioredis_1.default(Object.assign(Object.assign({}, RedisRegistry.options.redis), { db: storeRef }));
|
|
32
|
-
}
|
|
33
|
-
return ref;
|
|
34
|
-
}
|
|
35
|
-
static setOptions(options) {
|
|
36
|
-
RedisRegistry.options = options;
|
|
37
|
-
}
|
|
38
|
-
static _getOptions() {
|
|
39
|
-
return RedisRegistry.options;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
RedisRegistry.registry = new Map();
|
|
43
|
-
RedisRegistry.options = {
|
|
44
|
-
redis: {
|
|
45
|
-
port: parseInt((_a = process.env['REDIS_PORT']) !== null && _a !== void 0 ? _a : '6379'),
|
|
46
|
-
host: (_b = process.env['REDIS_HOST']) !== null && _b !== void 0 ? _b : 'localhost',
|
|
47
|
-
},
|
|
48
|
-
};
|
|
49
|
-
exports.RedisRegistry = RedisRegistry;
|
|
50
|
-
/**
|
|
51
|
-
* This function is used to set Redis Connection options per instance. If no
|
|
52
|
-
* options are provided, then the service connects as to a single instance
|
|
53
|
-
* with the environment values from REDIS_PORT and REDIS_HOST. if those
|
|
54
|
-
* environment values are not provided, it attempts to connect to localhost:6379
|
|
55
|
-
*
|
|
56
|
-
* @param options
|
|
57
|
-
*/
|
|
58
|
-
function setRedisConnectionSettings(options) {
|
|
59
|
-
RedisRegistry.setOptions(options);
|
|
60
|
-
}
|
|
61
|
-
exports.setRedisConnectionSettings = setRedisConnectionSettings;
|
|
62
|
-
});
|
|
63
|
-
define("src/lib/redis/groups", ["require", "exports", "tslib"], function (require, exports, tslib_1) {
|
|
64
|
-
"use strict";
|
|
65
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
66
|
-
exports.getAllConsumerGroups = void 0;
|
|
67
|
-
function getAllConsumerGroups(eventName, redisConnection) {
|
|
68
|
-
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
69
|
-
const consumerGroups = yield redisConnection.smembers(`consumerGroups:${eventName}`);
|
|
70
|
-
return consumerGroups;
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
exports.getAllConsumerGroups = getAllConsumerGroups;
|
|
74
|
-
});
|
|
75
|
-
define("src/lib/redis/streams", ["require", "exports", "tslib", "src/lib/redis/registry", "rxjs", "@jetit/id", "src/lib/redis/groups"], function (require, exports, tslib_2, registry_1, rxjs_1, id_1, groups_1) {
|
|
76
|
-
"use strict";
|
|
77
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
78
|
-
exports.Streams = void 0;
|
|
79
|
-
class Streams {
|
|
80
|
-
get redisPublisher() {
|
|
81
|
-
if (!this._redisPublisher)
|
|
82
|
-
this._redisPublisher = registry_1.RedisRegistry.getConnection('publish');
|
|
83
|
-
return this._redisPublisher;
|
|
84
|
-
}
|
|
85
|
-
get redisSubscriber() {
|
|
86
|
-
if (!this._redisSubscriber)
|
|
87
|
-
this._redisSubscriber = registry_1.RedisRegistry.getConnection('subscriber');
|
|
88
|
-
return this._redisSubscriber;
|
|
89
|
-
}
|
|
90
|
-
get redisGroups() {
|
|
91
|
-
if (!this._redisGroups)
|
|
92
|
-
this._redisGroups = registry_1.RedisRegistry.getConnection('groups');
|
|
93
|
-
return this._redisGroups;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Creates a new Streams instance for a given service.
|
|
97
|
-
*
|
|
98
|
-
* The constructor initializes the Redis connections for publishers, subscribers, and consumer groups.
|
|
99
|
-
* It also sets up an interval timer for clearing expired messages from Redis and another interval timer
|
|
100
|
-
* for processing scheduled events at regular intervals.
|
|
101
|
-
*
|
|
102
|
-
* @param serviceName - A unique name for the service that will be using this Streams instance.
|
|
103
|
-
*
|
|
104
|
-
* @example
|
|
105
|
-
*
|
|
106
|
-
* // Create a new Streams instance for the "POS" service
|
|
107
|
-
* const streams = new Streams('POS');
|
|
108
|
-
*/
|
|
109
|
-
constructor(serviceName) {
|
|
110
|
-
var _a;
|
|
111
|
-
this.eventsListened = [];
|
|
112
|
-
this.instanceId = `${serviceName}:${(0, id_1.generateID)('HEX', 'FE')}`;
|
|
113
|
-
this.consumerGroupName = `cg-${serviceName}`;
|
|
114
|
-
const cleanUpInterval = (_a = parseInt(process.env['CLEANUP_INTERVAL'] || '1000 * 60 * 60', 10)) !== null && _a !== void 0 ? _a : 1000 * 60 * 60;
|
|
115
|
-
this.cleanUpTimer = (0, rxjs_1.interval)(cleanUpInterval).subscribe(() => {
|
|
116
|
-
this.clearDuplicationCheckKeys();
|
|
117
|
-
this.eventsListened.forEach((eventName) => this.cleanupAcknowledgedMessages(eventName, cleanUpInterval));
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
createConsumerGroup(eventName) {
|
|
121
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
122
|
-
try {
|
|
123
|
-
const streamName = `${eventName}:${this.consumerGroupName}`;
|
|
124
|
-
yield this.redisGroups.xgroup('CREATE', streamName, this.consumerGroupName, '0', 'MKSTREAM');
|
|
125
|
-
}
|
|
126
|
-
catch (error) {
|
|
127
|
-
if (error.message !== 'BUSYGROUP Consumer Group name already exists') {
|
|
128
|
-
throw error;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
isDuplicateMessage(streamName, messageId) {
|
|
134
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
135
|
-
const processedMessagesKey = `pm:${this.consumerGroupName}:${streamName}`;
|
|
136
|
-
const temp = yield Promise.race([
|
|
137
|
-
this.redisGroups.zscore(processedMessagesKey, messageId),
|
|
138
|
-
/** ioRedis doesnt seem to return the nil event. So waiting for 100ms before moving on */
|
|
139
|
-
new Promise((res) => setTimeout(() => res(null), 100)),
|
|
140
|
-
]);
|
|
141
|
-
return temp !== null;
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
clearDuplicationCheckKeys() {
|
|
145
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
146
|
-
const processedMessagesKeyPattern = `pm:${this.consumerGroupName}:*`;
|
|
147
|
-
let cursor = '0';
|
|
148
|
-
do {
|
|
149
|
-
const [nextCursor, keys] = yield this.redisGroups.scan(cursor, 'MATCH', processedMessagesKeyPattern);
|
|
150
|
-
cursor = nextCursor;
|
|
151
|
-
for (const key of keys) {
|
|
152
|
-
const oneHourAgo = Date.now() - 60 * 60 * 1000;
|
|
153
|
-
yield this.redisGroups.zremrangebyscore(key, '-inf', oneHourAgo);
|
|
154
|
-
}
|
|
155
|
-
} while (cursor !== '0');
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Publishes an event with the given data to the Redis event stream.
|
|
160
|
-
*
|
|
161
|
-
* The method generates a unique event ID for each event, and adds it to the event data to handle message
|
|
162
|
-
* deduplication.
|
|
163
|
-
*
|
|
164
|
-
* @param data - An EventData<T> object containing the data for the event.
|
|
165
|
-
*
|
|
166
|
-
* @returns A Promise that resolves when the event has been published to the Redis stream.
|
|
167
|
-
*
|
|
168
|
-
* @example
|
|
169
|
-
*
|
|
170
|
-
* // Publish an "order.created" event with the given order data
|
|
171
|
-
* const orderData = { id: '123', customerName: 'John Doe', amount: 100 };
|
|
172
|
-
* const eventData = { eventName: 'order.created', data: orderData };
|
|
173
|
-
* await streams.publish(eventData);
|
|
174
|
-
*/
|
|
175
|
-
publish(data) {
|
|
176
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
177
|
-
data.eventId = (0, id_1.generateID)('HEX', 'FF'); // Added a unique Id to handle Message deduplication
|
|
178
|
-
const transaction = this.redisPublisher.multi();
|
|
179
|
-
const consumerGroups = yield (0, groups_1.getAllConsumerGroups)(data.eventName, this.redisGroups);
|
|
180
|
-
if (consumerGroups.length > 0) {
|
|
181
|
-
console.log(`Publishing event ${data.eventName} to consumer groups: ${consumerGroups.join(', ')}`);
|
|
182
|
-
for (const consumerGroup of consumerGroups) {
|
|
183
|
-
// Publish the event to each consumer group's stream
|
|
184
|
-
const streamName = `${data.eventName}:${consumerGroup}`;
|
|
185
|
-
transaction.xadd(streamName, '*', 'data', JSON.stringify(data));
|
|
186
|
-
}
|
|
187
|
-
transaction.publish(data.eventName, '');
|
|
188
|
-
yield transaction.exec().catch((error) => {
|
|
189
|
-
console.error(`Error while publishing event for service ${this.consumerGroupName} with instance ${this.instanceId}: `, error);
|
|
190
|
-
throw new Error('Publisher Error');
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
/**
|
|
196
|
-
* Schedules an event to be published at a specified future time. Thee event gets published if the
|
|
197
|
-
* differnece between the current time and the scheduled time is less than 500ms.
|
|
198
|
-
*
|
|
199
|
-
* @param scheduledTime - The Date object representing the future time when the event should be published.
|
|
200
|
-
* @param eventData - The event data object, containing the event name and its associated data.
|
|
201
|
-
*
|
|
202
|
-
* @throws Error - Throws an error if the scheduled time is in the past.
|
|
203
|
-
*
|
|
204
|
-
* @example
|
|
205
|
-
*
|
|
206
|
-
* const streams = new Streams('app-service');
|
|
207
|
-
*
|
|
208
|
-
* const futureTime = new Date(Date.now() + 10000); // 10 seconds from now
|
|
209
|
-
* const eventData: EventData<string> = {
|
|
210
|
-
* eventName: 'order.created',
|
|
211
|
-
* data: 'Order data'
|
|
212
|
-
* };
|
|
213
|
-
*
|
|
214
|
-
* await streams.scheduledPublish(futureTime, eventData);
|
|
215
|
-
*/
|
|
216
|
-
scheduledPublish(scheduledTime, eventData, uniquePerInstance = false) {
|
|
217
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
218
|
-
const currentTime = new Date();
|
|
219
|
-
if (scheduledTime < currentTime) {
|
|
220
|
-
throw new Error('Cannot schedule an event in the past');
|
|
221
|
-
}
|
|
222
|
-
else if (Math.abs(scheduledTime.getTime() - currentTime.getTime()) <= 500) {
|
|
223
|
-
yield this.publish(eventData);
|
|
224
|
-
}
|
|
225
|
-
else {
|
|
226
|
-
if (uniquePerInstance === true) {
|
|
227
|
-
const existingJob = yield this.redisPublisher.zscore('se', JSON.stringify(eventData));
|
|
228
|
-
if (existingJob) {
|
|
229
|
-
console.log(`Job with data '${eventData}' already exists. Skipping.`);
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
yield this.redisPublisher.zadd('se', scheduledTime.getTime(), JSON.stringify(eventData));
|
|
234
|
-
}
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* Listens for events with the given name and returns an Observable that emits an EventData<T> object
|
|
239
|
-
* each time a new event is received.
|
|
240
|
-
*
|
|
241
|
-
* The method uses a BehaviorSubject to emit the events as Observables. The BehaviorSubject ensures
|
|
242
|
-
* that new subscribers receive the last emitted event, even if they subscribe after the event has been emitted.
|
|
243
|
-
*
|
|
244
|
-
* If an error occurs while subscribing, the method logs the error to the console and throws
|
|
245
|
-
* an error. This is done to prevent the service from continuing without a proper event subscription.
|
|
246
|
-
*
|
|
247
|
-
* There is retry logic with exponential backoff to handle error cases. These are also controllable by the
|
|
248
|
-
* calling service
|
|
249
|
-
*
|
|
250
|
-
* @param eventName - The name of the event to listen for.
|
|
251
|
-
*
|
|
252
|
-
* @returns An Observable that emits an EventData<T> object each time a new event is received.
|
|
253
|
-
*
|
|
254
|
-
* @example
|
|
255
|
-
*
|
|
256
|
-
* // Listen for "order.created" events
|
|
257
|
-
* const orderCreated = streams.listen<OrderCreatedEvent>('order.created');
|
|
258
|
-
*
|
|
259
|
-
* // Subscribe to the Observable and log each new event
|
|
260
|
-
* orderCreated.subscribe((event) => {
|
|
261
|
-
* console.log('New order created:', event.data);
|
|
262
|
-
* });
|
|
263
|
-
*/
|
|
264
|
-
listen(eventName, maxRetries = 5, initialDelay = 1000) {
|
|
265
|
-
this.registerConsumerGroup(eventName); // Registers the consumer group for listening to the message
|
|
266
|
-
this.eventsListened.push(eventName);
|
|
267
|
-
return this.listenInternals(eventName).pipe((0, rxjs_1.retry)({
|
|
268
|
-
count: maxRetries,
|
|
269
|
-
delay: (error, retryAttempt) => {
|
|
270
|
-
const delay = initialDelay * Math.pow(2, retryAttempt);
|
|
271
|
-
console.error(`Error in listen: ${error.message}. Retrying in ${delay}ms (attempt ${retryAttempt + 1})`);
|
|
272
|
-
return (0, rxjs_1.timer)(delay);
|
|
273
|
-
},
|
|
274
|
-
}), (0, rxjs_1.catchError)((error) => {
|
|
275
|
-
console.error(`Error in listen after ${maxRetries} retries: ${error.message}`);
|
|
276
|
-
return (0, rxjs_1.throwError)(() => new Error(error.message));
|
|
277
|
-
}));
|
|
278
|
-
}
|
|
279
|
-
listenInternals(eventName) {
|
|
280
|
-
try {
|
|
281
|
-
this.createConsumerGroup(eventName);
|
|
282
|
-
const bs = new rxjs_1.BehaviorSubject(null);
|
|
283
|
-
const observable = bs.asObservable().pipe((0, rxjs_1.skip)(1));
|
|
284
|
-
const streamName = `${eventName}:${this.consumerGroupName}`;
|
|
285
|
-
this.redisSubscriber.subscribe(eventName);
|
|
286
|
-
const processMessage = () => tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
287
|
-
try {
|
|
288
|
-
const result = yield this.redisGroups.xreadgroup('GROUP', this.consumerGroupName, this.instanceId, 'COUNT', 1, 'BLOCK', 0, 'STREAMS', streamName, '>');
|
|
289
|
-
if (result) {
|
|
290
|
-
const [, streamMessages] = result[0];
|
|
291
|
-
for (const [id, data] of streamMessages) {
|
|
292
|
-
const eventData = JSON.parse(data[1]);
|
|
293
|
-
const messageId = eventData.eventId;
|
|
294
|
-
const isDuplicate = yield this.isDuplicateMessage(streamName, messageId);
|
|
295
|
-
if (isDuplicate) {
|
|
296
|
-
console.warn(`Duplicate message detected: ${messageId}`);
|
|
297
|
-
yield this.redisGroups.xack(streamName, this.consumerGroupName, id);
|
|
298
|
-
continue;
|
|
299
|
-
}
|
|
300
|
-
bs.next(eventData);
|
|
301
|
-
const pmKey = `pm:${this.consumerGroupName}:${streamName}`;
|
|
302
|
-
const currentTime = Date.now();
|
|
303
|
-
const transaction = this.redisGroups.multi();
|
|
304
|
-
transaction.zadd(pmKey, currentTime, messageId);
|
|
305
|
-
transaction.xack(streamName, this.consumerGroupName, id);
|
|
306
|
-
transaction.zadd(`ack:${streamName}`, Date.now(), id);
|
|
307
|
-
yield transaction.exec();
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
catch (e) {
|
|
312
|
-
console.error(JSON.stringify(e));
|
|
313
|
-
}
|
|
314
|
-
});
|
|
315
|
-
this.redisSubscriber.on('message', () => tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
316
|
-
yield processMessage();
|
|
317
|
-
}));
|
|
318
|
-
return observable;
|
|
319
|
-
}
|
|
320
|
-
catch (e) {
|
|
321
|
-
console.error(JSON.stringify(e));
|
|
322
|
-
throw e;
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
/**
|
|
326
|
-
* This method takes all messages allocated to this instance and republishes them so
|
|
327
|
-
* that other instances of this service can receive and process them.
|
|
328
|
-
*
|
|
329
|
-
* This needs to be handled every 1-2 minutes if the queue becomes too long and messages
|
|
330
|
-
* are not being processed.
|
|
331
|
-
*
|
|
332
|
-
* Ideal implementation would be to wrap this inside a setInterval
|
|
333
|
-
* @param streamName
|
|
334
|
-
*/
|
|
335
|
-
republishUnprocessedEvents(eventName) {
|
|
336
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
337
|
-
const streamName = `${eventName}:${this.consumerGroupName}`;
|
|
338
|
-
const result = yield this.redisGroups.xreadgroup('GROUP', this.consumerGroupName, this.instanceId, 'STREAMS', streamName, '>');
|
|
339
|
-
if (result) {
|
|
340
|
-
const [, streamMessages] = result[0];
|
|
341
|
-
for (const [id, data] of streamMessages) {
|
|
342
|
-
const eventData = JSON.parse(data[1]);
|
|
343
|
-
console.log(`Unprocessed event: ${id}, data:`, eventData);
|
|
344
|
-
const transaction = this.redisGroups.multi();
|
|
345
|
-
// Republishing the events
|
|
346
|
-
transaction.xadd(streamName, '*', 'data', JSON.stringify(eventData));
|
|
347
|
-
transaction.publish(eventName, '');
|
|
348
|
-
transaction.xack(streamName, this.consumerGroupName, id);
|
|
349
|
-
yield transaction.exec();
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
});
|
|
353
|
-
}
|
|
354
|
-
/**
|
|
355
|
-
* This method is used to claim messages in the event of a service crash. This library currently
|
|
356
|
-
* does not detect a service crash. This needs to be built as an extension of Kubernetes and
|
|
357
|
-
* a standalone service that notifies this service to process the events that are marked as
|
|
358
|
-
* pending
|
|
359
|
-
*
|
|
360
|
-
* @param streamName
|
|
361
|
-
* @param idleTimeout
|
|
362
|
-
*
|
|
363
|
-
* * @example
|
|
364
|
-
*
|
|
365
|
-
* // Attempt to recover messages from the "order.created" stream with an idle timeout of 10 seconds
|
|
366
|
-
* await streams.recoverCrashedConsumerMessages('order.created', 10000);
|
|
367
|
-
*/
|
|
368
|
-
recoverCrashedConsumerMessages(eventName, idleTimeout) {
|
|
369
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
370
|
-
const streamName = `${eventName}:${this.consumerGroupName}`;
|
|
371
|
-
const pendingMessages = (yield this.redisGroups.xpending(streamName, this.consumerGroupName));
|
|
372
|
-
if (!pendingMessages)
|
|
373
|
-
return;
|
|
374
|
-
const [, minId, maxId, consumers] = pendingMessages;
|
|
375
|
-
for (const [consumer, pendingCount] of consumers) {
|
|
376
|
-
if (parseInt(pendingCount) > 0) {
|
|
377
|
-
const pending = (yield this.redisGroups.xpending(streamName, this.consumerGroupName, minId, maxId, Number(pendingCount), consumer));
|
|
378
|
-
for (const [messageId] of pending) {
|
|
379
|
-
const claimedMessage = (yield this.redisGroups.xclaim(streamName, this.consumerGroupName, this.instanceId, idleTimeout, messageId));
|
|
380
|
-
if (claimedMessage) {
|
|
381
|
-
const [, data] = claimedMessage[0];
|
|
382
|
-
const eventData = JSON.parse(data[1]);
|
|
383
|
-
const transaction = this.redisGroups.multi();
|
|
384
|
-
transaction.xadd(streamName, '*', 'data', JSON.stringify(eventData));
|
|
385
|
-
transaction.publish(eventName, '');
|
|
386
|
-
transaction.xack(streamName, this.consumerGroupName, messageId);
|
|
387
|
-
yield transaction.exec();
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
/**
|
|
395
|
-
* This method allows the possibility of a graceful shutdown by cleaning up the
|
|
396
|
-
* redis connections.
|
|
397
|
-
*
|
|
398
|
-
* In all services where the library is used, its better to implement this method
|
|
399
|
-
*
|
|
400
|
-
* process.on('SIGTERM', shutdown);
|
|
401
|
-
* process.on('SIGINT', shutdown);
|
|
402
|
-
*
|
|
403
|
-
* async function shutdown(): Promise<void> {
|
|
404
|
-
* console.log('Graceful shutdown initiated.');
|
|
405
|
-
* try {
|
|
406
|
-
* await streams.close();
|
|
407
|
-
* console.log('Resources and connections successfully closed.');
|
|
408
|
-
* } catch (error) {
|
|
409
|
-
* console.error('Error during graceful shutdown:', error);
|
|
410
|
-
* }
|
|
411
|
-
* process.exit(0);
|
|
412
|
-
* }
|
|
413
|
-
*/
|
|
414
|
-
close() {
|
|
415
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
416
|
-
this.clearSubscribedEvents();
|
|
417
|
-
if (this.redisPublisher) {
|
|
418
|
-
yield this.redisPublisher.quit();
|
|
419
|
-
}
|
|
420
|
-
if (this.redisSubscriber) {
|
|
421
|
-
yield this.redisSubscriber.quit();
|
|
422
|
-
}
|
|
423
|
-
if (this.redisGroups) {
|
|
424
|
-
yield this.redisGroups.quit();
|
|
425
|
-
}
|
|
426
|
-
if (this.cleanUpTimer) {
|
|
427
|
-
this.cleanUpTimer.unsubscribe();
|
|
428
|
-
}
|
|
429
|
-
});
|
|
430
|
-
}
|
|
431
|
-
clearSubscribedEvents() {
|
|
432
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
433
|
-
console.log(`${this.eventsListened.length} events to be cleared`);
|
|
434
|
-
for (const eventName of this.eventsListened) {
|
|
435
|
-
yield this.redisGroups.srem(`consumerGroups:${eventName}`, this.consumerGroupName);
|
|
436
|
-
}
|
|
437
|
-
});
|
|
438
|
-
}
|
|
439
|
-
registerConsumerGroup(eventName) {
|
|
440
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
441
|
-
yield this.redisGroups.sadd(`consumerGroups:${eventName}`, this.consumerGroupName);
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
cleanupAcknowledgedMessages(eventName, interval = 60 * 60 * 1000) {
|
|
445
|
-
return tslib_2.__awaiter(this, void 0, void 0, function* () {
|
|
446
|
-
const streamName = `${eventName}:${this.consumerGroupName}`;
|
|
447
|
-
const cleanupThreshold = Date.now() - interval;
|
|
448
|
-
const acknowledgedMessages = yield this.redisGroups.zrangebyscore(`ack:${streamName}`, '-inf', cleanupThreshold);
|
|
449
|
-
if (acknowledgedMessages && acknowledgedMessages.length > 0) {
|
|
450
|
-
const transaction = this.redisGroups.multi();
|
|
451
|
-
// Remove acknowledged messages from the stream
|
|
452
|
-
for (const messageId of acknowledgedMessages) {
|
|
453
|
-
transaction.xdel(streamName, messageId);
|
|
454
|
-
}
|
|
455
|
-
// Remove acknowledged messages from the Sorted Set
|
|
456
|
-
transaction.zremrangebyscore(`ack:${streamName}`, '-inf', cleanupThreshold);
|
|
457
|
-
yield transaction.exec();
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
exports.Streams = Streams;
|
|
463
|
-
});
|
|
464
|
-
define("src/lib/redis/scheduler", ["require", "exports", "tslib", "@jetit/id", "rxjs", "src/lib/redis/registry", "src/lib/redis/groups"], function (require, exports, tslib_3, id_2, rxjs_2, registry_2, groups_2) {
|
|
465
|
-
"use strict";
|
|
466
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
467
|
-
exports.ScheduledProcessor = void 0;
|
|
468
|
-
/**
|
|
469
|
-
* DO NOT USE THIS CLASS IF YOU DON'T KNOW WHAT YOU ARE DOING. This class is
|
|
470
|
-
* meant to be used internally by the scheduler application
|
|
471
|
-
*/
|
|
472
|
-
class ScheduledProcessor {
|
|
473
|
-
get redisPublisher() {
|
|
474
|
-
if (!this._redisPublisher)
|
|
475
|
-
this._redisPublisher = registry_2.RedisRegistry.getConnection('publish');
|
|
476
|
-
return this._redisPublisher;
|
|
477
|
-
}
|
|
478
|
-
constructor(duration = 1000) {
|
|
479
|
-
this.previousTaskCompleted = true;
|
|
480
|
-
this.scheduledMessagesTimer = (0, rxjs_2.interval)(duration).subscribe(() => {
|
|
481
|
-
console.log('Checking Streams messages at ', new Date().toISOString(), '...');
|
|
482
|
-
/** Do not run scheduler if the previous run is not completed */
|
|
483
|
-
if (this.previousTaskCompleted) {
|
|
484
|
-
this.previousTaskCompleted = false;
|
|
485
|
-
this.processScheduledEvents()
|
|
486
|
-
.catch((error) => {
|
|
487
|
-
console.error('Error while processing scheduled events:', error);
|
|
488
|
-
})
|
|
489
|
-
.then(() => {
|
|
490
|
-
this.previousTaskCompleted = true;
|
|
491
|
-
});
|
|
492
|
-
}
|
|
493
|
-
else {
|
|
494
|
-
console.log('Skipping current scheduler run because previous run is in progress');
|
|
495
|
-
}
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
processScheduledEvents() {
|
|
499
|
-
return tslib_3.__awaiter(this, void 0, void 0, function* () {
|
|
500
|
-
const currentTime = new Date().getTime();
|
|
501
|
-
const events = yield this.redisPublisher.zrangebyscore('se', 0, currentTime);
|
|
502
|
-
console.log('Events to process:', events.length);
|
|
503
|
-
for (const eventString of events) {
|
|
504
|
-
const eventData = JSON.parse(eventString);
|
|
505
|
-
/**
|
|
506
|
-
* Remove the event from the Redis Sorted Set first. Please note that
|
|
507
|
-
* there is a chance of failure here if the process crashes before
|
|
508
|
-
* the event is published. In that case, the event will be lost.
|
|
509
|
-
*
|
|
510
|
-
* Instead of using the publish method directly, the entire logic is
|
|
511
|
-
* copy pasted to reduce the case of failure.
|
|
512
|
-
*/
|
|
513
|
-
const transaction = this.redisPublisher.multi();
|
|
514
|
-
eventData.eventId = (0, id_2.generateID)('HEX', 'FF');
|
|
515
|
-
transaction.zrem('se', eventString);
|
|
516
|
-
const consumerGroups = yield (0, groups_2.getAllConsumerGroups)(eventData.eventName, this.redisPublisher);
|
|
517
|
-
console.log('Scheduled Publishing to consumer groups: ', consumerGroups, 'with id ', eventData.eventId, '...');
|
|
518
|
-
for (const consumerGroup of consumerGroups) {
|
|
519
|
-
// Publish the event to each consumer group's stream
|
|
520
|
-
const streamName = `${eventData.eventName}:${consumerGroup}`;
|
|
521
|
-
transaction.xadd(streamName, '*', 'data', JSON.stringify(eventData));
|
|
522
|
-
}
|
|
523
|
-
transaction.publish(eventData.eventName, '');
|
|
524
|
-
yield transaction.exec();
|
|
525
|
-
}
|
|
526
|
-
});
|
|
527
|
-
}
|
|
528
|
-
getAllScheduledEvents() {
|
|
529
|
-
return this.redisPublisher.zrange('se', 0, -1);
|
|
530
|
-
}
|
|
531
|
-
close() {
|
|
532
|
-
return tslib_3.__awaiter(this, void 0, void 0, function* () {
|
|
533
|
-
if (this.scheduledMessagesTimer) {
|
|
534
|
-
this.scheduledMessagesTimer.unsubscribe();
|
|
535
|
-
}
|
|
536
|
-
});
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
exports.ScheduledProcessor = ScheduledProcessor;
|
|
540
|
-
});
|
|
541
|
-
define("src/lib/publisher", ["require", "exports", "src/lib/redis/streams", "src/lib/redis/registry", "src/lib/redis/scheduler"], function (require, exports, streams_1, registry_3, scheduler_1) {
|
|
542
|
-
"use strict";
|
|
543
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
544
|
-
exports.__SCHEDULER_INTERNALS__ = exports.setRedisConfig = exports.Publisher = void 0;
|
|
545
|
-
Object.defineProperty(exports, "Publisher", { enumerable: true, get: function () { return streams_1.Streams; } });
|
|
546
|
-
Object.defineProperty(exports, "setRedisConfig", { enumerable: true, get: function () { return registry_3.setRedisConnectionSettings; } });
|
|
547
|
-
Object.defineProperty(exports, "__SCHEDULER_INTERNALS__", { enumerable: true, get: function () { return scheduler_1.ScheduledProcessor; } });
|
|
548
|
-
});
|
|
549
|
-
define("src/index", ["require", "exports", "tslib", "src/lib/publisher"], function (require, exports, tslib_4, publisher_1) {
|
|
550
|
-
"use strict";
|
|
551
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
552
|
-
tslib_4.__exportStar(publisher_1, exports);
|
|
553
|
-
});
|