@rxdi/nats 0.7.240 → 0.7.241
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/{src/decorators/index.ts → dist/decorators/index.d.ts} +1 -1
- package/dist/decorators/index.js +20 -0
- package/dist/decorators/index.js.map +1 -0
- package/dist/decorators/nats-call.decorator.d.ts +7 -0
- package/dist/decorators/nats-call.decorator.js +32 -0
- package/dist/decorators/nats-call.decorator.js.map +1 -0
- package/dist/decorators/nats-emit.decorator.d.ts +6 -0
- package/dist/decorators/nats-emit.decorator.js +47 -0
- package/dist/decorators/nats-emit.decorator.js.map +1 -0
- package/dist/decorators/nats-listener.decorator.d.ts +5 -0
- package/dist/decorators/nats-listener.decorator.js +28 -0
- package/dist/decorators/nats-listener.decorator.js.map +1 -0
- package/{src/index.ts → dist/index.d.ts} +1 -2
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/{src/interfaces/index.ts → dist/interfaces/index.d.ts} +1 -1
- package/dist/interfaces/index.js +19 -0
- package/dist/interfaces/index.js.map +1 -0
- package/dist/interfaces/nats-logger.d.ts +20 -0
- package/dist/interfaces/nats-logger.js +37 -0
- package/dist/interfaces/nats-logger.js.map +1 -0
- package/dist/interfaces/nats-module.config.d.ts +54 -0
- package/dist/interfaces/nats-module.config.js +10 -0
- package/dist/interfaces/nats-module.config.js.map +1 -0
- package/dist/nats.module.d.ts +13 -0
- package/dist/nats.module.js +92 -0
- package/dist/nats.module.js.map +1 -0
- package/{src/services/index.ts → dist/services/index.d.ts} +1 -1
- package/dist/services/index.js +25 -0
- package/dist/services/index.js.map +1 -0
- package/dist/services/microservice-registry.service.d.ts +20 -0
- package/dist/services/microservice-registry.service.js +60 -0
- package/dist/services/microservice-registry.service.js.map +1 -0
- package/dist/services/nats-client.service.d.ts +27 -0
- package/dist/services/nats-client.service.js +188 -0
- package/dist/services/nats-client.service.js.map +1 -0
- package/dist/services/nats-listener.host.d.ts +30 -0
- package/dist/services/nats-listener.host.js +128 -0
- package/dist/services/nats-listener.host.js.map +1 -0
- package/dist/services/nats-logger.service.d.ts +11 -0
- package/dist/services/nats-logger.service.js +53 -0
- package/dist/services/nats-logger.service.js.map +1 -0
- package/dist/services/nats-pubsub.class.d.ts +36 -0
- package/dist/services/nats-pubsub.class.js +122 -0
- package/dist/services/nats-pubsub.class.js.map +1 -0
- package/dist/services/nats-pubsub.service.d.ts +19 -0
- package/dist/services/nats-pubsub.service.js +101 -0
- package/dist/services/nats-pubsub.service.js.map +1 -0
- package/dist/services/pubsub-async-iterator.d.ts +21 -0
- package/dist/services/pubsub-async-iterator.js +51 -0
- package/dist/services/pubsub-async-iterator.js.map +1 -0
- package/dist/services/service-discovery.service.d.ts +14 -0
- package/dist/services/service-discovery.service.js +70 -0
- package/dist/services/service-discovery.service.js.map +1 -0
- package/package.json +2 -2
- package/src/decorators/nats-call.decorator.ts +0 -42
- package/src/decorators/nats-emit.decorator.ts +0 -59
- package/src/decorators/nats-listener.decorator.ts +0 -37
- package/src/interfaces/nats-logger.ts +0 -41
- package/src/interfaces/nats-module.config.spec.ts +0 -210
- package/src/interfaces/nats-module.config.ts +0 -61
- package/src/nats-decorators.spec.ts +0 -96
- package/src/nats-logger.spec.ts +0 -171
- package/src/nats.module.ts +0 -86
- package/src/services/microservice-registry.service.ts +0 -56
- package/src/services/nats-client.service.ts +0 -187
- package/src/services/nats-listener.host.ts +0 -132
- package/src/services/nats-logger.service.ts +0 -46
- package/src/services/nats-pubsub.class.ts +0 -152
- package/src/services/nats-pubsub.service.ts +0 -95
- package/src/services/pubsub-async-iterator.spec.ts +0 -78
- package/src/services/pubsub-async-iterator.ts +0 -61
- package/src/services/service-discovery.service.ts +0 -57
- package/tsconfig.json +0 -26
- package/tslint.json +0 -6
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
import { Injectable, Inject, OnInit } from '@rxdi/core';
|
|
2
|
-
import { connect, NatsConnection, ConnectionOptions, Subscription } from 'nats';
|
|
3
|
-
import { NatsModuleConfiguration, NATS_MODULE_CONFIG, NATS_LOGGER } from '../interfaces';
|
|
4
|
-
import { NatsLoggerService } from './nats-logger.service';
|
|
5
|
-
|
|
6
|
-
export type RequestHandler = (data: any) => Promise<any>;
|
|
7
|
-
|
|
8
|
-
@Injectable()
|
|
9
|
-
export class NatsClientService implements OnInit {
|
|
10
|
-
private client: NatsConnection | null = null;
|
|
11
|
-
private subscriptions: Map<number, { sub: Subscription; handler: RequestHandler }> = new Map();
|
|
12
|
-
private subscriptionId = 0;
|
|
13
|
-
private isConnected = false;
|
|
14
|
-
private connectionPromise: Promise<void>;
|
|
15
|
-
private resolveConnection!: () => void;
|
|
16
|
-
|
|
17
|
-
constructor(
|
|
18
|
-
@Inject(NATS_MODULE_CONFIG) private config: NatsModuleConfiguration,
|
|
19
|
-
@Inject(NATS_LOGGER) private logger: NatsLoggerService
|
|
20
|
-
) {
|
|
21
|
-
this.connectionPromise = new Promise((resolve) => {
|
|
22
|
-
this.resolveConnection = resolve;
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async waitForConnection(): Promise<void> {
|
|
27
|
-
return this.connectionPromise;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
OnInit(): void {
|
|
31
|
-
this.connect().catch((error: unknown) => {
|
|
32
|
-
const err = error as Error;
|
|
33
|
-
this.logger.error(`[NatsClientService] Initial connection failed: ${err.message}`);
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
async connect(): Promise<void> {
|
|
38
|
-
if (this.isConnected) {
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
try {
|
|
43
|
-
const options: ConnectionOptions = {
|
|
44
|
-
name: this.config?.name || 'rxdi-nats-client',
|
|
45
|
-
maxReconnectAttempts: this.config?.maxReconnectAttempts ?? -1,
|
|
46
|
-
reconnect: true,
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
if (this.config?.user && this.config?.pass) {
|
|
50
|
-
options.user = this.config.user;
|
|
51
|
-
options.pass = this.config.pass;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
let servers = this.config?.servers;
|
|
55
|
-
if (!servers || servers.length === 0) {
|
|
56
|
-
servers = [`nats://${this.config?.host || 'localhost'}:${this.config?.port || 4222}`];
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
options.servers = servers;
|
|
60
|
-
this.client = await connect(options);
|
|
61
|
-
this.isConnected = true;
|
|
62
|
-
this.resolveConnection();
|
|
63
|
-
this.logger.info(`[NatsClientService] Connected to NATS!`);
|
|
64
|
-
} catch (error: unknown) {
|
|
65
|
-
const err = error as Error;
|
|
66
|
-
this.logger.error(`[NatsClientService] Connection failed: ${err.message}`);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
async publish(channel: string, data: any): Promise<void> {
|
|
71
|
-
if (!this.client) {
|
|
72
|
-
this.logger.warn('[NatsClientService] Client not connected');
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
const message = typeof data === 'string' ? data : JSON.stringify(data);
|
|
76
|
-
this.client.publish(channel, message);
|
|
77
|
-
this.logger.debug(`[NatsClientService] Published to ${channel}:`, data);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async subscribeRequestHandler(channel: string, handler: RequestHandler, queueGroup?: string): Promise<number> {
|
|
81
|
-
if (!this.client) {
|
|
82
|
-
this.logger.warn('[NatsClientService] Client not connected');
|
|
83
|
-
return -1;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
const sub = this.client.subscribe(channel, { queue: queueGroup });
|
|
87
|
-
const id = ++this.subscriptionId;
|
|
88
|
-
this.subscriptions.set(id, { sub, handler });
|
|
89
|
-
|
|
90
|
-
(async () => {
|
|
91
|
-
try {
|
|
92
|
-
for await (const msg of sub) {
|
|
93
|
-
try {
|
|
94
|
-
const data = msg.data ? JSON.parse(msg.data.toString()) : null;
|
|
95
|
-
|
|
96
|
-
const result = await handler(data);
|
|
97
|
-
|
|
98
|
-
if (msg.reply) {
|
|
99
|
-
this.client?.publish(msg.reply, JSON.stringify(result));
|
|
100
|
-
}
|
|
101
|
-
} catch (e) {
|
|
102
|
-
this.logger.error(`[NatsClientService] Request handler error on ${channel}:`, e);
|
|
103
|
-
if (msg.reply) {
|
|
104
|
-
this.client?.publish(msg.reply, JSON.stringify({ error: String(e) }));
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
} catch {
|
|
109
|
-
// Subscription closed
|
|
110
|
-
}
|
|
111
|
-
})();
|
|
112
|
-
|
|
113
|
-
this.logger.debug(`[NatsClientService] Subscribed request handler: ${channel}${queueGroup ? ` (queue: ${queueGroup})` : ''}`);
|
|
114
|
-
return id;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
async subscribe(channel: string, callback: (msg: any) => void, queueGroup?: string): Promise<number> {
|
|
118
|
-
if (!this.client) {
|
|
119
|
-
this.logger.warn('[NatsClientService] Client not connected');
|
|
120
|
-
return -1;
|
|
121
|
-
}
|
|
122
|
-
const sub = this.client.subscribe(channel, { queue: queueGroup });
|
|
123
|
-
const id = ++this.subscriptionId;
|
|
124
|
-
this.subscriptions.set(id, { sub, handler: async (data) => { callback(data); } });
|
|
125
|
-
|
|
126
|
-
(async () => {
|
|
127
|
-
try {
|
|
128
|
-
for await (const msg of sub) {
|
|
129
|
-
try {
|
|
130
|
-
const data = msg.data ? JSON.parse(msg.data.toString()) : null;
|
|
131
|
-
callback(data);
|
|
132
|
-
} catch {
|
|
133
|
-
callback(msg.data.toString());
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
} catch {
|
|
137
|
-
// Subscription closed
|
|
138
|
-
}
|
|
139
|
-
})();
|
|
140
|
-
|
|
141
|
-
this.logger.debug(`[NatsClientService] Subscribed: ${channel}${queueGroup ? ` (queue: ${queueGroup})` : ''}`);
|
|
142
|
-
return id;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
unsubscribe(subId: number): void {
|
|
146
|
-
const entry = this.subscriptions.get(subId);
|
|
147
|
-
if (entry) {
|
|
148
|
-
entry.sub.unsubscribe();
|
|
149
|
-
this.subscriptions.delete(subId);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
async request(channel: string, data: any, timeout = 30000): Promise<any> {
|
|
154
|
-
if (!this.client) {
|
|
155
|
-
throw new Error('NATS client is not connected');
|
|
156
|
-
}
|
|
157
|
-
this.logger.debug(`[NatsClientService] Sending request to ${channel}:`, data);
|
|
158
|
-
const message = typeof data === 'string' ? data : JSON.stringify(data);
|
|
159
|
-
const response = await this.client.request(channel, message, { timeout });
|
|
160
|
-
if (response.data) {
|
|
161
|
-
try {
|
|
162
|
-
const result = JSON.parse(response.data.toString());
|
|
163
|
-
this.logger.debug(`[NatsClientService] Request response from ${channel}:`, result);
|
|
164
|
-
return result;
|
|
165
|
-
} catch {
|
|
166
|
-
return response.data.toString();
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
return null;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
async close(): Promise<void> {
|
|
173
|
-
if (this.client) {
|
|
174
|
-
await this.client.close();
|
|
175
|
-
this.isConnected = false;
|
|
176
|
-
this.client = null;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
isReady(): boolean {
|
|
181
|
-
return this.isConnected && !!this.client;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
getClient(): NatsConnection | null {
|
|
185
|
-
return this.client;
|
|
186
|
-
}
|
|
187
|
-
}
|
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
import { Injectable, Inject, OnInit } from '@rxdi/core';
|
|
2
|
-
import { NatsClientService } from './nats-client.service';
|
|
3
|
-
import { NATS_LOGGER } from '../interfaces';
|
|
4
|
-
import { NatsLoggerService } from './nats-logger.service';
|
|
5
|
-
import { Container } from '@rxdi/core';
|
|
6
|
-
|
|
7
|
-
export interface CallEntry {
|
|
8
|
-
targetClass: Function;
|
|
9
|
-
methodName: string;
|
|
10
|
-
channel: string;
|
|
11
|
-
timeout: number;
|
|
12
|
-
queueGroup?: string;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export interface ListenerEntry {
|
|
16
|
-
targetClass: Function;
|
|
17
|
-
methodName: string;
|
|
18
|
-
channel: string;
|
|
19
|
-
queueGroup?: string;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
@Injectable()
|
|
23
|
-
export class NatsListenerHost implements OnInit {
|
|
24
|
-
private static callEntries: CallEntry[] = [];
|
|
25
|
-
private static listenerEntries: ListenerEntry[] = [];
|
|
26
|
-
private static initialized = false;
|
|
27
|
-
private static connectionReady = false;
|
|
28
|
-
|
|
29
|
-
constructor(
|
|
30
|
-
@Inject(NATS_LOGGER) private logger: NatsLoggerService
|
|
31
|
-
) {}
|
|
32
|
-
|
|
33
|
-
static registerCall(targetClass: Function, methodName: string, channel: string, timeout: number, queueGroup?: string): void {
|
|
34
|
-
NatsListenerHost.callEntries.push({ targetClass, methodName, channel, timeout, queueGroup });
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
static registerListener(targetClass: Function, methodName: string, channel: string, queueGroup?: string): void {
|
|
38
|
-
NatsListenerHost.listenerEntries.push({ targetClass, methodName, channel, queueGroup });
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
OnInit(): void {
|
|
42
|
-
this.logger.debug('[NatsListenerHost] Initializing...');
|
|
43
|
-
this.setupWithRetry();
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
private setupWithRetry(maxRetries = 30, retryDelayMs = 100): void {
|
|
47
|
-
let retries = 0;
|
|
48
|
-
|
|
49
|
-
const trySetup = () => {
|
|
50
|
-
try {
|
|
51
|
-
const natsClient = Container.get(NatsClientService);
|
|
52
|
-
|
|
53
|
-
if (!natsClient.isReady()) {
|
|
54
|
-
if (retries < maxRetries) {
|
|
55
|
-
retries++;
|
|
56
|
-
setTimeout(trySetup, retryDelayMs);
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
this.logger.error('[NatsListenerHost] Max retries reached, NATS client not ready');
|
|
60
|
-
return;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
if (!NatsListenerHost.connectionReady) {
|
|
64
|
-
NatsListenerHost.connectionReady = true;
|
|
65
|
-
this.setupAll(natsClient);
|
|
66
|
-
}
|
|
67
|
-
} catch (e) {
|
|
68
|
-
this.logger.error('[NatsListenerHost] Error:', e);
|
|
69
|
-
if (retries < maxRetries) {
|
|
70
|
-
retries++;
|
|
71
|
-
setTimeout(trySetup, retryDelayMs);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
trySetup();
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
private setupAll(natsClient: NatsClientService): void {
|
|
80
|
-
if (NatsListenerHost.initialized) {
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
this.logger.info('[NatsListenerHost] Setting up all handlers...');
|
|
85
|
-
this.setupCallHandlers(natsClient);
|
|
86
|
-
this.setupListenerHandlers(natsClient);
|
|
87
|
-
NatsListenerHost.initialized = true;
|
|
88
|
-
this.logger.info('[NatsListenerHost] All handlers subscribed');
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
private setupCallHandlers(natsClient: NatsClientService): void {
|
|
92
|
-
for (const entry of NatsListenerHost.callEntries) {
|
|
93
|
-
try {
|
|
94
|
-
const instance: any = Container.get(entry.targetClass as any);
|
|
95
|
-
this.logger.info(`[@NatsCall] Subscribing request handler: ${entry.channel} -> ${instance.constructor.name}.${entry.methodName}${entry.queueGroup ? ` (queue: ${entry.queueGroup})` : ''}`);
|
|
96
|
-
|
|
97
|
-
natsClient.subscribeRequestHandler(entry.channel, async (request: any) => {
|
|
98
|
-
try {
|
|
99
|
-
this.logger.debug(`[@NatsCall] Received request on ${entry.channel}:`, request);
|
|
100
|
-
const result = await instance[entry.methodName](request);
|
|
101
|
-
this.logger.debug(`[@NatsCall] Handler result for ${entry.channel}:`, result);
|
|
102
|
-
return result;
|
|
103
|
-
} catch (e) {
|
|
104
|
-
this.logger.error(`[@NatsCall] Error in handler ${entry.methodName}:`, e);
|
|
105
|
-
return { error: (e as Error).message };
|
|
106
|
-
}
|
|
107
|
-
}, entry.queueGroup);
|
|
108
|
-
} catch (e) {
|
|
109
|
-
this.logger.error(`[@NatsCall] Could not get instance of ${entry.targetClass.name}:`, e);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
private setupListenerHandlers(natsClient: NatsClientService): void {
|
|
115
|
-
for (const entry of NatsListenerHost.listenerEntries) {
|
|
116
|
-
try {
|
|
117
|
-
const instance: any = Container.get(entry.targetClass as any);
|
|
118
|
-
this.logger.info(`[@NatsListener] Subscribing: ${entry.channel} -> ${instance.constructor.name}.${entry.methodName}${entry.queueGroup ? ` (queue: ${entry.queueGroup})` : ''}`);
|
|
119
|
-
|
|
120
|
-
natsClient.subscribe(entry.channel, async (data: any) => {
|
|
121
|
-
try {
|
|
122
|
-
await instance[entry.methodName](data);
|
|
123
|
-
} catch (e) {
|
|
124
|
-
this.logger.error(`[@NatsListener] Error calling ${entry.methodName}:`, e);
|
|
125
|
-
}
|
|
126
|
-
}, entry.queueGroup);
|
|
127
|
-
} catch (e) {
|
|
128
|
-
this.logger.error(`[@NatsListener] Could not get instance of ${entry.targetClass.name}:`, e);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { Injectable } from '@rxdi/core';
|
|
2
|
-
import { NatsLogger, NatsLogLevel } from '../interfaces/nats-logger';
|
|
3
|
-
|
|
4
|
-
@Injectable()
|
|
5
|
-
export class NatsLoggerService {
|
|
6
|
-
private logger: NatsLogger;
|
|
7
|
-
private enabled: boolean;
|
|
8
|
-
|
|
9
|
-
constructor(enabled: boolean = false, logger?: NatsLogger) {
|
|
10
|
-
this.enabled = enabled;
|
|
11
|
-
this.logger = logger || {
|
|
12
|
-
debug: () => {},
|
|
13
|
-
info: () => {},
|
|
14
|
-
warn: () => {},
|
|
15
|
-
error: () => {},
|
|
16
|
-
};
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
setEnabled(enabled: boolean): void {
|
|
20
|
-
this.enabled = enabled;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
debug(message: string, ...args: any[]): void {
|
|
24
|
-
if (this.enabled) {
|
|
25
|
-
this.logger.debug(message, ...args);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
info(message: string, ...args: any[]): void {
|
|
30
|
-
if (this.enabled) {
|
|
31
|
-
this.logger.info(message, ...args);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
warn(message: string, ...args: any[]): void {
|
|
36
|
-
if (this.enabled) {
|
|
37
|
-
this.logger.warn(message, ...args);
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
error(message: string, ...args: any[]): void {
|
|
42
|
-
if (this.enabled) {
|
|
43
|
-
this.logger.error(message, ...args);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
import { NatsClientInterface, NatsPubSubInterface } from '../interfaces';
|
|
2
|
-
|
|
3
|
-
export class NatsPubSub implements NatsPubSubInterface {
|
|
4
|
-
private subscriptionMap = new Map<number, [string, (m: any) => Promise<void>]>();
|
|
5
|
-
private subsRefsMap = new Map<string, number[]>();
|
|
6
|
-
private currentSubscriptionId = 0;
|
|
7
|
-
private unsubscribeMap = new Map<string, () => void>();
|
|
8
|
-
private subscriptionIds: Map<string, number> = new Map();
|
|
9
|
-
private natsClient: NatsClientInterface;
|
|
10
|
-
|
|
11
|
-
constructor(natsClient: NatsClientInterface) {
|
|
12
|
-
this.natsClient = natsClient;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
async publish(trigger: string, payload: any): Promise<void> {
|
|
16
|
-
await this.natsClient.publish(trigger, payload);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
async subscribe<T>(
|
|
20
|
-
trigger: string,
|
|
21
|
-
onMessage: (m: T) => Promise<void>,
|
|
22
|
-
config?: any
|
|
23
|
-
): Promise<number> {
|
|
24
|
-
const id = this.currentSubscriptionId++;
|
|
25
|
-
|
|
26
|
-
this.subscriptionMap.set(id, [trigger, onMessage as (m: any) => Promise<void>]);
|
|
27
|
-
|
|
28
|
-
const refs = this.subsRefsMap.get(trigger);
|
|
29
|
-
if (refs?.length) {
|
|
30
|
-
this.subsRefsMap.set(trigger, [...refs, id]);
|
|
31
|
-
return id;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const subId = await this.natsClient.subscribe(trigger, async (msg: any) => {
|
|
35
|
-
const subscribers = this.subsRefsMap.get(trigger);
|
|
36
|
-
if (!subscribers?.length) return;
|
|
37
|
-
|
|
38
|
-
for (const sId of subscribers) {
|
|
39
|
-
const entry = this.subscriptionMap.get(sId);
|
|
40
|
-
if (!entry) continue;
|
|
41
|
-
const [, listener] = entry;
|
|
42
|
-
await listener(msg);
|
|
43
|
-
}
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
this.subscriptionIds.set(trigger, subId);
|
|
47
|
-
this.subsRefsMap.set(trigger, [id]);
|
|
48
|
-
|
|
49
|
-
return id;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
async unsubscribe(subId: number): Promise<void> {
|
|
53
|
-
const entry = this.subscriptionMap.get(subId);
|
|
54
|
-
const triggerName = entry?.[0];
|
|
55
|
-
|
|
56
|
-
if (!triggerName) {
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const refs = this.subsRefsMap.get(triggerName);
|
|
61
|
-
if (!refs) return;
|
|
62
|
-
|
|
63
|
-
if (refs.length === 1) {
|
|
64
|
-
const natsSubId = this.subscriptionIds.get(triggerName);
|
|
65
|
-
if (natsSubId !== undefined) {
|
|
66
|
-
this.natsClient.unsubscribe(natsSubId);
|
|
67
|
-
this.subscriptionIds.delete(triggerName);
|
|
68
|
-
}
|
|
69
|
-
this.unsubscribeMap.delete(triggerName);
|
|
70
|
-
this.subsRefsMap.delete(triggerName);
|
|
71
|
-
} else {
|
|
72
|
-
this.subsRefsMap.set(
|
|
73
|
-
triggerName,
|
|
74
|
-
refs.filter((id) => id !== subId)
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
this.subscriptionMap.delete(subId);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
asyncIterator<T>(triggers: string | string[]): AsyncIterator<T> {
|
|
82
|
-
return new NatsPubSubAsyncIterator<T>(this, triggers);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
asyncIterableIterator<T>(triggers: string | string[]): AsyncIterator<T> {
|
|
86
|
-
return new NatsPubSubAsyncIterator<T>(this, triggers);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export class NatsPubSubAsyncIterator<T> implements AsyncIterator<T> {
|
|
91
|
-
private subscriptionId: number | null = null;
|
|
92
|
-
private listeners: Array<(value: T) => void> = [];
|
|
93
|
-
private resolveReturn!: (value: { value: T; done: boolean }) => void;
|
|
94
|
-
private rejectPromise!: (reason: any) => void;
|
|
95
|
-
private returnPromise: Promise<{ value: T; done: boolean }>;
|
|
96
|
-
|
|
97
|
-
constructor(
|
|
98
|
-
private pubsub: NatsPubSubInterface,
|
|
99
|
-
private triggers: string | string[]
|
|
100
|
-
) {
|
|
101
|
-
this.returnPromise = new Promise<{ value: T; done: boolean }>((resolve, reject) => {
|
|
102
|
-
this.resolveReturn = resolve;
|
|
103
|
-
this.rejectPromise = reject;
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
async next(): Promise<{ value: T; done: boolean }> {
|
|
108
|
-
if (!this.subscriptionId) {
|
|
109
|
-
const trigger = Array.isArray(this.triggers) ? this.triggers[0] : this.triggers;
|
|
110
|
-
this.subscriptionId = await this.pubsub.subscribe(
|
|
111
|
-
trigger,
|
|
112
|
-
async (message: T) => {
|
|
113
|
-
for (const listener of this.listeners) {
|
|
114
|
-
listener(message);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
) as any;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
return new Promise<{ value: T; done: boolean }>((resolve) => {
|
|
121
|
-
const listener = (value: T) => {
|
|
122
|
-
this.listeners = this.listeners.filter((l) => l !== listener);
|
|
123
|
-
resolve({ value, done: false });
|
|
124
|
-
};
|
|
125
|
-
this.listeners.push(listener);
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
async return(): Promise<{ value: T; done: boolean }> {
|
|
130
|
-
if (this.subscriptionId) {
|
|
131
|
-
await this.pubsub.unsubscribe(this.subscriptionId);
|
|
132
|
-
this.subscriptionId = null;
|
|
133
|
-
}
|
|
134
|
-
return { value: undefined as any, done: true };
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
async throw?(error?: any): Promise<never> {
|
|
138
|
-
if (this.subscriptionId) {
|
|
139
|
-
await this.pubsub.unsubscribe(this.subscriptionId);
|
|
140
|
-
this.subscriptionId = null;
|
|
141
|
-
}
|
|
142
|
-
return Promise.reject(error);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
146
|
-
return this;
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
export function createNatsPubSub(natsClient: NatsClientInterface): NatsPubSub {
|
|
151
|
-
return new NatsPubSub(natsClient);
|
|
152
|
-
}
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import { Injectable, Inject, OnInit } from '@rxdi/core';
|
|
2
|
-
import { NatsClientService } from './nats-client.service';
|
|
3
|
-
import { NatsPubSubInterface, NATS_LOGGER } from '../interfaces';
|
|
4
|
-
import { NatsLoggerService } from './nats-logger.service';
|
|
5
|
-
import { PubSubAsyncIterator } from './pubsub-async-iterator';
|
|
6
|
-
|
|
7
|
-
@Injectable()
|
|
8
|
-
export class NatsPubSubService implements NatsPubSubInterface, OnInit {
|
|
9
|
-
private subscriptionMap = new Map<number, [string, (m: any) => Promise<void>]>();
|
|
10
|
-
private subsRefsMap = new Map<string, number[]>();
|
|
11
|
-
private currentSubscriptionId = 0;
|
|
12
|
-
private unsubscribeMap = new Map<string, () => void>();
|
|
13
|
-
|
|
14
|
-
constructor(
|
|
15
|
-
private natsClient: NatsClientService,
|
|
16
|
-
@Inject(NATS_LOGGER) private logger: NatsLoggerService
|
|
17
|
-
) {}
|
|
18
|
-
|
|
19
|
-
OnInit(): void {}
|
|
20
|
-
|
|
21
|
-
async publish(trigger: string, payload: any): Promise<void> {
|
|
22
|
-
if (!this.natsClient.isReady()) {
|
|
23
|
-
throw new Error('NATS client is not connected');
|
|
24
|
-
}
|
|
25
|
-
await this.natsClient.publish(trigger, payload);
|
|
26
|
-
this.logger.debug(`[NatsPubSubService] Published to ${trigger}:`, payload);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
async subscribe<T>(
|
|
30
|
-
trigger: string,
|
|
31
|
-
onMessage: (m: T) => Promise<void>
|
|
32
|
-
): Promise<number> {
|
|
33
|
-
if (!this.natsClient.isReady()) {
|
|
34
|
-
throw new Error('NATS client is not connected');
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const id = this.currentSubscriptionId++;
|
|
38
|
-
this.subscriptionMap.set(id, [trigger, onMessage as (m: any) => Promise<void>]);
|
|
39
|
-
|
|
40
|
-
const refs = this.subsRefsMap.get(trigger);
|
|
41
|
-
if (refs?.length) {
|
|
42
|
-
this.subsRefsMap.set(trigger, [...refs, id]);
|
|
43
|
-
return id;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
const subId = await this.natsClient.subscribe(trigger, async (msg: any) => {
|
|
47
|
-
const subscribers = this.subsRefsMap.get(trigger);
|
|
48
|
-
if (!subscribers?.length) return;
|
|
49
|
-
|
|
50
|
-
for (const sId of subscribers) {
|
|
51
|
-
const entry = this.subscriptionMap.get(sId);
|
|
52
|
-
if (!entry) continue;
|
|
53
|
-
const [, listener] = entry;
|
|
54
|
-
await listener(msg);
|
|
55
|
-
}
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
this.unsubscribeMap.set(trigger, () => this.natsClient.unsubscribe(subId));
|
|
59
|
-
this.subsRefsMap.set(trigger, [id]);
|
|
60
|
-
|
|
61
|
-
this.logger.debug(`[NatsPubSubService] Subscribed to ${trigger}`);
|
|
62
|
-
return id;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
async unsubscribe(subId: number): Promise<void> {
|
|
66
|
-
const entry = this.subscriptionMap.get(subId);
|
|
67
|
-
const triggerName = entry?.[0];
|
|
68
|
-
|
|
69
|
-
if (!triggerName) return;
|
|
70
|
-
|
|
71
|
-
const refs = this.subsRefsMap.get(triggerName);
|
|
72
|
-
if (!refs) return;
|
|
73
|
-
|
|
74
|
-
if (refs.length === 1) {
|
|
75
|
-
const unsubscribe = this.unsubscribeMap.get(triggerName);
|
|
76
|
-
if (typeof unsubscribe === 'function') {
|
|
77
|
-
unsubscribe();
|
|
78
|
-
}
|
|
79
|
-
this.unsubscribeMap.delete(triggerName);
|
|
80
|
-
this.subsRefsMap.delete(triggerName);
|
|
81
|
-
} else {
|
|
82
|
-
this.subsRefsMap.set(triggerName, refs.filter((id) => id !== subId));
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
this.subscriptionMap.delete(subId);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
asyncIterator<T>(triggers: string | string[]): AsyncIterator<T> {
|
|
89
|
-
return new PubSubAsyncIterator<T>(this, triggers);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
asyncIterableIterator<T>(triggers: string | string[]): AsyncIterator<T> {
|
|
93
|
-
return new PubSubAsyncIterator<T>(this, triggers);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import { PubSubAsyncIterator } from './pubsub-async-iterator';
|
|
2
|
-
import { NatsPubSubInterface } from '../interfaces';
|
|
3
|
-
|
|
4
|
-
describe('PubSubAsyncIterator', () => {
|
|
5
|
-
let mockPubSub: jest.Mocked<NatsPubSubInterface>;
|
|
6
|
-
|
|
7
|
-
beforeEach(() => {
|
|
8
|
-
mockPubSub = {
|
|
9
|
-
publish: jest.fn().mockResolvedValue(undefined),
|
|
10
|
-
subscribe: jest.fn().mockResolvedValue(1),
|
|
11
|
-
unsubscribe: jest.fn().mockResolvedValue(undefined),
|
|
12
|
-
asyncIterator: jest.fn(),
|
|
13
|
-
asyncIterableIterator: jest.fn(),
|
|
14
|
-
} as any;
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
describe('constructor', () => {
|
|
18
|
-
it('should create iterator with single trigger string', () => {
|
|
19
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, 'test.channel');
|
|
20
|
-
expect(iterator).toBeDefined();
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
it('should create iterator with array of triggers', () => {
|
|
24
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, ['channel1', 'channel2']);
|
|
25
|
-
expect(iterator).toBeDefined();
|
|
26
|
-
});
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
describe('next', () => {
|
|
30
|
-
it('should subscribe to trigger on first call', async () => {
|
|
31
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, 'test.channel');
|
|
32
|
-
iterator.next();
|
|
33
|
-
await Promise.resolve();
|
|
34
|
-
expect(mockPubSub.subscribe).toHaveBeenCalledWith('test.channel', expect.any(Function));
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
it('should use first trigger when array provided', async () => {
|
|
38
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, ['channel1', 'channel2']);
|
|
39
|
-
iterator.next();
|
|
40
|
-
await Promise.resolve();
|
|
41
|
-
expect(mockPubSub.subscribe).toHaveBeenCalledWith('channel1', expect.any(Function));
|
|
42
|
-
});
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
describe('return', () => {
|
|
46
|
-
it('should unsubscribe when return is called', async () => {
|
|
47
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, 'test.channel');
|
|
48
|
-
await iterator.return();
|
|
49
|
-
expect(mockPubSub.unsubscribe).not.toHaveBeenCalled();
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
it('should return done: true', async () => {
|
|
53
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, 'test.channel');
|
|
54
|
-
const result = await iterator.return();
|
|
55
|
-
expect(result).toEqual({ value: undefined, done: true });
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
it('should handle return when not subscribed', async () => {
|
|
59
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, 'test.channel');
|
|
60
|
-
const result = await iterator.return();
|
|
61
|
-
expect(result).toEqual({ value: undefined, done: true });
|
|
62
|
-
});
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
describe('throw', () => {
|
|
66
|
-
it('should reject with error', async () => {
|
|
67
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, 'test.channel');
|
|
68
|
-
await expect(iterator.throw!(new Error('test error'))).rejects.toThrow('test error');
|
|
69
|
-
});
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
describe('Symbol.asyncIterator', () => {
|
|
73
|
-
it('should return itself', () => {
|
|
74
|
-
const iterator = new PubSubAsyncIterator<string>(mockPubSub, 'test.channel');
|
|
75
|
-
expect(iterator[Symbol.asyncIterator]()).toBe(iterator);
|
|
76
|
-
});
|
|
77
|
-
});
|
|
78
|
-
});
|