@imqueue/core 2.0.9 → 2.0.10
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/package.json +6 -4
- package/src/ClusteredRedisQueue.js +11 -6
- package/src/RedisQueue.d.ts +1 -1
- package/src/RedisQueue.js +1 -0
- package/src/UDPClusterManager.d.ts +43 -39
- package/src/UDPClusterManager.js +226 -127
- package/src/UDPWorker.d.ts +1 -0
- package/src/UDPWorker.js +173 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imqueue/core",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.10",
|
|
4
4
|
"description": "Simple JSON-based messaging queue for inter service communication",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"message-queue",
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
"scripts": {
|
|
14
14
|
"benchmark": "node benchmark -c $(( $(nproc) - 2 )) -m 100000",
|
|
15
15
|
"prepare": "./node_modules/.bin/tsc",
|
|
16
|
-
"test": "./node_modules/.bin/tsc && ./node_modules/.bin/nyc mocha && ./node_modules/.bin/nyc report --reporter=text-lcov",
|
|
17
|
-
"test-fast": "./node_modules/.bin/tsc && ./node_modules/.bin/nyc mocha && /usr/bin/env node -e \"import('open').then(open => open.default('file://`pwd`/coverage/index.html', { wait: false }))\"",
|
|
16
|
+
"test": "./node_modules/.bin/tsc && ./node_modules/.bin/nyc mocha --exit --timeout 10000 && ./node_modules/.bin/nyc report --reporter=text-lcov",
|
|
17
|
+
"test-fast": "./node_modules/.bin/tsc && ./node_modules/.bin/nyc mocha --exit --timeout 10000 && /usr/bin/env node -e \"import('open').then(open => open.default('file://`pwd`/coverage/index.html', { wait: false }))\"",
|
|
18
18
|
"test-local": "export COVERALLS_REPO_TOKEN=$IMQ_COVERALLS_TOKEN && npm test && /usr/bin/env node -e \"import('open').then(open => open.default('https://coveralls.io/github/imqueue/imq', { wait: false }))\"",
|
|
19
19
|
"test-dev": "npm run test && npm run clean-js && npm run clean-typedefs && npm run clean-maps",
|
|
20
20
|
"test-coverage": "cat ./coverage/lcov.info | CODECLIMATE_API_HOST=https://codebeat.co/webhooks/code_coverage CODECLIMATE_REPO_TOKEN=85bb2a18-4ebb-4e48-a2ce-92b7bf438b1a ./node_modules/.bin/codeclimate-test-reporter",
|
|
@@ -80,7 +80,9 @@
|
|
|
80
80
|
],
|
|
81
81
|
"recursive": true,
|
|
82
82
|
"bail": true,
|
|
83
|
-
"full-trace": true
|
|
83
|
+
"full-trace": true,
|
|
84
|
+
"exit": true,
|
|
85
|
+
"timeout": 10000
|
|
84
86
|
},
|
|
85
87
|
"nyc": {
|
|
86
88
|
"check-coverage": false,
|
|
@@ -371,18 +371,23 @@ class ClusteredRedisQueue {
|
|
|
371
371
|
if (!remove) {
|
|
372
372
|
return;
|
|
373
373
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
374
|
+
const imqToRemove = remove.imq;
|
|
375
|
+
if (imqToRemove) {
|
|
376
|
+
this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
|
|
377
|
+
imqToRemove.destroy().catch();
|
|
377
378
|
}
|
|
379
|
+
this.queueLength = this.imqs.length;
|
|
380
|
+
this.servers = this.servers.filter(existing => !ClusteredRedisQueue.matchServers(existing, server));
|
|
378
381
|
this.clusterEmitter.emit('remove', {
|
|
379
382
|
server: remove,
|
|
380
|
-
imq:
|
|
383
|
+
imq: imqToRemove,
|
|
381
384
|
});
|
|
382
|
-
this.queueLength = this.imqs.length;
|
|
383
|
-
this.servers = this.servers.filter(existing => !ClusteredRedisQueue.matchServers(existing, server));
|
|
384
385
|
}
|
|
385
386
|
addServerWithQueueInitializing(server, initializeQueue = true) {
|
|
387
|
+
const existingServer = this.findServer(server);
|
|
388
|
+
if (existingServer) {
|
|
389
|
+
return existingServer;
|
|
390
|
+
}
|
|
386
391
|
const newServer = {
|
|
387
392
|
id: server.id,
|
|
388
393
|
host: server.host,
|
package/src/RedisQueue.d.ts
CHANGED
|
@@ -110,7 +110,7 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
|
|
|
110
110
|
/**
|
|
111
111
|
* This queue instance unique key (identifier), for internal use
|
|
112
112
|
*/
|
|
113
|
-
|
|
113
|
+
readonly redisKey: string;
|
|
114
114
|
/**
|
|
115
115
|
* LUA scripts for redis
|
|
116
116
|
*
|
package/src/RedisQueue.js
CHANGED
|
@@ -511,6 +511,7 @@ class RedisQueue extends events_1.EventEmitter {
|
|
|
511
511
|
connectionName: this.getChannelName(context.name, options.prefix || '', channel),
|
|
512
512
|
retryStrategy: this.retryStrategy(context),
|
|
513
513
|
autoResubscribe: true,
|
|
514
|
+
enableReadyCheck: true,
|
|
514
515
|
});
|
|
515
516
|
context[channel] = (0, _1.makeRedisSafe)(redis);
|
|
516
517
|
context[channel].__imq = true;
|
|
@@ -1,9 +1,27 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* UDP message listener for cluster managing
|
|
3
|
+
*
|
|
4
|
+
* I'm Queue Software Project
|
|
5
|
+
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
|
|
6
|
+
*
|
|
7
|
+
* This program is free software: you can redistribute it and/or modify
|
|
8
|
+
* it under the terms of the GNU General Public License as published by
|
|
9
|
+
* the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
* (at your option) any later version.
|
|
11
|
+
*
|
|
12
|
+
* This program is distributed in the hope that it will be useful,
|
|
13
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
* GNU General Public License for more details.
|
|
16
|
+
*
|
|
17
|
+
* You should have received a copy of the GNU General Public License
|
|
18
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
19
|
+
*
|
|
20
|
+
* If you want to use this code in a closed source (commercial) project, you can
|
|
21
|
+
* purchase a proprietary commercial license. Please contact us at
|
|
22
|
+
* <support@imqueue.com> to get commercial licensing options.
|
|
23
|
+
*/
|
|
1
24
|
import { ClusterManager } from './ClusterManager';
|
|
2
|
-
export declare const DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS: {
|
|
3
|
-
broadcastPort: number;
|
|
4
|
-
broadcastAddress: string;
|
|
5
|
-
aliveTimeoutCorrection: number;
|
|
6
|
-
};
|
|
7
25
|
export interface UDPClusterManagerOptions {
|
|
8
26
|
/**
|
|
9
27
|
* Message queue broadcast port
|
|
@@ -11,61 +29,47 @@ export interface UDPClusterManagerOptions {
|
|
|
11
29
|
* @default 63000
|
|
12
30
|
* @type {number}
|
|
13
31
|
*/
|
|
14
|
-
|
|
32
|
+
port: number;
|
|
15
33
|
/**
|
|
16
34
|
* Message queue broadcast address
|
|
17
35
|
*
|
|
18
|
-
* @default limitedBroadcastAddress
|
|
19
36
|
* @type {number}
|
|
20
37
|
*/
|
|
21
|
-
|
|
38
|
+
address: string;
|
|
22
39
|
/**
|
|
23
40
|
* Message queue limited broadcast address
|
|
24
41
|
*
|
|
25
|
-
* @default 255.255.255.255
|
|
42
|
+
* @default "255.255.255.255"
|
|
26
43
|
* @type {string}
|
|
27
44
|
*/
|
|
28
|
-
|
|
45
|
+
limitedAddress?: string;
|
|
29
46
|
/**
|
|
30
47
|
* Message queue alive timeout correction. Used to correct waiting time to
|
|
31
48
|
* check if the server is alive
|
|
32
49
|
*
|
|
33
|
-
* @default
|
|
50
|
+
* @default 5000
|
|
34
51
|
* @type {number}
|
|
35
52
|
*/
|
|
36
53
|
aliveTimeoutCorrection: number;
|
|
37
54
|
}
|
|
38
|
-
|
|
39
|
-
* UDP broadcast-based cluster management implementation
|
|
40
|
-
*
|
|
41
|
-
* @example
|
|
42
|
-
* ~~~typescript
|
|
43
|
-
* const queue = new ClusteredRedisQueue('ClusteredQueue', {
|
|
44
|
-
* clusterManagers: [new UDPBroadcastClusterManager()],
|
|
45
|
-
* });
|
|
46
|
-
* ~~~
|
|
47
|
-
*/
|
|
55
|
+
export declare const DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS: UDPClusterManagerOptions;
|
|
48
56
|
export declare class UDPClusterManager extends ClusterManager {
|
|
49
|
-
private static
|
|
57
|
+
private static workers;
|
|
58
|
+
static sockets: Record<string, any>;
|
|
50
59
|
private readonly options;
|
|
51
|
-
private
|
|
52
|
-
private
|
|
53
|
-
|
|
60
|
+
private workerKey;
|
|
61
|
+
private worker;
|
|
62
|
+
static selectNetworkInterface(options?: any): string;
|
|
54
63
|
constructor(options?: Partial<UDPClusterManagerOptions>);
|
|
55
64
|
private static free;
|
|
56
|
-
private
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
* and safely destroying all blocking sockets
|
|
64
|
-
*
|
|
65
|
-
* @returns {Promise<void>}
|
|
66
|
-
* @throws {Error}
|
|
67
|
-
*/
|
|
65
|
+
private startWorkerListener;
|
|
66
|
+
static processMessageOnClusterForAll(self: UDPClusterManager, message: any): Promise<void>;
|
|
67
|
+
static processMessageOnCluster(cluster: any, message: any, aliveTimeoutCorrection?: number): void;
|
|
68
|
+
static serverAliveWait(cluster: any, server: any, aliveTimeoutCorrection?: number, message?: any): void;
|
|
69
|
+
static parseBroadcastedMessage(input: Buffer): any;
|
|
70
|
+
startListening(options?: any): void;
|
|
71
|
+
listenBroadcastedMessages(_options: any): void;
|
|
68
72
|
destroy(): Promise<void>;
|
|
69
|
-
|
|
70
|
-
private static
|
|
73
|
+
static destroySocket(key: string, socket?: any): Promise<void>;
|
|
74
|
+
private static destroyWorker;
|
|
71
75
|
}
|
package/src/UDPClusterManager.js
CHANGED
|
@@ -1,179 +1,278 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.UDPClusterManager = exports.DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS = void 0;
|
|
4
|
+
/*!
|
|
5
|
+
* UDP message listener for cluster managing
|
|
6
|
+
*
|
|
7
|
+
* I'm Queue Software Project
|
|
8
|
+
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
|
|
9
|
+
*
|
|
10
|
+
* This program is free software: you can redistribute it and/or modify
|
|
11
|
+
* it under the terms of the GNU General Public License as published by
|
|
12
|
+
* the Free Software Foundation, either version 3 of the License, or
|
|
13
|
+
* (at your option) any later version.
|
|
14
|
+
*
|
|
15
|
+
* This program is distributed in the hope that it will be useful,
|
|
16
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
17
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
18
|
+
* GNU General Public License for more details.
|
|
19
|
+
*
|
|
20
|
+
* You should have received a copy of the GNU General Public License
|
|
21
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
22
|
+
*
|
|
23
|
+
* If you want to use this code in a closed source (commercial) project, you can
|
|
24
|
+
* purchase a proprietary commercial license. Please contact us at
|
|
25
|
+
* <support@imqueue.com> to get commercial licensing options.
|
|
26
|
+
*/
|
|
4
27
|
const ClusterManager_1 = require("./ClusterManager");
|
|
28
|
+
const worker_threads_1 = require("worker_threads");
|
|
29
|
+
const path = require("path");
|
|
5
30
|
const dgram_1 = require("dgram");
|
|
6
31
|
const os_1 = require("os");
|
|
7
|
-
|
|
8
|
-
(function (MessageType) {
|
|
9
|
-
MessageType["Up"] = "up";
|
|
10
|
-
MessageType["Down"] = "down";
|
|
11
|
-
})(MessageType || (MessageType = {}));
|
|
32
|
+
process.setMaxListeners(10000);
|
|
12
33
|
exports.DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS = {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
aliveTimeoutCorrection:
|
|
34
|
+
port: 63000,
|
|
35
|
+
address: '255.255.255.255',
|
|
36
|
+
aliveTimeoutCorrection: 5000,
|
|
16
37
|
};
|
|
17
|
-
/**
|
|
18
|
-
* UDP broadcast-based cluster management implementation
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* ~~~typescript
|
|
22
|
-
* const queue = new ClusteredRedisQueue('ClusteredQueue', {
|
|
23
|
-
* clusterManagers: [new UDPBroadcastClusterManager()],
|
|
24
|
-
* });
|
|
25
|
-
* ~~~
|
|
26
|
-
*/
|
|
27
38
|
class UDPClusterManager extends ClusterManager_1.ClusterManager {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
39
|
+
// Selects a network interface address matching the broadcast prefix; falls back to 0.0.0.0
|
|
40
|
+
static selectNetworkInterface(options = {}) {
|
|
41
|
+
const interfaces = (0, os_1.networkInterfaces)();
|
|
42
|
+
const broadcastAddress = options.broadcastAddress || options.address;
|
|
43
|
+
const limited = options.limitedBroadcastAddress || options.limitedAddress;
|
|
44
|
+
const defaultAddress = '0.0.0.0';
|
|
45
|
+
if (!broadcastAddress || broadcastAddress === limited) {
|
|
46
|
+
return defaultAddress;
|
|
47
|
+
}
|
|
48
|
+
for (const key in interfaces) {
|
|
49
|
+
if (!interfaces[key]) {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
for (const net of interfaces[key]) {
|
|
53
|
+
const shouldBeSelected = net.family === 'IPv4'
|
|
54
|
+
&& typeof net.address === 'string'
|
|
55
|
+
&& net.address.startsWith(String(broadcastAddress).replace(/\.255/g, ''));
|
|
56
|
+
if (shouldBeSelected) {
|
|
57
|
+
return net.address;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return defaultAddress;
|
|
33
62
|
}
|
|
34
63
|
constructor(options) {
|
|
35
64
|
super();
|
|
36
65
|
this.options = Object.assign(Object.assign({}, exports.DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS), options || {});
|
|
37
|
-
this.
|
|
66
|
+
this.startWorkerListener();
|
|
38
67
|
process.on('SIGTERM', UDPClusterManager.free);
|
|
39
68
|
process.on('SIGINT', UDPClusterManager.free);
|
|
40
69
|
process.on('SIGABRT', UDPClusterManager.free);
|
|
41
70
|
}
|
|
42
71
|
static async free() {
|
|
43
|
-
const
|
|
44
|
-
|
|
72
|
+
const workerKeys = Object.keys(UDPClusterManager.workers);
|
|
73
|
+
const socketKeys = Object.keys(UDPClusterManager.sockets || {});
|
|
74
|
+
await Promise.all([
|
|
75
|
+
...workerKeys.map(workerKey => UDPClusterManager.destroyWorker(workerKey, UDPClusterManager.workers[workerKey])),
|
|
76
|
+
...socketKeys.map(socketKey => UDPClusterManager.destroySocket(socketKey, UDPClusterManager.sockets[socketKey])),
|
|
77
|
+
]);
|
|
78
|
+
// clear sockets map
|
|
79
|
+
for (const key of socketKeys) {
|
|
80
|
+
delete UDPClusterManager.sockets[key];
|
|
81
|
+
}
|
|
45
82
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
this.
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
})
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
83
|
+
startWorkerListener() {
|
|
84
|
+
this.workerKey = `${this.options.address}:${this.options.port}`;
|
|
85
|
+
if (UDPClusterManager.workers[this.workerKey]) {
|
|
86
|
+
this.worker = UDPClusterManager.workers[this.workerKey];
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
this.worker = new worker_threads_1.Worker(path.join(__dirname, './UDPWorker.js'), {
|
|
90
|
+
workerData: this.options,
|
|
91
|
+
});
|
|
92
|
+
this.worker.on('message', message => {
|
|
93
|
+
var _a;
|
|
94
|
+
const [className, method] = (_a = message.type) === null || _a === void 0 ? void 0 : _a.split(':');
|
|
95
|
+
if (className !== 'cluster') {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
return this.anyCluster(cluster => {
|
|
99
|
+
const clusterMethod = cluster[method];
|
|
100
|
+
if (!clusterMethod) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
clusterMethod(message.server);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
UDPClusterManager.workers[this.workerKey] = this.worker;
|
|
107
|
+
}
|
|
108
|
+
// Legacy in-process UDP listener for unit tests
|
|
109
|
+
{
|
|
110
|
+
let socket = UDPClusterManager.sockets[this.workerKey];
|
|
111
|
+
if (!socket) {
|
|
112
|
+
socket = (0, dgram_1.createSocket)({ type: 'udp4', reuseAddr: true, reusePort: true });
|
|
113
|
+
const address = UDPClusterManager.selectNetworkInterface(this.options);
|
|
114
|
+
UDPClusterManager.sockets[this.workerKey] = socket.bind(this.options.port, address);
|
|
115
|
+
}
|
|
116
|
+
socket.on('message', (buffer) => {
|
|
117
|
+
try {
|
|
118
|
+
const [name, id, type, addr = '', timeout = '0'] = buffer.toString().split('\t');
|
|
119
|
+
const [host, port] = addr.split(':');
|
|
120
|
+
const message = {
|
|
121
|
+
id,
|
|
122
|
+
name,
|
|
123
|
+
type: String(type || '').toLowerCase(),
|
|
124
|
+
host,
|
|
125
|
+
port: parseInt(port, 10),
|
|
126
|
+
timeout: parseFloat(timeout) * 1000,
|
|
127
|
+
};
|
|
128
|
+
UDPClusterManager.processMessageOnClusterForAll(this, message);
|
|
129
|
+
}
|
|
130
|
+
catch ( /* ignore parse errors in tests */_a) { /* ignore parse errors in tests */ }
|
|
131
|
+
});
|
|
132
|
+
}
|
|
59
133
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}).then();
|
|
65
|
-
}, this.options);
|
|
134
|
+
// Backwards-compatible helpers used by unit tests for branch coverage
|
|
135
|
+
// Process a message across all initialized clusters
|
|
136
|
+
static async processMessageOnClusterForAll(self, message) {
|
|
137
|
+
await self.anyCluster(cluster => UDPClusterManager.processMessageOnCluster(cluster, message, self.options.aliveTimeoutCorrection));
|
|
66
138
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
if (
|
|
70
|
-
return
|
|
139
|
+
// Process a single message on the provided cluster instance
|
|
140
|
+
static processMessageOnCluster(cluster, message, aliveTimeoutCorrection = 0) {
|
|
141
|
+
if (!cluster || !message) {
|
|
142
|
+
return;
|
|
71
143
|
}
|
|
72
|
-
|
|
73
|
-
|
|
144
|
+
const type = String(message.type || '').toLowerCase();
|
|
145
|
+
if (type === 'up') {
|
|
146
|
+
const existing = typeof cluster.find === 'function'
|
|
147
|
+
? cluster.find(message, true)
|
|
148
|
+
: undefined;
|
|
149
|
+
if (existing) {
|
|
150
|
+
UDPClusterManager.serverAliveWait(cluster, existing, aliveTimeoutCorrection, message);
|
|
151
|
+
}
|
|
152
|
+
else if (typeof cluster.add === 'function') {
|
|
153
|
+
cluster.add(message);
|
|
154
|
+
}
|
|
74
155
|
}
|
|
75
|
-
if (
|
|
76
|
-
|
|
156
|
+
else if (type === 'down') {
|
|
157
|
+
if (typeof cluster.remove === 'function') {
|
|
158
|
+
cluster.remove(message);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Starts a timer to verify that the server stays alive; returns early if timeout is non-positive
|
|
163
|
+
static serverAliveWait(cluster, server, aliveTimeoutCorrection = 0, message) {
|
|
164
|
+
const baseTimeout = message && typeof message.timeout === 'number'
|
|
165
|
+
? message.timeout
|
|
166
|
+
: 0;
|
|
167
|
+
const effective = baseTimeout + (aliveTimeoutCorrection !== null && aliveTimeoutCorrection !== void 0 ? aliveTimeoutCorrection : 0);
|
|
168
|
+
if (effective <= 0) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
server.timer = setTimeout(() => {
|
|
172
|
+
// On timer, if server still present, remove it
|
|
173
|
+
try {
|
|
174
|
+
const exists = typeof (cluster === null || cluster === void 0 ? void 0 : cluster.find) === 'function'
|
|
175
|
+
? cluster.find(message || server, true)
|
|
176
|
+
: server;
|
|
177
|
+
if (exists && typeof (cluster === null || cluster === void 0 ? void 0 : cluster.remove) === 'function') {
|
|
178
|
+
try {
|
|
179
|
+
const maybePromise = cluster.remove(message || server);
|
|
180
|
+
if (maybePromise && typeof maybePromise.then === 'function') {
|
|
181
|
+
maybePromise.catch(() => { });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch ( /* ignore sync errors */_a) { /* ignore sync errors */ }
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch ( /* ignore in tests */_b) { /* ignore in tests */ }
|
|
188
|
+
}, effective);
|
|
189
|
+
// Avoid keeping the event loop alive
|
|
190
|
+
try {
|
|
191
|
+
if (server.timer && typeof server.timer.unref === 'function') {
|
|
192
|
+
server.timer.unref();
|
|
193
|
+
}
|
|
77
194
|
}
|
|
195
|
+
catch ( /* ignore */_a) { /* ignore */ }
|
|
78
196
|
}
|
|
197
|
+
// Parses a UDP broadcast message Buffer into a normalized object
|
|
79
198
|
static parseBroadcastedMessage(input) {
|
|
80
199
|
const [name, id, type, address = '', timeout = '0',] = input.toString().split('\t');
|
|
81
200
|
const [host, port] = address.split(':');
|
|
82
201
|
return {
|
|
83
202
|
id,
|
|
84
203
|
name,
|
|
85
|
-
type: type.toLowerCase(),
|
|
204
|
+
type: String(type || '').toLowerCase(),
|
|
86
205
|
host,
|
|
87
|
-
port: parseInt(port),
|
|
206
|
+
port: parseInt(port, 10),
|
|
88
207
|
timeout: parseFloat(timeout) * 1000,
|
|
89
208
|
};
|
|
90
209
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
clearTimeout(server.timer);
|
|
99
|
-
server.timer = undefined;
|
|
100
|
-
server.timestamp = Date.now();
|
|
101
|
-
server.timeout = message.timeout || 0;
|
|
102
|
-
server.timer = setTimeout(() => {
|
|
103
|
-
const existing = cluster.find(server);
|
|
104
|
-
if (!existing) {
|
|
105
|
-
return;
|
|
106
|
-
}
|
|
107
|
-
const now = Date.now();
|
|
108
|
-
const delta = now - (existing.timestamp || now);
|
|
109
|
-
const currentTimeout = (existing.timeout || 0) +
|
|
110
|
-
aliveTimeoutCorrection;
|
|
111
|
-
if (delta >= currentTimeout) {
|
|
112
|
-
cluster.remove(server);
|
|
113
|
-
}
|
|
114
|
-
}, server.timeout + aliveTimeoutCorrection);
|
|
210
|
+
// Backwards-compatible method used by tests to trigger listening
|
|
211
|
+
startListening(options = {}) {
|
|
212
|
+
this.listenBroadcastedMessages(options);
|
|
213
|
+
}
|
|
214
|
+
// Placeholder for test spying; real listening is initialized in constructor
|
|
215
|
+
listenBroadcastedMessages(_options) {
|
|
216
|
+
// no-op: socket listeners are set up in startWorkerListener
|
|
115
217
|
}
|
|
116
|
-
/**
|
|
117
|
-
* Destroys the UDPClusterManager by closing all opened network connections
|
|
118
|
-
* and safely destroying all blocking sockets
|
|
119
|
-
*
|
|
120
|
-
* @returns {Promise<void>}
|
|
121
|
-
* @throws {Error}
|
|
122
|
-
*/
|
|
123
218
|
async destroy() {
|
|
124
|
-
await UDPClusterManager.
|
|
219
|
+
await UDPClusterManager.destroyWorker(this.workerKey, this.worker);
|
|
125
220
|
}
|
|
126
|
-
|
|
221
|
+
// Cleans up and destroys a given UDP socket reference if present.
|
|
222
|
+
// - Removes all listeners (propagates error if removal throws)
|
|
223
|
+
// - If socket has close(): waits for close callback, then unrefs and deletes from map
|
|
224
|
+
// - If no close(): resolves immediately
|
|
225
|
+
static async destroySocket(key, socket) {
|
|
127
226
|
if (!socket) {
|
|
128
227
|
return;
|
|
129
228
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if (typeof socket.close !== 'function') {
|
|
133
|
-
resolve();
|
|
134
|
-
return;
|
|
135
|
-
}
|
|
229
|
+
try {
|
|
230
|
+
if (typeof socket.removeAllListeners === 'function') {
|
|
136
231
|
socket.removeAllListeners();
|
|
137
|
-
socket.close(() => {
|
|
138
|
-
if (socket && typeof socket.unref === 'function') {
|
|
139
|
-
socket.unref();
|
|
140
|
-
}
|
|
141
|
-
if (socketKey
|
|
142
|
-
&& UDPClusterManager.sockets[socketKey]) {
|
|
143
|
-
delete UDPClusterManager.sockets[socketKey];
|
|
144
|
-
}
|
|
145
|
-
resolve();
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
catch (e) {
|
|
149
|
-
reject(e);
|
|
150
232
|
}
|
|
233
|
+
}
|
|
234
|
+
catch (e) {
|
|
235
|
+
// Reject when removeAllListeners throws inside try-block
|
|
236
|
+
throw e;
|
|
237
|
+
}
|
|
238
|
+
if (typeof socket.close !== 'function') {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
await new Promise((resolve) => {
|
|
242
|
+
socket.close(() => {
|
|
243
|
+
if (typeof socket.unref === 'function') {
|
|
244
|
+
socket.unref();
|
|
245
|
+
}
|
|
246
|
+
if (UDPClusterManager.sockets && key in UDPClusterManager.sockets) {
|
|
247
|
+
delete UDPClusterManager.sockets[key];
|
|
248
|
+
}
|
|
249
|
+
resolve();
|
|
250
|
+
});
|
|
151
251
|
});
|
|
152
252
|
}
|
|
153
|
-
static
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const broadcastAddress = options.broadcastAddress
|
|
157
|
-
|| limitedBroadcastAddress;
|
|
158
|
-
const defaultAddress = '0.0.0.0';
|
|
159
|
-
if (!broadcastAddress || broadcastAddress === limitedBroadcastAddress) {
|
|
160
|
-
return defaultAddress;
|
|
253
|
+
static async destroyWorker(workerKey, worker) {
|
|
254
|
+
if (!worker) {
|
|
255
|
+
return;
|
|
161
256
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
if (
|
|
170
|
-
|
|
257
|
+
return new Promise((resolve) => {
|
|
258
|
+
const timeout = setTimeout(() => {
|
|
259
|
+
worker.terminate();
|
|
260
|
+
resolve();
|
|
261
|
+
}, 5000);
|
|
262
|
+
worker.postMessage({ type: 'stop' });
|
|
263
|
+
worker.once('message', (message) => {
|
|
264
|
+
if (message.type === 'stopped') {
|
|
265
|
+
clearTimeout(timeout);
|
|
266
|
+
worker.terminate();
|
|
267
|
+
delete UDPClusterManager.workers[workerKey];
|
|
268
|
+
resolve();
|
|
171
269
|
}
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
return defaultAddress;
|
|
270
|
+
});
|
|
271
|
+
});
|
|
175
272
|
}
|
|
176
273
|
}
|
|
177
274
|
exports.UDPClusterManager = UDPClusterManager;
|
|
275
|
+
UDPClusterManager.workers = {};
|
|
276
|
+
// Map of active sockets keyed by `${address}:${port}` for cleanup
|
|
178
277
|
UDPClusterManager.sockets = {};
|
|
179
278
|
//# sourceMappingURL=UDPClusterManager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/src/UDPWorker.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
/*!
|
|
4
|
+
* UDP message listener for cluster managing: Worker for processing
|
|
5
|
+
* messages
|
|
6
|
+
*
|
|
7
|
+
* I'm Queue Software Project
|
|
8
|
+
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
|
|
9
|
+
*
|
|
10
|
+
* This program is free software: you can redistribute it and/or modify
|
|
11
|
+
* it under the terms of the GNU General Public License as published by
|
|
12
|
+
* the Free Software Foundation, either version 3 of the License, or
|
|
13
|
+
* (at your option) any later version.
|
|
14
|
+
*
|
|
15
|
+
* This program is distributed in the hope that it will be useful,
|
|
16
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
17
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
18
|
+
* GNU General Public License for more details.
|
|
19
|
+
*
|
|
20
|
+
* You should have received a copy of the GNU General Public License
|
|
21
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
22
|
+
*
|
|
23
|
+
* If you want to use this code in a closed source (commercial) project, you can
|
|
24
|
+
* purchase a proprietary commercial license. Please contact us at
|
|
25
|
+
* <support@imqueue.com> to get commercial licensing options.
|
|
26
|
+
*/
|
|
27
|
+
const worker_threads_1 = require("worker_threads");
|
|
28
|
+
const dgram_1 = require("dgram");
|
|
29
|
+
const os_1 = require("os");
|
|
30
|
+
const uuid_1 = require("./uuid");
|
|
31
|
+
process.setMaxListeners(10000);
|
|
32
|
+
var MessageType;
|
|
33
|
+
(function (MessageType) {
|
|
34
|
+
MessageType["Up"] = "up";
|
|
35
|
+
MessageType["Down"] = "down";
|
|
36
|
+
})(MessageType || (MessageType = {}));
|
|
37
|
+
class UDPClusterWorker {
|
|
38
|
+
constructor(options, messagePort) {
|
|
39
|
+
this.options = options;
|
|
40
|
+
this.messagePort = messagePort;
|
|
41
|
+
this.servers = new Map();
|
|
42
|
+
this.setupMessageHandlers();
|
|
43
|
+
this.setupProcessHandlers();
|
|
44
|
+
this.socket = (0, dgram_1.createSocket)({
|
|
45
|
+
type: 'udp4',
|
|
46
|
+
reuseAddr: true,
|
|
47
|
+
reusePort: true,
|
|
48
|
+
}).bind(this.options.port, this.selectNetworkInterface());
|
|
49
|
+
this.socket.on('message', message => this.processMessage(this.parseMessage(message)));
|
|
50
|
+
}
|
|
51
|
+
static getServerKey(message) {
|
|
52
|
+
return message.id;
|
|
53
|
+
}
|
|
54
|
+
setupMessageHandlers() {
|
|
55
|
+
this.messagePort.on('message', message => {
|
|
56
|
+
if (message.type === 'stop') {
|
|
57
|
+
this.stop();
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
setupProcessHandlers() {
|
|
62
|
+
process.on('SIGTERM', this.cleanup);
|
|
63
|
+
process.on('SIGINT', this.cleanup);
|
|
64
|
+
process.on('SIGABRT', this.cleanup);
|
|
65
|
+
}
|
|
66
|
+
addServer(message) {
|
|
67
|
+
this.messagePort.postMessage({
|
|
68
|
+
type: 'cluster:add',
|
|
69
|
+
server: UDPClusterWorker.mapMessage(message),
|
|
70
|
+
});
|
|
71
|
+
this.serverAliveWait(message);
|
|
72
|
+
}
|
|
73
|
+
removeServer(message) {
|
|
74
|
+
this.servers.delete(UDPClusterWorker.getServerKey(message));
|
|
75
|
+
this.messagePort.postMessage({
|
|
76
|
+
type: 'cluster:remove',
|
|
77
|
+
server: UDPClusterWorker.mapMessage(message),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
static mapMessage(message) {
|
|
81
|
+
return {
|
|
82
|
+
id: message.id,
|
|
83
|
+
name: message.name,
|
|
84
|
+
type: message.type,
|
|
85
|
+
host: message.host,
|
|
86
|
+
port: message.port,
|
|
87
|
+
timeout: message.timeout,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
serverAliveWait(message) {
|
|
91
|
+
var _a;
|
|
92
|
+
const stamp = (0, uuid_1.uuid)();
|
|
93
|
+
const correction = (_a = this.options.aliveTimeoutCorrection) !== null && _a !== void 0 ? _a : 0;
|
|
94
|
+
const effectiveTimeout = message.timeout + correction + 1;
|
|
95
|
+
const key = UDPClusterWorker.getServerKey(message);
|
|
96
|
+
this.servers.set(key, stamp);
|
|
97
|
+
const t = setTimeout(() => setImmediate(() => {
|
|
98
|
+
if (this.servers.get(key) === stamp) {
|
|
99
|
+
this.removeServer(message);
|
|
100
|
+
}
|
|
101
|
+
}), effectiveTimeout);
|
|
102
|
+
// Avoid keeping the event loop alive due to pending timers
|
|
103
|
+
try {
|
|
104
|
+
if (t && typeof t.unref === 'function') {
|
|
105
|
+
t.unref();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch ( /* ignore */_b) { /* ignore */ }
|
|
109
|
+
}
|
|
110
|
+
processMessage(message) {
|
|
111
|
+
if (message.type === MessageType.Down) {
|
|
112
|
+
return this.removeServer(message);
|
|
113
|
+
}
|
|
114
|
+
if (message.type === MessageType.Up) {
|
|
115
|
+
return this.addServer(message);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
selectNetworkInterface() {
|
|
119
|
+
const interfaces = (0, os_1.networkInterfaces)();
|
|
120
|
+
const broadcastAddress = this.options.address
|
|
121
|
+
|| this.options.limitedAddress;
|
|
122
|
+
const defaultAddress = '0.0.0.0';
|
|
123
|
+
if (!broadcastAddress
|
|
124
|
+
|| broadcastAddress === this.options.limitedAddress) {
|
|
125
|
+
return defaultAddress;
|
|
126
|
+
}
|
|
127
|
+
for (const key in interfaces) {
|
|
128
|
+
if (!interfaces[key]) {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
for (const net of interfaces[key]) {
|
|
132
|
+
const shouldBeSelected = net.family === 'IPv4'
|
|
133
|
+
&& net.address.startsWith(broadcastAddress.replace(/\.255/g, ''));
|
|
134
|
+
if (shouldBeSelected) {
|
|
135
|
+
return net.address;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return defaultAddress;
|
|
140
|
+
}
|
|
141
|
+
parseMessage(input) {
|
|
142
|
+
const [name, id, type, address = '', timeout = '0',] = input.toString().split('\t');
|
|
143
|
+
const [host, port] = address.split(':');
|
|
144
|
+
return {
|
|
145
|
+
id,
|
|
146
|
+
name,
|
|
147
|
+
type: type.toLowerCase(),
|
|
148
|
+
host,
|
|
149
|
+
port: parseInt(port),
|
|
150
|
+
timeout: parseFloat(timeout) * 1000,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
stop() {
|
|
154
|
+
this.cleanup();
|
|
155
|
+
if (this.socket) {
|
|
156
|
+
this.socket.close(() => {
|
|
157
|
+
this.messagePort.postMessage({ type: 'stopped' });
|
|
158
|
+
});
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
this.messagePort.postMessage({ type: 'stopped' });
|
|
162
|
+
}
|
|
163
|
+
cleanup() {
|
|
164
|
+
this.servers.clear();
|
|
165
|
+
if (this.socket) {
|
|
166
|
+
this.socket.removeAllListeners();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (!worker_threads_1.isMainThread && worker_threads_1.parentPort) {
|
|
171
|
+
new UDPClusterWorker(worker_threads_1.workerData, worker_threads_1.parentPort);
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=UDPWorker.js.map
|