forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-mqtt.ts
220 lines (192 loc) 路 6.24 KB
/
server-mqtt.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import { isUndefined } from '@nestjs/common/utils/shared.utils';
import { Observable } from 'rxjs';
import {
CONNECT_EVENT,
ERROR_EVENT,
MESSAGE_EVENT,
MQTT_DEFAULT_URL,
MQTT_SEPARATOR,
MQTT_WILDCARD_ALL,
MQTT_WILDCARD_SINGLE,
NO_MESSAGE_HANDLER,
} from '../constants';
import { MqttContext } from '../ctx-host/mqtt.context';
import { Transport } from '../enums';
import { MqttClient } from '../external/mqtt-client.interface';
import {
CustomTransportStrategy,
IncomingRequest,
MessageHandler,
PacketId,
ReadPacket,
} from '../interfaces';
import { MqttOptions } from '../interfaces/microservice-configuration.interface';
import { MqttRecord } from '../record-builders/mqtt.record-builder';
import { MqttRecordSerializer } from '../serializers/mqtt-record.serializer';
import { Server } from './server';
let mqttPackage: any = {};
export class ServerMqtt extends Server implements CustomTransportStrategy {
public readonly transportId = Transport.MQTT;
private readonly url: string;
private mqttClient: MqttClient;
constructor(private readonly options: MqttOptions['options']) {
super();
this.url = this.getOptionsProp(options, 'url') || MQTT_DEFAULT_URL;
mqttPackage = this.loadPackage('mqtt', ServerMqtt.name, () =>
require('mqtt'),
);
this.initializeSerializer(options);
this.initializeDeserializer(options);
}
public async listen(
callback: (err?: unknown, ...optionalParams: unknown[]) => void,
) {
try {
this.mqttClient = this.createMqttClient();
this.start(callback);
} catch (err) {
callback(err);
}
}
public start(
callback: (err?: unknown, ...optionalParams: unknown[]) => void,
) {
this.handleError(this.mqttClient);
this.bindEvents(this.mqttClient);
this.mqttClient.on(CONNECT_EVENT, () => callback());
}
public bindEvents(mqttClient: MqttClient) {
mqttClient.on(MESSAGE_EVENT, this.getMessageHandler(mqttClient).bind(this));
const registeredPatterns = [...this.messageHandlers.keys()];
registeredPatterns.forEach(pattern => {
const { isEventHandler } = this.messageHandlers.get(pattern);
mqttClient.subscribe(
isEventHandler ? pattern : this.getRequestPattern(pattern),
this.getOptionsProp(this.options, 'subscribeOptions'),
);
});
}
public close() {
this.mqttClient && this.mqttClient.end();
}
public createMqttClient(): MqttClient {
return mqttPackage.connect(this.url, this.options as MqttOptions);
}
public getMessageHandler(pub: MqttClient): Function {
return async (
channel: string,
buffer: Buffer,
originalPacket?: Record<string, any>,
) => this.handleMessage(channel, buffer, pub, originalPacket);
}
public async handleMessage(
channel: string,
buffer: Buffer,
pub: MqttClient,
originalPacket?: Record<string, any>,
): Promise<any> {
const rawPacket = this.parseMessage(buffer.toString());
const packet = await this.deserializer.deserialize(rawPacket, { channel });
const mqttContext = new MqttContext([channel, originalPacket]);
if (isUndefined((packet as IncomingRequest).id)) {
return this.handleEvent(channel, packet, mqttContext);
}
const publish = this.getPublisher(
pub,
channel,
(packet as IncomingRequest).id,
);
const handler = this.getHandlerByPattern(channel);
if (!handler) {
const status = 'error';
const noHandlerPacket = {
id: (packet as IncomingRequest).id,
status,
err: NO_MESSAGE_HANDLER,
};
return publish(noHandlerPacket);
}
const response$ = this.transformToObservable(
await handler(packet.data, mqttContext),
) as Observable<any>;
response$ && this.send(response$, publish);
}
public getPublisher(client: MqttClient, pattern: any, id: string): any {
return (response: any) => {
Object.assign(response, { id });
const outgoingResponse: Partial<MqttRecord> =
this.serializer.serialize(response);
const options = outgoingResponse.options;
delete outgoingResponse.options;
return client.publish(
this.getReplyPattern(pattern),
JSON.stringify(outgoingResponse),
options,
);
};
}
public parseMessage(content: any): ReadPacket & PacketId {
try {
return JSON.parse(content);
} catch (e) {
return content;
}
}
public matchMqttPattern(pattern: string, topic: string) {
const patternSegments = pattern.split(MQTT_SEPARATOR);
const topicSegments = topic.split(MQTT_SEPARATOR);
const patternSegmentsLength = patternSegments.length;
const topicSegmentsLength = topicSegments.length;
const lastIndex = patternSegmentsLength - 1;
for (let i = 0; i < patternSegmentsLength; i++) {
const currentPattern = patternSegments[i];
const patternChar = currentPattern[0];
const currentTopic = topicSegments[i];
if (!currentTopic && !currentPattern) {
continue;
}
if (!currentTopic && currentPattern !== MQTT_WILDCARD_ALL) {
return false;
}
if (patternChar === MQTT_WILDCARD_ALL) {
return i === lastIndex;
}
if (
patternChar !== MQTT_WILDCARD_SINGLE &&
currentPattern !== currentTopic
) {
return false;
}
}
return patternSegmentsLength === topicSegmentsLength;
}
public getHandlerByPattern(pattern: string): MessageHandler | null {
const route = this.getRouteFromPattern(pattern);
if (this.messageHandlers.has(route)) {
return this.messageHandlers.get(route) || null;
}
for (const [key, value] of this.messageHandlers) {
if (
!key.includes(MQTT_WILDCARD_SINGLE) && !key.includes(MQTT_WILDCARD_ALL)
) {
continue;
}
if (this.matchMqttPattern(key, route)) {
return value;
}
}
return null;
}
public getRequestPattern(pattern: string): string {
return pattern;
}
public getReplyPattern(pattern: string): string {
return `${pattern}/reply`;
}
public handleError(stream: any) {
stream.on(ERROR_EVENT, (err: any) => this.logger.error(err));
}
protected initializeSerializer(options: MqttOptions['options']) {
this.serializer = options?.serializer ?? new MqttRecordSerializer();
}
}