forked from moleculerjs/moleculer-channels
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.js
315 lines (273 loc) · 7.96 KB
/
base.js
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
* @moleculer/channels
* Copyright (c) 2021 MoleculerJS (https://github.com/moleculerjs/channels)
* MIT Licensed
*/
"use strict";
const _ = require("lodash");
const semver = require("semver");
const { MoleculerError } = require("moleculer").Errors;
const { Serializers, METRIC } = require("moleculer");
const C = require("../constants");
/**
* @typedef {import("moleculer").ServiceBroker} ServiceBroker Moleculer Service Broker instance
* @typedef {import("moleculer").Service} Service Moleculer Service definition
* @typedef {import("moleculer").LoggerInstance} Logger Logger instance
* @typedef {import("moleculer").Serializer} Serializer Moleculer Serializer
* @typedef {import("../index").Channel} Channel Base channel definition
* @typedef {import("../index").DeadLetteringOptions} DeadLetteringOptions Dead-letter-queue options
*/
/**
* @typedef {Object} BaseDefaultOptions Base Adapter configuration
* @property {String?} prefix Adapter prefix
* @property {String} consumerName Name of the consumer
* @property {String} serializer Type of serializer to use in message exchange. Defaults to JSON
* @property {Number} maxRetries Maximum number of retries before sending the message to dead-letter-queue or drop
* @property {Number} maxInFlight Maximum number of messages that can be processed in parallel.
* @property {DeadLetteringOptions} deadLettering Dead-letter-queue options
*/
class BaseAdapter {
/**
* Constructor of adapter
* @param {Object?} opts
*/
constructor(opts) {
/** @type {BaseDefaultOptions} */
this.opts = _.defaultsDeep({}, opts, {
consumerName: null,
prefix: null,
serializer: "JSON",
maxRetries: 3,
maxInFlight: 1,
deadLettering: {
enabled: false,
queueName: "FAILED_MESSAGES"
}
});
/**
* Tracks the messages that are still being processed by different clients
* @type {Map<string, Array<string|number>>}
*/
this.activeMessages = new Map();
/** @type {Boolean} Flag indicating the adapter's connection status */
this.connected = false;
}
/**
* Initialize the adapter.
*
* @param {ServiceBroker} broker
* @param {Logger} logger
*/
init(broker, logger) {
this.broker = broker;
this.logger = logger;
this.Promise = broker.Promise;
if (!this.opts.consumerName) this.opts.consumerName = this.broker.nodeID;
if (this.opts.prefix == null) this.opts.prefix = broker.namespace;
this.logger.info("Channel consumer name:", this.opts.consumerName);
this.logger.info("Channel prefix:", this.opts.prefix);
// create an instance of serializer (default to JSON)
/** @type {Serializer} */
this.serializer = Serializers.resolve(this.opts.serializer);
this.serializer.init(this.broker);
this.logger.info("Channel serializer:", this.broker.getConstructorName(this.serializer));
this.registerAdapterMetrics(broker);
}
/**
* Register adapter related metrics
* @param {ServiceBroker} broker
*/
registerAdapterMetrics(broker) {
if (!broker.isMetricsEnabled()) return;
broker.metrics.register({
type: METRIC.TYPE_COUNTER,
name: C.METRIC_CHANNELS_MESSAGES_ERRORS_TOTAL,
labelNames: ["channel", "group"],
rate: true,
unit: "msg"
});
broker.metrics.register({
type: METRIC.TYPE_COUNTER,
name: C.METRIC_CHANNELS_MESSAGES_RETRIES_TOTAL,
labelNames: ["channel", "group"],
rate: true,
unit: "msg"
});
broker.metrics.register({
type: METRIC.TYPE_COUNTER,
name: C.METRIC_CHANNELS_MESSAGES_DEAD_LETTERING_TOTAL,
labelNames: ["channel", "group"],
rate: true,
unit: "msg"
});
}
/**
*
* @param {String} metricName
* @param {Channel} chan
*/
metricsIncrement(metricName, chan) {
if (!this.broker.isMetricsEnabled()) return;
this.broker.metrics.increment(metricName, {
channel: chan.name,
group: chan.group
});
}
/**
* Check the installed client library version.
* https://github.com/npm/node-semver#usage
*
* @param {String} library
* @param {String} requiredVersions
* @returns {Boolean}
*/
checkClientLibVersion(library, requiredVersions) {
const pkg = require(`${library}/package.json`);
const installedVersion = pkg.version;
if (semver.satisfies(installedVersion, requiredVersions)) {
return true;
} else {
this.logger.warn(
`The installed ${library} library is not supported officially. Proper functionality cannot be guaranteed. Supported versions:`,
requiredVersions
);
return false;
}
}
/**
* Init active messages list for tracking messages of a channel
* @param {string} channelID
* @param {Boolean?} toThrow Throw error if already exists
*/
initChannelActiveMessages(channelID, toThrow = true) {
if (this.activeMessages.has(channelID)) {
if (toThrow)
throw new MoleculerError(
`Already tracking active messages of channel ${channelID}`
);
return;
}
this.activeMessages.set(channelID, []);
}
/**
* Remove active messages list of a channel
* @param {string} channelID
*/
stopChannelActiveMessages(channelID) {
if (!this.activeMessages.has(channelID)) {
throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
}
if (this.activeMessages.get(channelID).length !== 0) {
throw new MoleculerError(
`Can't stop tracking active messages of channel ${channelID}. It still has ${
this.activeMessages.get(channelID).length
} messages being processed.`
);
}
this.activeMessages.delete(channelID);
}
/**
* Add IDs of the messages that are currently being processed
*
* @param {string} channelID Channel ID
* @param {Array<string|number>} IDs List of IDs
*/
addChannelActiveMessages(channelID, IDs) {
if (!this.activeMessages.has(channelID)) {
throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
}
this.activeMessages.get(channelID).push(...IDs);
}
/**
* Remove IDs of the messages that were already processed
*
* @param {string} channelID Channel ID
* @param {string[]|number[]} IDs List of IDs
*/
removeChannelActiveMessages(channelID, IDs) {
if (!this.activeMessages.has(channelID)) {
throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
}
const messageList = this.activeMessages.get(channelID);
IDs.forEach(id => {
const idx = messageList.indexOf(id);
if (idx != -1) {
messageList.splice(idx, 1);
}
});
}
/**
* Get the number of active messages of a channel
*
* @param {string} channelID Channel ID
*/
getNumberOfChannelActiveMessages(channelID) {
if (!this.activeMessages.has(channelID)) {
//throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
return 0;
}
return this.activeMessages.get(channelID).length;
}
/**
* Get the number of channels
*/
getNumberOfTrackedChannels() {
return this.activeMessages.size;
}
/**
* Given a topic name adds the prefix
*
* @param {String} topicName
* @returns {String} New topic name
*/
addPrefixTopic(topicName) {
if (this.opts.prefix != null && this.opts.prefix != "" && topicName) {
return `${this.opts.prefix}.${topicName}`;
}
return topicName;
}
/**
* Connect to the adapter.
*/
async connect() {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Disconnect from adapter
*/
async disconnect() {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Subscribe to a channel.
*
* @param {Channel} chan
* @param {Service} svc
*/
async subscribe(chan, svc) {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Unsubscribe from a channel.
*
* @param {Channel} chan
*/
async unsubscribe(chan) {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Publish a payload to a channel.
* @param {String} channelName
* @param {any} payload
* @param {Object?} opts
*/
async publish(channelName, payload, opts) {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
}
module.exports = BaseAdapter;