@flusys/nestjs-shared 6.4.0 → 7.0.0-beta.1
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/README.md +437 -0
- package/cjs/classes/api-service.class.js +71 -8
- package/cjs/classes/api-service.class.spec.js +220 -0
- package/cjs/classes/disabled-event-bus.class.js +15 -0
- package/cjs/classes/disabled-event-bus.class.spec.js +40 -0
- package/cjs/classes/domain-event.publisher.js +76 -0
- package/cjs/classes/domain-event.publisher.spec.js +234 -0
- package/cjs/classes/event-bus.registry.js +69 -0
- package/cjs/classes/event-bus.registry.spec.js +116 -0
- package/cjs/classes/event-transports/event-transport.registry.js +41 -0
- package/cjs/classes/event-transports/event-transport.registry.spec.js +31 -0
- package/cjs/classes/event-transports/index.js +23 -0
- package/cjs/classes/event-transports/kafka-transport.optional.js +151 -0
- package/cjs/classes/event-transports/kafka-transport.optional.spec.js +199 -0
- package/cjs/classes/event-transports/memory-transport.js +54 -0
- package/cjs/classes/event-transports/memory-transport.spec.js +58 -0
- package/cjs/classes/event-transports/rabbitmq-transport.optional.js +184 -0
- package/cjs/classes/event-transports/rabbitmq-transport.optional.spec.js +256 -0
- package/cjs/classes/hybrid-event-bus.class.js +261 -0
- package/cjs/classes/hybrid-event-bus.class.spec.js +189 -0
- package/cjs/classes/index.js +5 -0
- package/cjs/constants/index.js +24 -0
- package/cjs/decorators/index.js +1 -0
- package/cjs/decorators/on-domain-event.decorator.js +13 -0
- package/cjs/decorators/on-domain-event.decorator.spec.js +50 -0
- package/cjs/entities/user-root.js +2 -2
- package/cjs/enums/event-action.enum.js +18 -0
- package/cjs/enums/index.js +1 -0
- package/cjs/interfaces/event-bus.interface.js +4 -0
- package/cjs/interfaces/index.js +1 -0
- package/cjs/modules/event-bus/event-bus.explorer.js +124 -0
- package/cjs/modules/event-bus/event-bus.explorer.spec.js +189 -0
- package/cjs/modules/event-bus/event-bus.integration.spec.js +254 -0
- package/cjs/modules/event-bus/event-bus.module.js +94 -0
- package/cjs/modules/event-bus/event-bus.module.spec.js +149 -0
- package/cjs/modules/event-bus/module-events.provider.js +39 -0
- package/cjs/modules/event-bus/module-events.provider.spec.js +56 -0
- package/cjs/modules/index.js +3 -0
- package/cjs/utils/event-pattern.util.js +98 -0
- package/cjs/utils/event-pattern.util.spec.js +234 -0
- package/cjs/utils/index.js +2 -0
- package/cjs/utils/optional-module.util.js +35 -0
- package/cjs/utils/optional-module.util.spec.js +14 -0
- package/classes/api-service.class.d.ts +11 -1
- package/classes/disabled-event-bus.class.d.ts +6 -0
- package/classes/domain-event.publisher.d.ts +14 -0
- package/classes/event-bus.registry.d.ts +14 -0
- package/classes/event-transports/event-transport.registry.d.ts +10 -0
- package/classes/event-transports/index.d.ts +2 -0
- package/classes/event-transports/kafka-transport.optional.d.ts +21 -0
- package/classes/event-transports/memory-transport.d.ts +13 -0
- package/classes/event-transports/rabbitmq-transport.optional.d.ts +27 -0
- package/classes/hybrid-event-bus.class.d.ts +32 -0
- package/classes/index.d.ts +5 -0
- package/constants/index.d.ts +6 -0
- package/decorators/index.d.ts +1 -0
- package/decorators/on-domain-event.decorator.d.ts +1 -0
- package/enums/event-action.enum.d.ts +7 -0
- package/enums/index.d.ts +1 -0
- package/fesm/classes/api-service.class.js +71 -8
- package/fesm/classes/api-service.class.spec.js +220 -0
- package/fesm/classes/disabled-event-bus.class.js +11 -0
- package/fesm/classes/disabled-event-bus.class.spec.js +36 -0
- package/fesm/classes/domain-event.publisher.js +63 -0
- package/fesm/classes/domain-event.publisher.spec.js +230 -0
- package/fesm/classes/event-bus.registry.js +65 -0
- package/fesm/classes/event-bus.registry.spec.js +112 -0
- package/fesm/classes/event-transports/event-transport.registry.js +35 -0
- package/fesm/classes/event-transports/event-transport.registry.spec.js +27 -0
- package/fesm/classes/event-transports/index.js +6 -0
- package/fesm/classes/event-transports/kafka-transport.optional.js +144 -0
- package/fesm/classes/event-transports/kafka-transport.optional.spec.js +195 -0
- package/fesm/classes/event-transports/memory-transport.js +46 -0
- package/fesm/classes/event-transports/memory-transport.spec.js +54 -0
- package/fesm/classes/event-transports/rabbitmq-transport.optional.js +174 -0
- package/fesm/classes/event-transports/rabbitmq-transport.optional.spec.js +252 -0
- package/fesm/classes/hybrid-event-bus.class.js +217 -0
- package/fesm/classes/hybrid-event-bus.class.spec.js +185 -0
- package/fesm/classes/index.js +5 -0
- package/fesm/constants/index.js +7 -0
- package/fesm/decorators/index.js +1 -0
- package/fesm/decorators/on-domain-event.decorator.js +10 -0
- package/fesm/decorators/on-domain-event.decorator.spec.js +46 -0
- package/fesm/entities/user-root.js +1 -1
- package/fesm/enums/event-action.enum.js +8 -0
- package/fesm/enums/index.js +1 -0
- package/fesm/interfaces/event-bus.interface.js +1 -0
- package/fesm/interfaces/index.js +1 -0
- package/fesm/modules/event-bus/event-bus.explorer.js +114 -0
- package/fesm/modules/event-bus/event-bus.explorer.spec.js +185 -0
- package/fesm/modules/event-bus/event-bus.integration.spec.js +250 -0
- package/fesm/modules/event-bus/event-bus.module.js +84 -0
- package/fesm/modules/event-bus/event-bus.module.spec.js +145 -0
- package/fesm/modules/event-bus/module-events.provider.js +26 -0
- package/fesm/modules/event-bus/module-events.provider.spec.js +52 -0
- package/fesm/modules/index.js +3 -0
- package/fesm/utils/event-pattern.util.js +86 -0
- package/fesm/utils/event-pattern.util.spec.js +230 -0
- package/fesm/utils/index.js +2 -0
- package/fesm/utils/optional-module.util.js +25 -0
- package/fesm/utils/optional-module.util.spec.js +10 -0
- package/interfaces/event-bus.interface.d.ts +74 -0
- package/interfaces/index.d.ts +1 -0
- package/modules/event-bus/event-bus.explorer.d.ts +14 -0
- package/modules/event-bus/event-bus.module.d.ts +8 -0
- package/modules/event-bus/module-events.provider.d.ts +3 -0
- package/modules/index.d.ts +3 -0
- package/package.json +2 -2
- package/utils/event-pattern.util.d.ts +3 -0
- package/utils/index.d.ts +2 -0
- package/utils/optional-module.util.d.ts +1 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
const mockLoadOptionalModule = jest.fn();
|
|
2
|
+
jest.mock('../../utils/optional-module.util', ()=>({
|
|
3
|
+
loadOptionalModule: (...args)=>mockLoadOptionalModule(...args)
|
|
4
|
+
}));
|
|
5
|
+
import { InternalServerErrorException, Logger } from '@nestjs/common';
|
|
6
|
+
import { EventAction } from '../../enums/event-action.enum';
|
|
7
|
+
import { RabbitMqTransport } from './rabbitmq-transport.optional';
|
|
8
|
+
function buildEvent() {
|
|
9
|
+
return {
|
|
10
|
+
id: 'event-1',
|
|
11
|
+
name: 'storage.folder.created',
|
|
12
|
+
module: 'storage',
|
|
13
|
+
entity: 'folder',
|
|
14
|
+
action: EventAction.CREATED,
|
|
15
|
+
payload: {
|
|
16
|
+
ids: [
|
|
17
|
+
'1'
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
actor: {},
|
|
21
|
+
occurredAt: '2026-01-01T00:00:00.000Z',
|
|
22
|
+
version: 1
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function createChannelMock() {
|
|
26
|
+
return {
|
|
27
|
+
assertExchange: jest.fn().mockResolvedValue(undefined),
|
|
28
|
+
assertQueue: jest.fn().mockResolvedValue(undefined),
|
|
29
|
+
prefetch: jest.fn().mockResolvedValue(undefined),
|
|
30
|
+
bindQueue: jest.fn().mockResolvedValue(undefined),
|
|
31
|
+
consume: jest.fn().mockResolvedValue(undefined),
|
|
32
|
+
publish: jest.fn(),
|
|
33
|
+
ack: jest.fn(),
|
|
34
|
+
nack: jest.fn(),
|
|
35
|
+
on: jest.fn(),
|
|
36
|
+
removeAllListeners: jest.fn(),
|
|
37
|
+
close: jest.fn().mockResolvedValue(undefined)
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** A reconnect must land on a fresh channel, so every createChannel yields one */ function createAmqpMock() {
|
|
41
|
+
const channels = [];
|
|
42
|
+
const connection = {
|
|
43
|
+
createChannel: jest.fn(async ()=>{
|
|
44
|
+
const channel = createChannelMock();
|
|
45
|
+
channels.push(channel);
|
|
46
|
+
return channel;
|
|
47
|
+
}),
|
|
48
|
+
on: jest.fn(),
|
|
49
|
+
removeAllListeners: jest.fn(),
|
|
50
|
+
close: jest.fn().mockResolvedValue(undefined)
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
channels,
|
|
54
|
+
connection,
|
|
55
|
+
connect: jest.fn().mockResolvedValue(connection),
|
|
56
|
+
get channel () {
|
|
57
|
+
return channels[channels.length - 1];
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function listenerFor(target, event) {
|
|
62
|
+
const registered = target.on.mock.calls.find(([name])=>name === event);
|
|
63
|
+
if (!registered) throw new Error(`No '${event}' listener was registered`);
|
|
64
|
+
return registered[1];
|
|
65
|
+
}
|
|
66
|
+
describe('RabbitMqTransport', ()=>{
|
|
67
|
+
let amqp;
|
|
68
|
+
let warnSpy;
|
|
69
|
+
let errorSpy;
|
|
70
|
+
beforeEach(()=>{
|
|
71
|
+
amqp = createAmqpMock();
|
|
72
|
+
mockLoadOptionalModule.mockResolvedValue({
|
|
73
|
+
connect: amqp.connect
|
|
74
|
+
});
|
|
75
|
+
warnSpy = jest.spyOn(Logger.prototype, 'warn').mockImplementation(()=>undefined);
|
|
76
|
+
errorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(()=>undefined);
|
|
77
|
+
});
|
|
78
|
+
afterEach(()=>{
|
|
79
|
+
warnSpy.mockRestore();
|
|
80
|
+
errorSpy.mockRestore();
|
|
81
|
+
jest.clearAllMocks();
|
|
82
|
+
});
|
|
83
|
+
it('should throw a descriptive error when amqplib is not installed', async ()=>{
|
|
84
|
+
mockLoadOptionalModule.mockRejectedValue(new Error('Cannot find module'));
|
|
85
|
+
await expect(new RabbitMqTransport().connect()).rejects.toThrow(InternalServerErrorException);
|
|
86
|
+
});
|
|
87
|
+
it('should assert a topic exchange and a durable queue on connect', async ()=>{
|
|
88
|
+
const transport = new RabbitMqTransport({
|
|
89
|
+
exchange: 'ex',
|
|
90
|
+
queue: 'svc.events'
|
|
91
|
+
});
|
|
92
|
+
await transport.connect();
|
|
93
|
+
expect(amqp.channel.assertExchange).toHaveBeenCalledWith('ex', 'topic', {
|
|
94
|
+
durable: true
|
|
95
|
+
});
|
|
96
|
+
expect(amqp.channel.assertQueue).toHaveBeenCalledWith('svc.events', {
|
|
97
|
+
durable: true
|
|
98
|
+
});
|
|
99
|
+
expect(transport.isReady()).toBe(true);
|
|
100
|
+
});
|
|
101
|
+
it('should publish with the event name as the routing key', async ()=>{
|
|
102
|
+
const transport = new RabbitMqTransport({
|
|
103
|
+
exchange: 'ex'
|
|
104
|
+
});
|
|
105
|
+
await transport.connect();
|
|
106
|
+
const event = buildEvent();
|
|
107
|
+
await transport.publish(event);
|
|
108
|
+
expect(amqp.channel.publish).toHaveBeenCalledWith('ex', 'storage.folder.created', expect.any(Buffer), expect.objectContaining({
|
|
109
|
+
messageId: 'event-1',
|
|
110
|
+
contentType: 'application/json'
|
|
111
|
+
}));
|
|
112
|
+
});
|
|
113
|
+
it('should ignore publish before connect instead of throwing', async ()=>{
|
|
114
|
+
await expect(new RabbitMqTransport().publish(buildEvent())).resolves.toBeUndefined();
|
|
115
|
+
});
|
|
116
|
+
it('should translate the ** wildcard to the AMQP # wildcard when binding', async ()=>{
|
|
117
|
+
const transport = new RabbitMqTransport({
|
|
118
|
+
exchange: 'ex',
|
|
119
|
+
queue: 'q'
|
|
120
|
+
});
|
|
121
|
+
await transport.connect();
|
|
122
|
+
await transport.bind('storage.**');
|
|
123
|
+
expect(amqp.channel.bindQueue).toHaveBeenCalledWith('q', 'ex', 'storage.#');
|
|
124
|
+
});
|
|
125
|
+
it('should start consuming only once across several binds', async ()=>{
|
|
126
|
+
const transport = new RabbitMqTransport();
|
|
127
|
+
await transport.connect();
|
|
128
|
+
await transport.bind('storage.#');
|
|
129
|
+
await transport.bind('auth.#');
|
|
130
|
+
expect(amqp.channel.consume).toHaveBeenCalledTimes(1);
|
|
131
|
+
});
|
|
132
|
+
it('should hand a consumed message to its handlers and ack it', async ()=>{
|
|
133
|
+
const transport = new RabbitMqTransport();
|
|
134
|
+
const handler = jest.fn();
|
|
135
|
+
transport.onMessage(handler);
|
|
136
|
+
await transport.connect();
|
|
137
|
+
await transport.bind('storage.#');
|
|
138
|
+
const event = buildEvent();
|
|
139
|
+
const message = {
|
|
140
|
+
content: Buffer.from(JSON.stringify(event))
|
|
141
|
+
};
|
|
142
|
+
await amqp.channel.consume.mock.calls[0][1](message);
|
|
143
|
+
expect(handler).toHaveBeenCalledWith(event);
|
|
144
|
+
expect(amqp.channel.ack).toHaveBeenCalledWith(message);
|
|
145
|
+
});
|
|
146
|
+
it('should nack a message it cannot parse', async ()=>{
|
|
147
|
+
const transport = new RabbitMqTransport();
|
|
148
|
+
await transport.connect();
|
|
149
|
+
await transport.bind('storage.#');
|
|
150
|
+
const message = {
|
|
151
|
+
content: Buffer.from('not json')
|
|
152
|
+
};
|
|
153
|
+
await amqp.channel.consume.mock.calls[0][1](message);
|
|
154
|
+
expect(amqp.channel.nack).toHaveBeenCalledWith(message, false, false);
|
|
155
|
+
});
|
|
156
|
+
it('should close the channel and the connection', async ()=>{
|
|
157
|
+
const transport = new RabbitMqTransport();
|
|
158
|
+
await transport.connect();
|
|
159
|
+
await transport.close();
|
|
160
|
+
expect(amqp.channel.close).toHaveBeenCalled();
|
|
161
|
+
expect(amqp.connection.close).toHaveBeenCalled();
|
|
162
|
+
expect(transport.isReady()).toBe(false);
|
|
163
|
+
});
|
|
164
|
+
it('should reconnect when the channel dies while the connection is still up', async ()=>{
|
|
165
|
+
jest.useFakeTimers();
|
|
166
|
+
const transport = new RabbitMqTransport({
|
|
167
|
+
reconnectDelay: 10
|
|
168
|
+
});
|
|
169
|
+
await transport.connect();
|
|
170
|
+
listenerFor(amqp.channels[0], 'close')();
|
|
171
|
+
expect(transport.isReady()).toBe(false);
|
|
172
|
+
await jest.advanceTimersByTimeAsync(10);
|
|
173
|
+
expect(amqp.connect).toHaveBeenCalledTimes(2);
|
|
174
|
+
expect(transport.isReady()).toBe(true);
|
|
175
|
+
jest.useRealTimers();
|
|
176
|
+
});
|
|
177
|
+
it('should close the surviving connection rather than leak it on a channel failure', async ()=>{
|
|
178
|
+
jest.useFakeTimers();
|
|
179
|
+
const transport = new RabbitMqTransport({
|
|
180
|
+
reconnectDelay: 10
|
|
181
|
+
});
|
|
182
|
+
await transport.connect();
|
|
183
|
+
listenerFor(amqp.channels[0], 'close')();
|
|
184
|
+
await jest.advanceTimersByTimeAsync(10);
|
|
185
|
+
expect(amqp.connection.close).toHaveBeenCalledTimes(1);
|
|
186
|
+
jest.useRealTimers();
|
|
187
|
+
});
|
|
188
|
+
it('should schedule a single reconnect when the channel and the connection both close', async ()=>{
|
|
189
|
+
jest.useFakeTimers();
|
|
190
|
+
const transport = new RabbitMqTransport({
|
|
191
|
+
reconnectDelay: 10
|
|
192
|
+
});
|
|
193
|
+
await transport.connect();
|
|
194
|
+
listenerFor(amqp.channels[0], 'close')();
|
|
195
|
+
listenerFor(amqp.connection, 'close')();
|
|
196
|
+
await jest.advanceTimersByTimeAsync(10);
|
|
197
|
+
expect(amqp.connect).toHaveBeenCalledTimes(2);
|
|
198
|
+
jest.useRealTimers();
|
|
199
|
+
});
|
|
200
|
+
it('should re-bind every pattern onto the new channel after a reconnect', async ()=>{
|
|
201
|
+
jest.useFakeTimers();
|
|
202
|
+
const transport = new RabbitMqTransport({
|
|
203
|
+
exchange: 'ex',
|
|
204
|
+
queue: 'q',
|
|
205
|
+
reconnectDelay: 10
|
|
206
|
+
});
|
|
207
|
+
await transport.connect();
|
|
208
|
+
await transport.bind('storage.**');
|
|
209
|
+
listenerFor(amqp.channels[0], 'close')();
|
|
210
|
+
await jest.advanceTimersByTimeAsync(10);
|
|
211
|
+
expect(amqp.channels[1].bindQueue).toHaveBeenCalledWith('q', 'ex', 'storage.#');
|
|
212
|
+
expect(amqp.channels[1].consume).toHaveBeenCalledTimes(1);
|
|
213
|
+
jest.useRealTimers();
|
|
214
|
+
});
|
|
215
|
+
it('should ack an in-flight delivery on the channel it arrived on', async ()=>{
|
|
216
|
+
jest.useFakeTimers();
|
|
217
|
+
const transport = new RabbitMqTransport({
|
|
218
|
+
reconnectDelay: 10
|
|
219
|
+
});
|
|
220
|
+
await transport.connect();
|
|
221
|
+
await transport.bind('storage.#');
|
|
222
|
+
const deliver = amqp.channels[0].consume.mock.calls[0][1];
|
|
223
|
+
listenerFor(amqp.channels[0], 'close')();
|
|
224
|
+
await jest.advanceTimersByTimeAsync(10);
|
|
225
|
+
await deliver({
|
|
226
|
+
content: Buffer.from(JSON.stringify(buildEvent()))
|
|
227
|
+
});
|
|
228
|
+
expect(amqp.channels[0].ack).toHaveBeenCalled();
|
|
229
|
+
expect(amqp.channels[1].ack).not.toHaveBeenCalled();
|
|
230
|
+
jest.useRealTimers();
|
|
231
|
+
});
|
|
232
|
+
it('should let a later bind retry consuming after the broker rejects consume', async ()=>{
|
|
233
|
+
const transport = new RabbitMqTransport();
|
|
234
|
+
await transport.connect();
|
|
235
|
+
amqp.channel.consume.mockRejectedValueOnce(new Error('CHANNEL_ERROR'));
|
|
236
|
+
await expect(transport.bind('storage.#')).rejects.toThrow('CHANNEL_ERROR');
|
|
237
|
+
await transport.bind('auth.#');
|
|
238
|
+
expect(amqp.channel.consume).toHaveBeenCalledTimes(2);
|
|
239
|
+
});
|
|
240
|
+
it('should stop reconnecting once it has been closed', async ()=>{
|
|
241
|
+
jest.useFakeTimers();
|
|
242
|
+
const transport = new RabbitMqTransport({
|
|
243
|
+
reconnectDelay: 10
|
|
244
|
+
});
|
|
245
|
+
await transport.connect();
|
|
246
|
+
await transport.close();
|
|
247
|
+
listenerFor(amqp.channels[0], 'close')();
|
|
248
|
+
await jest.advanceTimersByTimeAsync(50);
|
|
249
|
+
expect(amqp.connect).toHaveBeenCalledTimes(1);
|
|
250
|
+
jest.useRealTimers();
|
|
251
|
+
});
|
|
252
|
+
});
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
function _define_property(obj, key, value) {
|
|
2
|
+
if (key in obj) {
|
|
3
|
+
Object.defineProperty(obj, key, {
|
|
4
|
+
value: value,
|
|
5
|
+
enumerable: true,
|
|
6
|
+
configurable: true,
|
|
7
|
+
writable: true
|
|
8
|
+
});
|
|
9
|
+
} else {
|
|
10
|
+
obj[key] = value;
|
|
11
|
+
}
|
|
12
|
+
return obj;
|
|
13
|
+
}
|
|
14
|
+
import { envConfig } from '@flusys/nestjs-core/config';
|
|
15
|
+
import { Logger } from '@nestjs/common';
|
|
16
|
+
import { matchEventPattern } from '../utils/event-pattern.util';
|
|
17
|
+
import { EventTransportRegistry } from './event-transports/event-transport.registry';
|
|
18
|
+
import { MemoryTransport } from './event-transports/memory-transport';
|
|
19
|
+
const DEFAULT_DEDUPE_SIZE = 5000;
|
|
20
|
+
/**
|
|
21
|
+
* Event counterpart of HybridCache: one wrapper, transport chosen by configuration.
|
|
22
|
+
*
|
|
23
|
+
* - `memory` in-process only, no broker required (default)
|
|
24
|
+
* - `rabbitmq` topic exchange, cross-service
|
|
25
|
+
* - `kafka` single topic, cross-service
|
|
26
|
+
* - `hybrid` both, with duplicate delivery suppressed by event id
|
|
27
|
+
*/ export class HybridEventBus {
|
|
28
|
+
getTransportLabel() {
|
|
29
|
+
return this.label;
|
|
30
|
+
}
|
|
31
|
+
getActiveTransports() {
|
|
32
|
+
return this.transports.map((transport)=>transport.name);
|
|
33
|
+
}
|
|
34
|
+
async connect() {
|
|
35
|
+
if (this.connected) return;
|
|
36
|
+
if (!this.connecting) {
|
|
37
|
+
this.connecting = this.buildTransports().catch((error)=>{
|
|
38
|
+
// A cached rejection would leave the bus dead for the process lifetime
|
|
39
|
+
this.connecting = undefined;
|
|
40
|
+
throw error;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
await this.connecting;
|
|
44
|
+
this.connected = true;
|
|
45
|
+
}
|
|
46
|
+
async publish(event) {
|
|
47
|
+
if (!await this.ensureConnected()) return;
|
|
48
|
+
await Promise.all(this.transports.map((transport)=>transport.publish(event).catch((error)=>{
|
|
49
|
+
this.logger.warn(`Publish failed on ${transport.name}: ${error.message}`);
|
|
50
|
+
})));
|
|
51
|
+
}
|
|
52
|
+
async subscribe(pattern, handler) {
|
|
53
|
+
this.subscriptions.push({
|
|
54
|
+
pattern,
|
|
55
|
+
handler: handler
|
|
56
|
+
});
|
|
57
|
+
if (!await this.ensureConnected()) return;
|
|
58
|
+
await Promise.all(this.transports.map((transport)=>transport.bind(pattern).catch((error)=>{
|
|
59
|
+
this.logger.warn(`Bind failed on ${transport.name}: ${error.message}`);
|
|
60
|
+
})));
|
|
61
|
+
}
|
|
62
|
+
async close() {
|
|
63
|
+
await Promise.allSettled(this.transports.map((transport)=>transport.close()));
|
|
64
|
+
this.transports.length = 0;
|
|
65
|
+
this.subscriptions.length = 0;
|
|
66
|
+
this.seenIds.clear();
|
|
67
|
+
this.seenOrder.length = 0;
|
|
68
|
+
this.memory = undefined;
|
|
69
|
+
this.connecting = undefined;
|
|
70
|
+
this.connected = false;
|
|
71
|
+
}
|
|
72
|
+
// ─── Private Helpers ────────────────────────────────────────────────────────
|
|
73
|
+
/**
|
|
74
|
+
* Connecting must never throw at the call site - a bus that cannot start is
|
|
75
|
+
* a degraded system, not a failed request. The next call retries.
|
|
76
|
+
*/ async ensureConnected() {
|
|
77
|
+
try {
|
|
78
|
+
await this.connect();
|
|
79
|
+
return true;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
82
|
+
this.logger.error(`Event bus is not available: ${message}`);
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
resolveLabelFromEnv() {
|
|
87
|
+
const value = envConfig.tryGetValue('USE_EVENT_LABEL', false) || 'memory';
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
async buildTransports() {
|
|
91
|
+
if (this.label === 'memory' || this.label === 'hybrid') {
|
|
92
|
+
this.memory = new MemoryTransport();
|
|
93
|
+
await this.memory.connect();
|
|
94
|
+
this.registerTransport(this.memory);
|
|
95
|
+
}
|
|
96
|
+
if (this.label !== 'memory') {
|
|
97
|
+
const broker = await this.createBrokerTransport(this.label);
|
|
98
|
+
if (broker) {
|
|
99
|
+
this.registerTransport(broker);
|
|
100
|
+
} else {
|
|
101
|
+
this.logger.error(`Event transport '${this.label}' was requested but is unavailable - delivering ` + `in-process only, so no event will reach another service. Check the broker URL ` + `and that its driver is installed.`);
|
|
102
|
+
if (!this.memory) {
|
|
103
|
+
this.memory = new MemoryTransport();
|
|
104
|
+
await this.memory.connect();
|
|
105
|
+
this.registerTransport(this.memory);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async createBrokerTransport(label) {
|
|
111
|
+
const name = label === 'hybrid' ? this.resolveHybridBrokerName() : label;
|
|
112
|
+
try {
|
|
113
|
+
await this.loadOptionalTransport(name);
|
|
114
|
+
const factory = EventTransportRegistry.get(name);
|
|
115
|
+
if (!factory) {
|
|
116
|
+
this.logger.error(`Event transport '${name}' is not registered. Available: ${EventTransportRegistry.getAll().join(', ')}`);
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
const transport = factory(this.getTransportConfig(name));
|
|
120
|
+
await transport.connect();
|
|
121
|
+
return transport;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
124
|
+
this.logger.error(`Failed to start the '${name}' event transport: ${message}`);
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
resolveHybridBrokerName() {
|
|
129
|
+
return envConfig.tryGetValue('EVENT_BROKER', false) || 'rabbitmq';
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Registers explicitly rather than relying on the transport file's own
|
|
133
|
+
* side effect, which a tree shaking bundler is free to drop.
|
|
134
|
+
*/ async loadOptionalTransport(name) {
|
|
135
|
+
if (EventTransportRegistry.has(name)) return;
|
|
136
|
+
if (name === 'rabbitmq') {
|
|
137
|
+
const { RabbitMqTransport } = await import('./event-transports/rabbitmq-transport.optional');
|
|
138
|
+
EventTransportRegistry.register('rabbitmq', (config)=>new RabbitMqTransport(config));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (name === 'kafka') {
|
|
142
|
+
const { KafkaTransport } = await import('./event-transports/kafka-transport.optional');
|
|
143
|
+
EventTransportRegistry.register('kafka', (config)=>new KafkaTransport(config));
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
getTransportConfig(name) {
|
|
147
|
+
if (name === 'rabbitmq') {
|
|
148
|
+
return {
|
|
149
|
+
url: envConfig.tryGetValue('RABBITMQ_URL', false) || undefined,
|
|
150
|
+
queue: this.options.serviceName ? `${this.options.serviceName}.events` : undefined,
|
|
151
|
+
...this.options.rabbitmq ?? {}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
if (name === 'kafka') {
|
|
155
|
+
return {
|
|
156
|
+
brokers: this.parseBrokers(envConfig.tryGetValue('KAFKA_BROKERS', false)),
|
|
157
|
+
clientId: this.options.serviceName,
|
|
158
|
+
groupId: this.options.serviceName ? `${this.options.serviceName}-events` : undefined,
|
|
159
|
+
...this.options.kafka ?? {}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
return {};
|
|
163
|
+
}
|
|
164
|
+
parseBrokers(value) {
|
|
165
|
+
if (!value) return undefined;
|
|
166
|
+
return value.split(',').map((broker)=>broker.trim()).filter(Boolean);
|
|
167
|
+
}
|
|
168
|
+
registerTransport(transport) {
|
|
169
|
+
transport.onMessage((event)=>this.dispatch(event));
|
|
170
|
+
this.transports.push(transport);
|
|
171
|
+
}
|
|
172
|
+
async dispatch(event) {
|
|
173
|
+
if (this.isDuplicate(event.id)) return;
|
|
174
|
+
const matched = this.subscriptions.filter((subscription)=>matchEventPattern(subscription.pattern, event.name));
|
|
175
|
+
await Promise.all(matched.map(async (subscription)=>{
|
|
176
|
+
try {
|
|
177
|
+
await subscription.handler(event);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
180
|
+
this.logger.error(`Handler for '${subscription.pattern}' failed: ${message}`);
|
|
181
|
+
}
|
|
182
|
+
}));
|
|
183
|
+
}
|
|
184
|
+
isDuplicate(eventId) {
|
|
185
|
+
if (!eventId) return false;
|
|
186
|
+
if (this.seenIds.has(eventId)) return true;
|
|
187
|
+
this.seenIds.add(eventId);
|
|
188
|
+
this.seenOrder.push(eventId);
|
|
189
|
+
if (this.seenOrder.length > this.dedupeSize) {
|
|
190
|
+
const evicted = this.seenOrder.shift();
|
|
191
|
+
if (evicted) this.seenIds.delete(evicted);
|
|
192
|
+
}
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
constructor(options = {}){
|
|
196
|
+
_define_property(this, "options", void 0);
|
|
197
|
+
_define_property(this, "logger", void 0);
|
|
198
|
+
_define_property(this, "subscriptions", void 0);
|
|
199
|
+
_define_property(this, "transports", void 0);
|
|
200
|
+
_define_property(this, "seenIds", void 0);
|
|
201
|
+
_define_property(this, "seenOrder", void 0);
|
|
202
|
+
_define_property(this, "label", void 0);
|
|
203
|
+
_define_property(this, "dedupeSize", void 0);
|
|
204
|
+
_define_property(this, "memory", void 0);
|
|
205
|
+
_define_property(this, "connecting", void 0);
|
|
206
|
+
_define_property(this, "connected", void 0);
|
|
207
|
+
this.options = options;
|
|
208
|
+
this.logger = new Logger(HybridEventBus.name);
|
|
209
|
+
this.subscriptions = [];
|
|
210
|
+
this.transports = [];
|
|
211
|
+
this.seenIds = new Set();
|
|
212
|
+
this.seenOrder = [];
|
|
213
|
+
this.connected = false;
|
|
214
|
+
this.label = options.transport ?? this.resolveLabelFromEnv();
|
|
215
|
+
this.dedupeSize = options.dedupeSize ?? DEFAULT_DEDUPE_SIZE;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { EventAction } from '../enums/event-action.enum';
|
|
2
|
+
import { EventTransportRegistry } from './event-transports/event-transport.registry';
|
|
3
|
+
import { MemoryTransport } from './event-transports/memory-transport';
|
|
4
|
+
import { HybridEventBus } from './hybrid-event-bus.class';
|
|
5
|
+
function buildEvent(name = 'storage.folder.created', id = 'event-1') {
|
|
6
|
+
return {
|
|
7
|
+
id,
|
|
8
|
+
name,
|
|
9
|
+
module: 'storage',
|
|
10
|
+
entity: 'folder',
|
|
11
|
+
action: EventAction.CREATED,
|
|
12
|
+
payload: {
|
|
13
|
+
ids: [
|
|
14
|
+
'1'
|
|
15
|
+
]
|
|
16
|
+
},
|
|
17
|
+
actor: {},
|
|
18
|
+
occurredAt: new Date().toISOString(),
|
|
19
|
+
version: 1
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function createFakeTransport(name) {
|
|
23
|
+
const handlers = [];
|
|
24
|
+
const transport = {
|
|
25
|
+
name,
|
|
26
|
+
connect: jest.fn().mockResolvedValue(undefined),
|
|
27
|
+
publish: jest.fn().mockResolvedValue(undefined),
|
|
28
|
+
bind: jest.fn().mockResolvedValue(undefined),
|
|
29
|
+
onMessage: (handler)=>handlers.push(handler),
|
|
30
|
+
close: jest.fn().mockResolvedValue(undefined),
|
|
31
|
+
isReady: ()=>true,
|
|
32
|
+
emit: (event)=>handlers.forEach((handler)=>handler(event))
|
|
33
|
+
};
|
|
34
|
+
return transport;
|
|
35
|
+
}
|
|
36
|
+
describe('HybridEventBus', ()=>{
|
|
37
|
+
const originalLabel = process.env.USE_EVENT_LABEL;
|
|
38
|
+
afterEach(async ()=>{
|
|
39
|
+
EventTransportRegistry.clear();
|
|
40
|
+
if (originalLabel === undefined) delete process.env.USE_EVENT_LABEL;
|
|
41
|
+
else process.env.USE_EVENT_LABEL = originalLabel;
|
|
42
|
+
});
|
|
43
|
+
it('should default to the memory transport', async ()=>{
|
|
44
|
+
const bus = new HybridEventBus();
|
|
45
|
+
await bus.connect();
|
|
46
|
+
expect(bus.getTransportLabel()).toBe('memory');
|
|
47
|
+
expect(bus.getActiveTransports()).toEqual([
|
|
48
|
+
'memory'
|
|
49
|
+
]);
|
|
50
|
+
await bus.close();
|
|
51
|
+
});
|
|
52
|
+
it('should read the transport label from USE_EVENT_LABEL when not given explicitly', ()=>{
|
|
53
|
+
process.env.USE_EVENT_LABEL = 'kafka';
|
|
54
|
+
expect(new HybridEventBus().getTransportLabel()).toBe('kafka');
|
|
55
|
+
});
|
|
56
|
+
it('should prefer an explicit transport option over the env value', ()=>{
|
|
57
|
+
process.env.USE_EVENT_LABEL = 'kafka';
|
|
58
|
+
expect(new HybridEventBus({
|
|
59
|
+
transport: 'memory'
|
|
60
|
+
}).getTransportLabel()).toBe('memory');
|
|
61
|
+
});
|
|
62
|
+
it('should deliver a published event to a matching subscriber', async ()=>{
|
|
63
|
+
const bus = new HybridEventBus({
|
|
64
|
+
transport: 'memory'
|
|
65
|
+
});
|
|
66
|
+
const handler = jest.fn();
|
|
67
|
+
await bus.subscribe('storage.*.created', handler);
|
|
68
|
+
await bus.publish(buildEvent());
|
|
69
|
+
expect(handler).toHaveBeenCalledWith(expect.objectContaining({
|
|
70
|
+
name: 'storage.folder.created'
|
|
71
|
+
}));
|
|
72
|
+
await bus.close();
|
|
73
|
+
});
|
|
74
|
+
it('should not deliver an event to a non matching subscriber', async ()=>{
|
|
75
|
+
const bus = new HybridEventBus({
|
|
76
|
+
transport: 'memory'
|
|
77
|
+
});
|
|
78
|
+
const handler = jest.fn();
|
|
79
|
+
await bus.subscribe('auth.#', handler);
|
|
80
|
+
await bus.publish(buildEvent());
|
|
81
|
+
expect(handler).not.toHaveBeenCalled();
|
|
82
|
+
await bus.close();
|
|
83
|
+
});
|
|
84
|
+
it('should keep publishing when a handler throws', async ()=>{
|
|
85
|
+
const bus = new HybridEventBus({
|
|
86
|
+
transport: 'memory'
|
|
87
|
+
});
|
|
88
|
+
const failing = jest.fn().mockRejectedValue(new Error('boom'));
|
|
89
|
+
const healthy = jest.fn();
|
|
90
|
+
await bus.subscribe('**', failing);
|
|
91
|
+
await bus.subscribe('**', healthy);
|
|
92
|
+
await expect(bus.publish(buildEvent())).resolves.toBeUndefined();
|
|
93
|
+
expect(healthy).toHaveBeenCalled();
|
|
94
|
+
await bus.close();
|
|
95
|
+
});
|
|
96
|
+
it('should publish to both layers in hybrid mode and deliver each event once', async ()=>{
|
|
97
|
+
const broker = createFakeTransport('rabbitmq');
|
|
98
|
+
EventTransportRegistry.register('rabbitmq', ()=>broker);
|
|
99
|
+
const bus = new HybridEventBus({
|
|
100
|
+
transport: 'hybrid'
|
|
101
|
+
});
|
|
102
|
+
const handler = jest.fn();
|
|
103
|
+
await bus.subscribe('**', handler);
|
|
104
|
+
expect(bus.getActiveTransports()).toEqual([
|
|
105
|
+
'memory',
|
|
106
|
+
'rabbitmq'
|
|
107
|
+
]);
|
|
108
|
+
const event = buildEvent();
|
|
109
|
+
await bus.publish(event);
|
|
110
|
+
// the broker loops the same event back to this process
|
|
111
|
+
broker.emit(event);
|
|
112
|
+
expect(broker.publish).toHaveBeenCalledWith(event);
|
|
113
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
114
|
+
await bus.close();
|
|
115
|
+
});
|
|
116
|
+
it('should fall back to memory when the broker cannot start', async ()=>{
|
|
117
|
+
EventTransportRegistry.register('kafka', ()=>{
|
|
118
|
+
throw new Error('kafkajs not installed');
|
|
119
|
+
});
|
|
120
|
+
const bus = new HybridEventBus({
|
|
121
|
+
transport: 'kafka'
|
|
122
|
+
});
|
|
123
|
+
await bus.connect();
|
|
124
|
+
expect(bus.getActiveTransports()).toEqual([
|
|
125
|
+
'memory'
|
|
126
|
+
]);
|
|
127
|
+
await bus.close();
|
|
128
|
+
});
|
|
129
|
+
it('should survive a transport that fails to publish', async ()=>{
|
|
130
|
+
const broker = createFakeTransport('rabbitmq');
|
|
131
|
+
broker.publish.mockRejectedValue(new Error('channel closed'));
|
|
132
|
+
EventTransportRegistry.register('rabbitmq', ()=>broker);
|
|
133
|
+
const bus = new HybridEventBus({
|
|
134
|
+
transport: 'rabbitmq'
|
|
135
|
+
});
|
|
136
|
+
await expect(bus.publish(buildEvent())).resolves.toBeUndefined();
|
|
137
|
+
await bus.close();
|
|
138
|
+
});
|
|
139
|
+
it('should not publish or throw while it has no working transport', async ()=>{
|
|
140
|
+
const connectSpy = jest.spyOn(MemoryTransport.prototype, 'connect').mockRejectedValueOnce(new Error('boot failure'));
|
|
141
|
+
const bus = new HybridEventBus({
|
|
142
|
+
transport: 'memory'
|
|
143
|
+
});
|
|
144
|
+
await expect(bus.publish(buildEvent())).resolves.toBeUndefined();
|
|
145
|
+
expect(bus.getActiveTransports()).toEqual([]);
|
|
146
|
+
connectSpy.mockRestore();
|
|
147
|
+
await bus.close();
|
|
148
|
+
});
|
|
149
|
+
it('should retry connecting after a failed attempt instead of staying dead', async ()=>{
|
|
150
|
+
const connectSpy = jest.spyOn(MemoryTransport.prototype, 'connect').mockRejectedValueOnce(new Error('boot failure'));
|
|
151
|
+
const bus = new HybridEventBus({
|
|
152
|
+
transport: 'memory'
|
|
153
|
+
});
|
|
154
|
+
const handler = jest.fn();
|
|
155
|
+
await bus.publish(buildEvent());
|
|
156
|
+
connectSpy.mockRestore();
|
|
157
|
+
await bus.subscribe('**', handler);
|
|
158
|
+
await bus.publish(buildEvent('storage.folder.created', 'event-2'));
|
|
159
|
+
expect(bus.getActiveTransports()).toEqual([
|
|
160
|
+
'memory'
|
|
161
|
+
]);
|
|
162
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
163
|
+
await bus.close();
|
|
164
|
+
});
|
|
165
|
+
it('should keep a subscription made while disconnected so a later connect binds it', async ()=>{
|
|
166
|
+
const connectSpy = jest.spyOn(MemoryTransport.prototype, 'connect').mockRejectedValueOnce(new Error('boot failure'));
|
|
167
|
+
const bus = new HybridEventBus({
|
|
168
|
+
transport: 'memory'
|
|
169
|
+
});
|
|
170
|
+
const handler = jest.fn();
|
|
171
|
+
await expect(bus.subscribe('**', handler)).resolves.toBeUndefined();
|
|
172
|
+
connectSpy.mockRestore();
|
|
173
|
+
await bus.publish(buildEvent());
|
|
174
|
+
expect(handler).toHaveBeenCalledTimes(1);
|
|
175
|
+
await bus.close();
|
|
176
|
+
});
|
|
177
|
+
it('should forget its transports after close', async ()=>{
|
|
178
|
+
const bus = new HybridEventBus({
|
|
179
|
+
transport: 'memory'
|
|
180
|
+
});
|
|
181
|
+
await bus.connect();
|
|
182
|
+
await bus.close();
|
|
183
|
+
expect(bus.getActiveTransports()).toEqual([]);
|
|
184
|
+
});
|
|
185
|
+
});
|
package/fesm/classes/index.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
export * from './api-controller.class';
|
|
2
2
|
export * from './api-service.class';
|
|
3
|
+
export * from './disabled-event-bus.class';
|
|
4
|
+
export * from './domain-event.publisher';
|
|
5
|
+
export * from './event-bus.registry';
|
|
6
|
+
export * from './event-transports';
|
|
3
7
|
export * from './handle-custome-db';
|
|
4
8
|
export * from './hybrid-cache.class';
|
|
9
|
+
export * from './hybrid-event-bus.class';
|
|
5
10
|
export * from './winston.logger.class';
|
|
6
11
|
// Re-export permission constants for convenience
|
|
7
12
|
export * from '../constants/permissions';
|
package/fesm/constants/index.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
// Metadata keys
|
|
2
2
|
export const IS_PUBLIC_KEY = 'isPublic';
|
|
3
3
|
export const PERMISSIONS_KEY = 'permissions';
|
|
4
|
+
export const DOMAIN_EVENT_HANDLER_KEY = 'domainEventHandler';
|
|
4
5
|
// Injection tokens
|
|
5
6
|
export const CACHE_INSTANCE = 'CACHE_INSTANCE';
|
|
6
7
|
export const PERMISSION_GUARD_CONFIG = 'PERMISSION_GUARD_CONFIG';
|
|
8
|
+
export const EVENT_BUS_INSTANCE = 'EVENT_BUS_INSTANCE';
|
|
9
|
+
export const EVENT_BUS_MODULE_OPTIONS = 'EVENT_BUS_MODULE_OPTIONS';
|
|
7
10
|
// Header names
|
|
8
11
|
export const IDEMPOTENCY_KEY_HEADER = 'x-idempotency-key';
|
|
9
12
|
export const REQUEST_ID_HEADER = 'x-request-id';
|
|
@@ -11,6 +14,10 @@ export const CLIENT_TYPE_HEADER = 'x-client-type';
|
|
|
11
14
|
// Cache key prefixes
|
|
12
15
|
export const PERMISSIONS_CACHE_PREFIX = 'my-permissions';
|
|
13
16
|
export const IDEMPOTENCY_CACHE_PREFIX = 'idempotency';
|
|
17
|
+
// Event bus defaults
|
|
18
|
+
export const DEFAULT_EVENT_EXCHANGE = 'flusys.events';
|
|
19
|
+
export const DEFAULT_EVENT_TOPIC = 'flusys.domain-events';
|
|
20
|
+
export const DEFAULT_EVENT_SERVICE_NAME = 'flusys';
|
|
14
21
|
// Permission codes
|
|
15
22
|
export * from './permissions';
|
|
16
23
|
// Message keys for localization
|