@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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jetit/publisher",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "type": "commonjs",
5
5
  "dependencies": {
6
6
  "@jetit/id": "0.0.6",
@@ -12,5 +12,6 @@
12
12
  "tslib": "2.5.0"
13
13
  },
14
14
  "main": "./src/index.js",
15
- "types": "./src/index.d.ts"
15
+ "types": "./src/index.d.ts",
16
+ "readme":"README.md"
16
17
  }
package/src/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # publisher
2
+
3
+ publisher is a library for implementing an event-driven architecture using Redis PUB/SUB and Redis Streams. It provides a simple and scalable mechanism for publishing and consuming events in real-time, and supports features such as message deduplication, consumer group management, and scheduled event publishing.
4
+
5
+ ## Simple Example
6
+
7
+ ```typescript
8
+ import { Publisher, EventData } from '@jetit/streams';
9
+
10
+ // Create an instance of the publisher
11
+ const streams = new Streams('Websockets');
12
+
13
+ // Publish an event
14
+ const eventData: EventData<{ message: string }> = {
15
+ eventName: 'my-event',
16
+ data: { message: 'Hello, world!' }
17
+ };
18
+
19
+ await streams.publish(eventData);
20
+
21
+ // Subscribe to an event
22
+ streams.listen('my-event').subscribe(event => {
23
+ console.log(`Received event: ${event.eventName}`, event.data);
24
+ });
25
+ ```
26
+
27
+ ## Possible use cases
28
+
29
+ 1. Microservices communication: If your system is composed of multiple microservices, the publisher can be used to facilitate communication between them by publishing and listening to events.
30
+
31
+ 2. Event sourcing and CQRS: In an event-sourced system, the publisher can be used to store and process events that represent the state changes of the system, enabling Command Query Responsibility Segregation (CQRS) by separating the read and write models.
32
+
33
+ 3. Task queues: The publisher can be used to create task queues for distributing workloads among different worker instances, ensuring that tasks are processed in the order they were created.
34
+
35
+ 4. Data streaming and processing: The publisher can be used to ingest and process large volumes of data in real-time, such as log files, clickstream data, or other event-based data.
36
+
37
+ 5. Distributed system coordination: In a distributed system, the publisher can be used for coordination between different components, such as managing leader election or maintaining configuration information.
38
+
39
+ 6. Real-time analytics and monitoring: The publisher can be used to collect and process real-time analytics data, such as user behavior, application performance metrics, or system monitoring information.
40
+
41
+ 7. Event-driven workflows: You can use the publisher to create event-driven workflows, where each step in the workflow is triggered by the completion of a previous step. This can be useful for orchestrating complex, multi-step processes.
42
+
43
+ 8. Message broadcasting: The publisher can be used to broadcast messages to multiple consumers or subscribers, allowing for efficient and scalable communication in applications with many components or services.
package/src/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './lib/publisher';
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./lib/publisher"), exports);
@@ -0,0 +1,3 @@
1
+ export { Streams as Publisher } from './redis/streams';
2
+ export { setRedisConnectionSettings as setRedisConfig } from './redis/registry';
3
+ export { ScheduledProcessor as __SCHEDULER_INTERNALS__ } from './redis/scheduler';
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.__SCHEDULER_INTERNALS__ = exports.setRedisConfig = exports.Publisher = void 0;
4
+ var streams_1 = require("./redis/streams");
5
+ Object.defineProperty(exports, "Publisher", { enumerable: true, get: function () { return streams_1.Streams; } });
6
+ var registry_1 = require("./redis/registry");
7
+ Object.defineProperty(exports, "setRedisConfig", { enumerable: true, get: function () { return registry_1.setRedisConnectionSettings; } });
8
+ var scheduler_1 = require("./redis/scheduler");
9
+ Object.defineProperty(exports, "__SCHEDULER_INTERNALS__", { enumerable: true, get: function () { return scheduler_1.ScheduledProcessor; } });
@@ -0,0 +1,2 @@
1
+ import { RedisType } from './registry';
2
+ export declare function getAllConsumerGroups(eventName: string, redisConnection: RedisType): Promise<string[]>;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAllConsumerGroups = void 0;
4
+ const tslib_1 = require("tslib");
5
+ function getAllConsumerGroups(eventName, redisConnection) {
6
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
7
+ const consumerGroups = yield redisConnection.smembers(`consumerGroups:${eventName}`);
8
+ return consumerGroups;
9
+ });
10
+ }
11
+ exports.getAllConsumerGroups = getAllConsumerGroups;
@@ -0,0 +1,20 @@
1
+ import Redis, { Cluster } from 'ioredis';
2
+ import { IOptions } from './types';
3
+ export type RedisType = Redis | Cluster;
4
+ export declare class RedisRegistry {
5
+ private static registry;
6
+ private static options;
7
+ static attemptConnection(connectionKey: string, storeRef?: number): Redis;
8
+ static getConnection(connectionType?: string, storeRef?: number): RedisType;
9
+ static setOptions(options: IOptions): void;
10
+ static _getOptions(): IOptions;
11
+ }
12
+ /**
13
+ * This function is used to set Redis Connection options per instance. If no
14
+ * options are provided, then the service connects as to a single instance
15
+ * with the environment values from REDIS_PORT and REDIS_HOST. if those
16
+ * environment values are not provided, it attempts to connect to localhost:6379
17
+ *
18
+ * @param options
19
+ */
20
+ export declare function setRedisConnectionSettings(options: IOptions): void;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var _a, _b;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.setRedisConnectionSettings = exports.RedisRegistry = void 0;
5
+ const ioredis_1 = require("ioredis");
6
+ class RedisRegistry {
7
+ static attemptConnection(connectionKey, storeRef = 0) {
8
+ let ref;
9
+ if (RedisRegistry.options.cluster) {
10
+ ref = new ioredis_1.Cluster(RedisRegistry.options.cluster.nodes, Object.assign(Object.assign({}, RedisRegistry.options.cluster.options), { redisOptions: {
11
+ db: storeRef,
12
+ } }));
13
+ }
14
+ ref = new ioredis_1.default(Object.assign(Object.assign({}, RedisRegistry.options.redis), { db: storeRef }));
15
+ RedisRegistry.registry.set(connectionKey, ref);
16
+ return ref;
17
+ }
18
+ static getConnection(connectionType = 'primary', storeRef = 0) {
19
+ const connectionKey = `${connectionType}${storeRef}`;
20
+ let ref = this.registry.get(connectionKey);
21
+ if (!ref) {
22
+ if (RedisRegistry.options.cluster) {
23
+ ref = new ioredis_1.Cluster(RedisRegistry.options.cluster.nodes, Object.assign(Object.assign({}, RedisRegistry.options.cluster.options), { redisOptions: {
24
+ db: storeRef,
25
+ } }));
26
+ }
27
+ ref = new ioredis_1.default(Object.assign(Object.assign({}, RedisRegistry.options.redis), { db: storeRef }));
28
+ }
29
+ return ref;
30
+ }
31
+ static setOptions(options) {
32
+ RedisRegistry.options = options;
33
+ }
34
+ static _getOptions() {
35
+ return RedisRegistry.options;
36
+ }
37
+ }
38
+ RedisRegistry.registry = new Map();
39
+ RedisRegistry.options = {
40
+ redis: {
41
+ port: parseInt((_a = process.env['REDIS_PORT']) !== null && _a !== void 0 ? _a : '6379'),
42
+ host: (_b = process.env['REDIS_HOST']) !== null && _b !== void 0 ? _b : 'localhost',
43
+ },
44
+ };
45
+ exports.RedisRegistry = RedisRegistry;
46
+ /**
47
+ * This function is used to set Redis Connection options per instance. If no
48
+ * options are provided, then the service connects as to a single instance
49
+ * with the environment values from REDIS_PORT and REDIS_HOST. if those
50
+ * environment values are not provided, it attempts to connect to localhost:6379
51
+ *
52
+ * @param options
53
+ */
54
+ function setRedisConnectionSettings(options) {
55
+ RedisRegistry.setOptions(options);
56
+ }
57
+ exports.setRedisConnectionSettings = setRedisConnectionSettings;
@@ -0,0 +1,15 @@
1
+ import { RedisType } from './registry';
2
+ /**
3
+ * DO NOT USE THIS CLASS IF YOU DON'T KNOW WHAT YOU ARE DOING. This class is
4
+ * meant to be used internally by the scheduler application
5
+ */
6
+ export declare class ScheduledProcessor {
7
+ private scheduledMessagesTimer;
8
+ private _redisPublisher?;
9
+ private previousTaskCompleted;
10
+ get redisPublisher(): RedisType;
11
+ constructor(duration?: number);
12
+ private processScheduledEvents;
13
+ getAllScheduledEvents(): Promise<Array<string>>;
14
+ close(): Promise<void>;
15
+ }
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ScheduledProcessor = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const id_1 = require("@jetit/id");
6
+ const rxjs_1 = require("rxjs");
7
+ const registry_1 = require("./registry");
8
+ const groups_1 = require("./groups");
9
+ /**
10
+ * DO NOT USE THIS CLASS IF YOU DON'T KNOW WHAT YOU ARE DOING. This class is
11
+ * meant to be used internally by the scheduler application
12
+ */
13
+ class ScheduledProcessor {
14
+ get redisPublisher() {
15
+ if (!this._redisPublisher)
16
+ this._redisPublisher = registry_1.RedisRegistry.getConnection('publish');
17
+ return this._redisPublisher;
18
+ }
19
+ constructor(duration = 1000) {
20
+ this.previousTaskCompleted = true;
21
+ this.scheduledMessagesTimer = (0, rxjs_1.interval)(duration).subscribe(() => {
22
+ console.log('Checking Streams messages at ', new Date().toISOString(), '...');
23
+ /** Do not run scheduler if the previous run is not completed */
24
+ if (this.previousTaskCompleted) {
25
+ this.previousTaskCompleted = false;
26
+ this.processScheduledEvents()
27
+ .catch((error) => {
28
+ console.error('Error while processing scheduled events:', error);
29
+ })
30
+ .then(() => {
31
+ this.previousTaskCompleted = true;
32
+ });
33
+ }
34
+ else {
35
+ console.log('Skipping current scheduler run because previous run is in progress');
36
+ }
37
+ });
38
+ }
39
+ processScheduledEvents() {
40
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
41
+ const currentTime = new Date().getTime();
42
+ const events = yield this.redisPublisher.zrangebyscore('se', 0, currentTime);
43
+ console.log('Events to process:', events.length);
44
+ for (const eventString of events) {
45
+ const eventData = JSON.parse(eventString);
46
+ /**
47
+ * Remove the event from the Redis Sorted Set first. Please note that
48
+ * there is a chance of failure here if the process crashes before
49
+ * the event is published. In that case, the event will be lost.
50
+ *
51
+ * Instead of using the publish method directly, the entire logic is
52
+ * copy pasted to reduce the case of failure.
53
+ */
54
+ const transaction = this.redisPublisher.multi();
55
+ eventData.eventId = (0, id_1.generateID)('HEX', 'FF');
56
+ transaction.zrem('se', eventString);
57
+ const consumerGroups = yield (0, groups_1.getAllConsumerGroups)(eventData.eventName, this.redisPublisher);
58
+ console.log('Scheduled Publishing to consumer groups: ', consumerGroups, 'with id ', eventData.eventId, '...');
59
+ for (const consumerGroup of consumerGroups) {
60
+ // Publish the event to each consumer group's stream
61
+ const streamName = `${eventData.eventName}:${consumerGroup}`;
62
+ transaction.xadd(streamName, '*', 'data', JSON.stringify(eventData));
63
+ }
64
+ transaction.publish(eventData.eventName, '');
65
+ yield transaction.exec();
66
+ }
67
+ });
68
+ }
69
+ getAllScheduledEvents() {
70
+ return this.redisPublisher.zrange('se', 0, -1);
71
+ }
72
+ close() {
73
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
74
+ if (this.scheduledMessagesTimer) {
75
+ this.scheduledMessagesTimer.unsubscribe();
76
+ }
77
+ });
78
+ }
79
+ }
80
+ exports.ScheduledProcessor = ScheduledProcessor;
@@ -0,0 +1,152 @@
1
+ import { RedisType } from './registry';
2
+ import { EventData } from './types';
3
+ import { Observable } from 'rxjs';
4
+ export declare class Streams {
5
+ private _redisPublisher?;
6
+ private _redisSubscriber?;
7
+ private _redisGroups?;
8
+ private consumerGroupName;
9
+ private instanceId;
10
+ private cleanUpTimer;
11
+ private eventsListened;
12
+ get redisPublisher(): RedisType;
13
+ get redisSubscriber(): RedisType;
14
+ get redisGroups(): RedisType;
15
+ /**
16
+ * Creates a new Streams instance for a given service.
17
+ *
18
+ * The constructor initializes the Redis connections for publishers, subscribers, and consumer groups.
19
+ * It also sets up an interval timer for clearing expired messages from Redis and another interval timer
20
+ * for processing scheduled events at regular intervals.
21
+ *
22
+ * @param serviceName - A unique name for the service that will be using this Streams instance.
23
+ *
24
+ * @example
25
+ *
26
+ * // Create a new Streams instance for the "POS" service
27
+ * const streams = new Streams('POS');
28
+ */
29
+ constructor(serviceName: string);
30
+ private createConsumerGroup;
31
+ private isDuplicateMessage;
32
+ private clearDuplicationCheckKeys;
33
+ /**
34
+ * Publishes an event with the given data to the Redis event stream.
35
+ *
36
+ * The method generates a unique event ID for each event, and adds it to the event data to handle message
37
+ * deduplication.
38
+ *
39
+ * @param data - An EventData<T> object containing the data for the event.
40
+ *
41
+ * @returns A Promise that resolves when the event has been published to the Redis stream.
42
+ *
43
+ * @example
44
+ *
45
+ * // Publish an "order.created" event with the given order data
46
+ * const orderData = { id: '123', customerName: 'John Doe', amount: 100 };
47
+ * const eventData = { eventName: 'order.created', data: orderData };
48
+ * await streams.publish(eventData);
49
+ */
50
+ publish<T>(data: EventData<T>): Promise<void>;
51
+ /**
52
+ * Schedules an event to be published at a specified future time. Thee event gets published if the
53
+ * differnece between the current time and the scheduled time is less than 500ms.
54
+ *
55
+ * @param scheduledTime - The Date object representing the future time when the event should be published.
56
+ * @param eventData - The event data object, containing the event name and its associated data.
57
+ *
58
+ * @throws Error - Throws an error if the scheduled time is in the past.
59
+ *
60
+ * @example
61
+ *
62
+ * const streams = new Streams('app-service');
63
+ *
64
+ * const futureTime = new Date(Date.now() + 10000); // 10 seconds from now
65
+ * const eventData: EventData<string> = {
66
+ * eventName: 'order.created',
67
+ * data: 'Order data'
68
+ * };
69
+ *
70
+ * await streams.scheduledPublish(futureTime, eventData);
71
+ */
72
+ scheduledPublish<T>(scheduledTime: Date, eventData: EventData<T>, uniquePerInstance?: boolean): Promise<void>;
73
+ /**
74
+ * Listens for events with the given name and returns an Observable that emits an EventData<T> object
75
+ * each time a new event is received.
76
+ *
77
+ * The method uses a BehaviorSubject to emit the events as Observables. The BehaviorSubject ensures
78
+ * that new subscribers receive the last emitted event, even if they subscribe after the event has been emitted.
79
+ *
80
+ * If an error occurs while subscribing, the method logs the error to the console and throws
81
+ * an error. This is done to prevent the service from continuing without a proper event subscription.
82
+ *
83
+ * There is retry logic with exponential backoff to handle error cases. These are also controllable by the
84
+ * calling service
85
+ *
86
+ * @param eventName - The name of the event to listen for.
87
+ *
88
+ * @returns An Observable that emits an EventData<T> object each time a new event is received.
89
+ *
90
+ * @example
91
+ *
92
+ * // Listen for "order.created" events
93
+ * const orderCreated = streams.listen<OrderCreatedEvent>('order.created');
94
+ *
95
+ * // Subscribe to the Observable and log each new event
96
+ * orderCreated.subscribe((event) => {
97
+ * console.log('New order created:', event.data);
98
+ * });
99
+ */
100
+ listen<T>(eventName: string, maxRetries?: number, initialDelay?: number): Observable<EventData<T>>;
101
+ private listenInternals;
102
+ /**
103
+ * This method takes all messages allocated to this instance and republishes them so
104
+ * that other instances of this service can receive and process them.
105
+ *
106
+ * This needs to be handled every 1-2 minutes if the queue becomes too long and messages
107
+ * are not being processed.
108
+ *
109
+ * Ideal implementation would be to wrap this inside a setInterval
110
+ * @param streamName
111
+ */
112
+ republishUnprocessedEvents(eventName: string): Promise<void>;
113
+ /**
114
+ * This method is used to claim messages in the event of a service crash. This library currently
115
+ * does not detect a service crash. This needs to be built as an extension of Kubernetes and
116
+ * a standalone service that notifies this service to process the events that are marked as
117
+ * pending
118
+ *
119
+ * @param streamName
120
+ * @param idleTimeout
121
+ *
122
+ * * @example
123
+ *
124
+ * // Attempt to recover messages from the "order.created" stream with an idle timeout of 10 seconds
125
+ * await streams.recoverCrashedConsumerMessages('order.created', 10000);
126
+ */
127
+ recoverCrashedConsumerMessages(eventName: string, idleTimeout: number): Promise<void>;
128
+ /**
129
+ * This method allows the possibility of a graceful shutdown by cleaning up the
130
+ * redis connections.
131
+ *
132
+ * In all services where the library is used, its better to implement this method
133
+ *
134
+ * process.on('SIGTERM', shutdown);
135
+ * process.on('SIGINT', shutdown);
136
+ *
137
+ * async function shutdown(): Promise<void> {
138
+ * console.log('Graceful shutdown initiated.');
139
+ * try {
140
+ * await streams.close();
141
+ * console.log('Resources and connections successfully closed.');
142
+ * } catch (error) {
143
+ * console.error('Error during graceful shutdown:', error);
144
+ * }
145
+ * process.exit(0);
146
+ * }
147
+ */
148
+ close(): Promise<void>;
149
+ private clearSubscribedEvents;
150
+ private registerConsumerGroup;
151
+ private cleanupAcknowledgedMessages;
152
+ }