-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzeromq.service.ts
More file actions
59 lines (48 loc) · 1.83 KB
/
zeromq.service.ts
File metadata and controls
59 lines (48 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
import { createMessage, etag, Notify, Process } from '@letsflow/core/process';
import { Push, Reply, SocketOptions } from 'zeromq';
import { ConfigService } from '@/common/config/config.service';
import { NotifyProvider } from '../notify-provider.interface';
export type ZeromqOptions =
| ({ type: 'push'; address: string } & SocketOptions<Push>)
| ({ type: 'reply'; address: string } & SocketOptions<Reply>);
@Injectable()
export class ZeromqService implements NotifyProvider, OnModuleDestroy {
private sockets: Map<string, Push | Reply> = new Map();
constructor(
private readonly config: ConfigService,
@Inject('CREATE_ZEROMQ_SOCKET') private readonly createSocket: (settings: ZeromqOptions) => Push | Reply,
) {}
onModuleDestroy() {
this.sockets.forEach((socket) => {
socket.close();
});
}
getSocket(service: string): Push | Reply {
if (this.sockets.has(service)) {
return this.sockets.get(service);
}
const settings = this.config.get('services')[service] as ZeromqOptions | undefined;
if (!settings) {
throw new Error(`Service '${service}' not configured for ZeroMQ`);
}
const socket = this.createSocket(settings);
this.sockets[service] = socket;
return socket;
}
async notify(process: Process, args: Notify): Promise<any> {
const socket = this.getSocket(args.service);
const message =
args.message ?? {
process: process.id,
...createMessage(process, args.service),
etag: etag(process),
};
await socket.send(typeof message === 'string' ? message : JSON.stringify(message));
// Use `in` and not `instanceof` for compatibility with Jest mocks
if ('receive' in socket) {
const [response] = await socket.receive();
return response;
}
}
}