@imqueue/rpc 2.1.0 → 3.1.0
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/README.md +68 -0
- package/package.json +26 -61
- package/src/IMQCache.d.ts +10 -9
- package/src/IMQCache.js +16 -22
- package/src/IMQClient.d.ts +21 -16
- package/src/IMQClient.js +466 -270
- package/src/IMQDelay.d.ts +14 -0
- package/src/IMQDelay.js +26 -5
- package/src/IMQLock.d.ts +17 -15
- package/src/IMQLock.js +36 -36
- package/src/IMQMetadata.d.ts +8 -0
- package/src/IMQMetadata.js +8 -0
- package/src/IMQRPCDescription.d.ts +2 -2
- package/src/IMQRPCDescription.js +2 -2
- package/src/IMQRPCError.d.ts +7 -7
- package/src/IMQRPCError.js +7 -8
- package/src/IMQRPCOptions.d.ts +27 -3
- package/src/IMQRPCOptions.js +17 -3
- package/src/IMQRPCRequest.d.ts +1 -1
- package/src/IMQRPCResponse.d.ts +1 -1
- package/src/IMQRequestContext.js +1 -2
- package/src/IMQService.d.ts +3 -4
- package/src/IMQService.js +302 -220
- package/src/cache/ICache.d.ts +53 -0
- package/src/cache/RedisCache.d.ts +36 -31
- package/src/cache/RedisCache.js +104 -61
- package/src/decorators/cache.d.ts +12 -0
- package/src/decorators/cache.js +56 -41
- package/src/decorators/classType.d.ts +43 -0
- package/src/decorators/classType.js +83 -0
- package/src/decorators/expose.d.ts +5 -31
- package/src/decorators/expose.js +147 -129
- package/src/decorators/index.d.ts +2 -0
- package/src/decorators/index.js +4 -0
- package/src/decorators/indexed.d.ts +23 -0
- package/src/decorators/indexed.js +22 -13
- package/src/decorators/lock.d.ts +10 -11
- package/src/decorators/lock.js +63 -56
- package/src/decorators/logged.d.ts +11 -9
- package/src/decorators/logged.js +47 -40
- package/src/decorators/metadata.d.ts +24 -0
- package/src/decorators/metadata.js +45 -0
- package/src/decorators/property.d.ts +7 -57
- package/src/decorators/property.js +112 -83
- package/src/decorators/remote.d.ts +7 -7
- package/src/decorators/remote.js +19 -13
- package/src/helpers/fs.d.ts +13 -13
- package/src/helpers/fs.js +19 -19
- package/src/helpers/os-uuid.d.ts +2 -1
- package/src/helpers/os-uuid.js +86 -3
- package/src/helpers/pid.d.ts +19 -9
- package/src/helpers/pid.js +33 -33
- package/src/helpers/signature.d.ts +9 -7
- package/src/helpers/signature.js +80 -10
- package/src/index.d.ts +0 -1
- package/src/index.js +0 -1
- package/tsconfig.json +18 -14
- package/.github/workflows/build.yml +0 -28
- package/debug.d.ts +0 -1
package/src/IMQClient.js
CHANGED
|
@@ -1,13 +1,71 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
|
|
19
|
+
var useValue = arguments.length > 2;
|
|
20
|
+
for (var i = 0; i < initializers.length; i++) {
|
|
21
|
+
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
22
|
+
}
|
|
23
|
+
return useValue ? value : void 0;
|
|
7
24
|
};
|
|
8
|
-
var
|
|
9
|
-
if (
|
|
25
|
+
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
26
|
+
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
|
27
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
28
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
29
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
30
|
+
var _, done = false;
|
|
31
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
32
|
+
var context = {};
|
|
33
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
34
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
35
|
+
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
|
36
|
+
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
|
37
|
+
if (kind === "accessor") {
|
|
38
|
+
if (result === void 0) continue;
|
|
39
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
40
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
41
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
42
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
43
|
+
}
|
|
44
|
+
else if (_ = accept(result)) {
|
|
45
|
+
if (kind === "field") initializers.unshift(_);
|
|
46
|
+
else descriptor[key] = _;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
50
|
+
done = true;
|
|
10
51
|
};
|
|
52
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
53
|
+
var ownKeys = function(o) {
|
|
54
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
55
|
+
var ar = [];
|
|
56
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
57
|
+
return ar;
|
|
58
|
+
};
|
|
59
|
+
return ownKeys(o);
|
|
60
|
+
};
|
|
61
|
+
return function (mod) {
|
|
62
|
+
if (mod && mod.__esModule) return mod;
|
|
63
|
+
var result = {};
|
|
64
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
65
|
+
__setModuleDefault(result, mod);
|
|
66
|
+
return result;
|
|
67
|
+
};
|
|
68
|
+
})();
|
|
11
69
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
70
|
exports.IMQClient = void 0;
|
|
13
71
|
exports.imqCallResolver = imqCallResolver;
|
|
@@ -35,236 +93,323 @@ exports.imqCallRejector = imqCallRejector;
|
|
|
35
93
|
* purchase a proprietary commercial license. Please contact us at
|
|
36
94
|
* <support@imqueue.com> to get commercial licensing options.
|
|
37
95
|
*/
|
|
38
|
-
const core_1 = require("@imqueue/core");
|
|
96
|
+
const core_1 = __importStar(require("@imqueue/core"));
|
|
39
97
|
const _1 = require(".");
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
const
|
|
43
|
-
|
|
98
|
+
const helpers_1 = require("./helpers");
|
|
99
|
+
const node_events_1 = require("node:events");
|
|
100
|
+
const node_vm_1 = require("node:vm");
|
|
101
|
+
const node_child_process_1 = require("node:child_process");
|
|
102
|
+
const node_fs_1 = require("node:fs");
|
|
103
|
+
const node_os_1 = require("node:os");
|
|
104
|
+
const node_path_1 = require("node:path");
|
|
105
|
+
// Loaded via require (not a static import) so that consumers which type-check
|
|
106
|
+
// this source through a file: link do not need `resolveJsonModule` enabled.
|
|
44
107
|
const tsOptions = require('../tsconfig.json').compilerOptions;
|
|
45
108
|
const RX_SEMICOLON = /;+$/g;
|
|
46
109
|
/**
|
|
47
110
|
* Class IMQClient - base abstract class for service clients.
|
|
48
111
|
*/
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
constructor(options, serviceName, name) {
|
|
60
|
-
var _a;
|
|
61
|
-
super();
|
|
62
|
-
this.resolvers = {};
|
|
63
|
-
const baseName = name || this.constructor.name;
|
|
64
|
-
this.baseName = baseName;
|
|
65
|
-
if (this.constructor.name === 'IMQClient') {
|
|
66
|
-
throw new TypeError('IMQClient class is abstract and cannot ' +
|
|
67
|
-
'be instantiated directly!');
|
|
112
|
+
let IMQClient = (() => {
|
|
113
|
+
let _classSuper = node_events_1.EventEmitter;
|
|
114
|
+
let _instanceExtraInitializers = [];
|
|
115
|
+
let _describe_decorators;
|
|
116
|
+
return class IMQClient extends _classSuper {
|
|
117
|
+
static {
|
|
118
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
|
119
|
+
_describe_decorators = [(0, _1.remote)()];
|
|
120
|
+
__esDecorate(this, null, _describe_decorators, { kind: "method", name: "describe", static: false, private: false, access: { has: obj => "describe" in obj, get: obj => obj.describe }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
121
|
+
if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
68
122
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
123
|
+
options = __runInitializers(this, _instanceExtraInitializers);
|
|
124
|
+
id;
|
|
125
|
+
name;
|
|
126
|
+
hostName;
|
|
127
|
+
serviceName;
|
|
128
|
+
queueName;
|
|
129
|
+
baseName;
|
|
130
|
+
imq;
|
|
131
|
+
subscriptionImq;
|
|
132
|
+
static singleImq;
|
|
133
|
+
static singleImqRefs = 0;
|
|
134
|
+
static maxListenersBumped = false;
|
|
135
|
+
destroyed = false;
|
|
136
|
+
signalHandlers = [];
|
|
137
|
+
logger;
|
|
138
|
+
resolvers = {};
|
|
139
|
+
/**
|
|
140
|
+
* Class constructor
|
|
141
|
+
*
|
|
142
|
+
* @param {Partial<IMQClientOptions>} options
|
|
143
|
+
* @param {string} serviceName
|
|
144
|
+
* @param {string} name
|
|
145
|
+
*/
|
|
146
|
+
constructor(options, serviceName, name) {
|
|
147
|
+
super();
|
|
148
|
+
const baseName = name || this.constructor.name;
|
|
149
|
+
this.baseName = baseName;
|
|
150
|
+
if (this.constructor.name === 'IMQClient') {
|
|
151
|
+
throw new TypeError('IMQClient class is abstract and cannot ' +
|
|
152
|
+
'be instantiated directly!');
|
|
153
|
+
}
|
|
154
|
+
this.options = { ..._1.DEFAULT_IMQ_CLIENT_OPTIONS, ...options };
|
|
155
|
+
this.id = (0, helpers_1.pid)(baseName);
|
|
156
|
+
this.logger = this.options.logger || /* istanbul ignore next */ console;
|
|
157
|
+
this.hostName =
|
|
158
|
+
IMQClient.singleImq?.name || `${(0, helpers_1.osUuid)()}-${this.id}:client`;
|
|
159
|
+
this.name = `${baseName}-${this.hostName}`;
|
|
160
|
+
this.serviceName = serviceName || baseName.replace(/Client$/, '');
|
|
161
|
+
this.queueName = this.options.singleQueue ? this.hostName : this.name;
|
|
162
|
+
this.imq = this.createImq();
|
|
163
|
+
this.subscriptionImq = this.createSubscriptionImq();
|
|
164
|
+
// raise the process listener limit on first use (many clients may
|
|
165
|
+
// coexist, each registering its own signal handlers)
|
|
166
|
+
if (!IMQClient.maxListenersBumped) {
|
|
167
|
+
IMQClient.maxListenersBumped = true;
|
|
168
|
+
process.setMaxListeners(10000);
|
|
169
|
+
}
|
|
170
|
+
helpers_1.SIGNALS.forEach((signal) => {
|
|
171
|
+
const handler = () => {
|
|
172
|
+
this.destroy().catch(this.logger.error);
|
|
173
|
+
setTimeout(() => process.exit(0), core_1.IMQ_SHUTDOWN_TIMEOUT);
|
|
174
|
+
};
|
|
175
|
+
// tracked so destroy() can unregister them (see below)
|
|
176
|
+
this.signalHandlers.push([signal, handler]);
|
|
177
|
+
process.on(signal, handler);
|
|
178
|
+
});
|
|
88
179
|
}
|
|
89
|
-
|
|
90
|
-
|
|
180
|
+
createImq() {
|
|
181
|
+
if (!this.options.singleQueue) {
|
|
182
|
+
return core_1.default.create(this.queueName, this.options);
|
|
183
|
+
}
|
|
184
|
+
if (!IMQClient.singleImq) {
|
|
185
|
+
IMQClient.singleImq = core_1.default.create(this.queueName, this.options);
|
|
186
|
+
}
|
|
187
|
+
// the shared queue is reference-counted so that destroying one client
|
|
188
|
+
// does not tear the transport down under the others
|
|
189
|
+
IMQClient.singleImqRefs++;
|
|
190
|
+
return IMQClient.singleImq;
|
|
91
191
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
return this.
|
|
192
|
+
createSubscriptionImq() {
|
|
193
|
+
if (!this.options.singleQueue) {
|
|
194
|
+
return this.imq;
|
|
195
|
+
}
|
|
196
|
+
return core_1.default.create(this.name, this.options);
|
|
97
197
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
198
|
+
/**
|
|
199
|
+
* Sends call to remote service method
|
|
200
|
+
*
|
|
201
|
+
* @param {...any[]} args
|
|
202
|
+
* @template T
|
|
203
|
+
* @returns {Promise<T>}
|
|
204
|
+
*/
|
|
205
|
+
async remoteCall(...args) {
|
|
206
|
+
const logger = this.options.logger || console;
|
|
207
|
+
const method = args.pop();
|
|
208
|
+
const from = this.queueName;
|
|
209
|
+
const to = this.serviceName;
|
|
210
|
+
let delay = 0;
|
|
211
|
+
let metadata;
|
|
212
|
+
if (args[args.length - 1] instanceof _1.IMQDelay) {
|
|
213
|
+
delay = args.pop().ms;
|
|
214
|
+
if (!isFinite(delay) || isNaN(delay) || delay < 0) {
|
|
215
|
+
delay = 0;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (args[args.length - 1] instanceof _1.IMQMetadata) {
|
|
219
|
+
metadata = args.pop();
|
|
220
|
+
}
|
|
221
|
+
const request = {
|
|
222
|
+
from,
|
|
223
|
+
method,
|
|
224
|
+
args,
|
|
225
|
+
...(metadata ? { metadata } : {}),
|
|
226
|
+
};
|
|
227
|
+
if (typeof this.options.beforeCall === 'function') {
|
|
228
|
+
const beforeCall = this.options.beforeCall.bind(this);
|
|
229
|
+
try {
|
|
230
|
+
await beforeCall(request);
|
|
231
|
+
}
|
|
232
|
+
catch (err) {
|
|
233
|
+
logger.warn(_1.BEFORE_HOOK_ERROR, err);
|
|
234
|
+
}
|
|
121
235
|
}
|
|
236
|
+
const callTimeout = this.options.callTimeout;
|
|
237
|
+
return new Promise((resolve, reject) => {
|
|
238
|
+
let timer = null;
|
|
239
|
+
const clearTimer = () => {
|
|
240
|
+
if (timer) {
|
|
241
|
+
clearTimeout(timer);
|
|
242
|
+
timer = null;
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
const doResolve = (data) => {
|
|
246
|
+
clearTimer();
|
|
247
|
+
resolve(data);
|
|
248
|
+
};
|
|
249
|
+
const doReject = (err) => {
|
|
250
|
+
clearTimer();
|
|
251
|
+
reject(err);
|
|
252
|
+
};
|
|
253
|
+
void (async () => {
|
|
254
|
+
try {
|
|
255
|
+
const id = await this.imq.send(to, request, delay, doReject);
|
|
256
|
+
this.resolvers[id] = [
|
|
257
|
+
imqCallResolver(doResolve, request, this),
|
|
258
|
+
imqCallRejector(doReject, request, this),
|
|
259
|
+
];
|
|
260
|
+
if (callTimeout && callTimeout > 0) {
|
|
261
|
+
// reject and release the pending resolver if no
|
|
262
|
+
// response arrives in time; a requested delivery delay
|
|
263
|
+
// extends the budget accordingly
|
|
264
|
+
timer = setTimeout(() => {
|
|
265
|
+
delete this.resolvers[id];
|
|
266
|
+
doReject((0, _1.IMQError)('IMQ_RPC_CALL_TIMEOUT', `Call to ${to}.${method}() timed out after ${callTimeout} ms.`, new Error().stack, method, args));
|
|
267
|
+
}, callTimeout + delay);
|
|
268
|
+
timer.unref?.();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
catch (err) {
|
|
272
|
+
imqCallRejector(doReject, request, this)(err);
|
|
273
|
+
}
|
|
274
|
+
})();
|
|
275
|
+
});
|
|
122
276
|
}
|
|
123
|
-
|
|
124
|
-
|
|
277
|
+
/**
|
|
278
|
+
* Adds subscription to service event channel
|
|
279
|
+
*
|
|
280
|
+
* @param {(data: JsonObject) => any} handler
|
|
281
|
+
* @return {Promise<void>}
|
|
282
|
+
*/
|
|
283
|
+
async subscribe(handler) {
|
|
284
|
+
return this.subscriptionImq.subscribe(this.serviceName, handler);
|
|
125
285
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
286
|
+
/**
|
|
287
|
+
* Destroys subscription channel to service
|
|
288
|
+
*
|
|
289
|
+
* @return {Promise<void>}
|
|
290
|
+
*/
|
|
291
|
+
async unsubscribe() {
|
|
292
|
+
return this.subscriptionImq.unsubscribe();
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Broadcasts given payload to all other service clients subscribed.
|
|
296
|
+
* So this is like client-to-clients publishing.
|
|
297
|
+
*
|
|
298
|
+
* @param {JsonObject} payload
|
|
299
|
+
* @return {Promise<void>}
|
|
300
|
+
*/
|
|
301
|
+
async broadcast(payload) {
|
|
302
|
+
return this.imq.publish(payload, this.queueName);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Initializes client work
|
|
306
|
+
*
|
|
307
|
+
* @returns {Promise<void>}
|
|
308
|
+
*/
|
|
309
|
+
async start() {
|
|
310
|
+
this.imq.on('message', (message) => {
|
|
311
|
+
// the following condition below is hard to test with the
|
|
312
|
+
// current redis mock, BTW it was tested manually on real
|
|
313
|
+
// redis run
|
|
314
|
+
if (!this.resolvers[message.to]) {
|
|
315
|
+
// when there is no resolvers it means
|
|
316
|
+
// we have message in queue which was initiated
|
|
317
|
+
// by some process which is broken. So we provide an
|
|
318
|
+
// ability to handle enqueued messages via EventEmitter
|
|
319
|
+
// interface
|
|
320
|
+
this.emit(message.request.method, message);
|
|
321
|
+
}
|
|
322
|
+
const [resolve, reject] = this.resolvers[message.to] || [];
|
|
323
|
+
// make sure no memory leaking
|
|
324
|
+
delete this.resolvers[message.to];
|
|
325
|
+
if (message.error) {
|
|
326
|
+
return reject && reject(message.error, message);
|
|
327
|
+
}
|
|
328
|
+
resolve && resolve(message.data, message);
|
|
329
|
+
});
|
|
330
|
+
if (this.imq) {
|
|
331
|
+
await this.imq.start();
|
|
136
332
|
}
|
|
137
333
|
}
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
334
|
+
/**
|
|
335
|
+
* Stops client work
|
|
336
|
+
*
|
|
337
|
+
* @returns {Promise<void>}
|
|
338
|
+
*/
|
|
339
|
+
async stop() {
|
|
340
|
+
await this.imq.stop();
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Destroys client
|
|
344
|
+
*
|
|
345
|
+
* @returns {Promise<void>}
|
|
346
|
+
*/
|
|
347
|
+
async destroy() {
|
|
348
|
+
if (this.destroyed) {
|
|
349
|
+
return;
|
|
145
350
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
351
|
+
this.destroyed = true;
|
|
352
|
+
// unregister this instance's process signal handlers so destroyed
|
|
353
|
+
// clients do not leak process-level listeners
|
|
354
|
+
for (const [signal, handler] of this.signalHandlers) {
|
|
355
|
+
process.removeListener(signal, handler);
|
|
149
356
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
*/
|
|
159
|
-
async subscribe(handler) {
|
|
160
|
-
return this.subscriptionImq.subscribe(this.serviceName, handler);
|
|
161
|
-
}
|
|
162
|
-
// noinspection JSUnusedGlobalSymbols
|
|
163
|
-
/**
|
|
164
|
-
* Destroys subscription channel to service
|
|
165
|
-
*
|
|
166
|
-
* @return {Promise<void>}
|
|
167
|
-
*/
|
|
168
|
-
async unsubscribe() {
|
|
169
|
-
return this.subscriptionImq.unsubscribe();
|
|
170
|
-
}
|
|
171
|
-
// noinspection JSUnusedGlobalSymbols
|
|
172
|
-
/**
|
|
173
|
-
* Broadcasts given payload to all other service clients subscribed.
|
|
174
|
-
* So this is like client-to-clients publishing.
|
|
175
|
-
*
|
|
176
|
-
* @param {JsonObject} payload
|
|
177
|
-
* @return {Promise<void>}
|
|
178
|
-
*/
|
|
179
|
-
async broadcast(payload) {
|
|
180
|
-
return this.imq.publish(payload, this.queueName);
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* Initializes client work
|
|
184
|
-
*
|
|
185
|
-
* @returns {Promise<void>}
|
|
186
|
-
*/
|
|
187
|
-
async start() {
|
|
188
|
-
this.imq.on('message', (message) => {
|
|
189
|
-
// the following condition below is hard to test with the
|
|
190
|
-
// current redis mock, BTW it was tested manually on real
|
|
191
|
-
// redis run
|
|
192
|
-
// istanbul ignore if
|
|
193
|
-
if (!this.resolvers[message.to]) {
|
|
194
|
-
// when there is no resolvers it means
|
|
195
|
-
// we have message in queue which was initiated
|
|
196
|
-
// by some process which is broken. So we provide an
|
|
197
|
-
// ability to handle enqueued messages via EventEmitter
|
|
198
|
-
// interface
|
|
199
|
-
this.emit(message.request.method, message);
|
|
357
|
+
this.signalHandlers.length = 0;
|
|
358
|
+
await this.subscriptionImq.unsubscribe();
|
|
359
|
+
(0, helpers_1.forgetPid)(this.baseName, this.id, this.logger);
|
|
360
|
+
this.removeAllListeners();
|
|
361
|
+
// in singleQueue mode the subscription queue is a separate,
|
|
362
|
+
// per-client instance and must be torn down with the client
|
|
363
|
+
if (this.subscriptionImq !== this.imq) {
|
|
364
|
+
await this.subscriptionImq.destroy();
|
|
200
365
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
366
|
+
if (!this.options.singleQueue) {
|
|
367
|
+
await this.imq.destroy();
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
// shared queue: only the last client tears it down
|
|
371
|
+
if (--IMQClient.singleImqRefs <= 0) {
|
|
372
|
+
IMQClient.singleImqRefs = 0;
|
|
373
|
+
const singleImq = IMQClient.singleImq;
|
|
374
|
+
IMQClient.singleImq = undefined;
|
|
375
|
+
await singleImq?.destroy();
|
|
206
376
|
}
|
|
207
|
-
resolve && resolve(message.data, message);
|
|
208
|
-
});
|
|
209
|
-
if (this.imq) {
|
|
210
|
-
await this.imq.start();
|
|
211
377
|
}
|
|
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
|
-
async describe(delay) {
|
|
240
|
-
return await this.remoteCall(...arguments);
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Creates client for a service with the given name
|
|
244
|
-
*
|
|
245
|
-
* @param {string} name
|
|
246
|
-
* @param {Partial<IMQServiceOptions>} options
|
|
247
|
-
* @returns {IMQClient}
|
|
248
|
-
*/
|
|
249
|
-
static async create(name, options) {
|
|
250
|
-
const clientOptions = Object.assign(Object.assign({}, _1.DEFAULT_IMQ_CLIENT_OPTIONS), options);
|
|
251
|
-
return await generator(name, clientOptions);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
378
|
+
/**
|
|
379
|
+
* Returns service description metadata.
|
|
380
|
+
*
|
|
381
|
+
* @param {IMQDelay} [_delay] - optional delivery delay; forwarded to the
|
|
382
|
+
* service through `arguments` by the `@remote` decorator
|
|
383
|
+
* @returns {Promise<Description>}
|
|
384
|
+
*/
|
|
385
|
+
async describe(_delay) {
|
|
386
|
+
return await this.remoteCall(...arguments);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Creates client for a service with the given name
|
|
390
|
+
*
|
|
391
|
+
* @param {string} name
|
|
392
|
+
* @param {Partial<IMQServiceOptions>} options
|
|
393
|
+
* @returns {IMQClient}
|
|
394
|
+
*/
|
|
395
|
+
static async create(name, options) {
|
|
396
|
+
const clientOptions = {
|
|
397
|
+
..._1.DEFAULT_IMQ_CLIENT_OPTIONS,
|
|
398
|
+
...options,
|
|
399
|
+
};
|
|
400
|
+
return await generator(name, clientOptions);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
})();
|
|
254
404
|
exports.IMQClient = IMQClient;
|
|
255
|
-
__decorate([
|
|
256
|
-
(0, _1.remote)(),
|
|
257
|
-
__metadata("design:type", Function),
|
|
258
|
-
__metadata("design:paramtypes", [_1.IMQDelay]),
|
|
259
|
-
__metadata("design:returntype", Promise)
|
|
260
|
-
], IMQClient.prototype, "describe", null);
|
|
261
405
|
/**
|
|
262
|
-
* Builds
|
|
406
|
+
* Builds a call resolver that resolves the pending promise and then runs the
|
|
407
|
+
* optional after-call hook.
|
|
263
408
|
*
|
|
264
|
-
* @param {(
|
|
265
|
-
* @param {IMQRPCRequest} req
|
|
266
|
-
* @param {IMQClient} client -
|
|
267
|
-
* @return {(data: any, res: IMQRPCResponse) => void} - hook-
|
|
409
|
+
* @param {(data: any) => void} resolve - the underlying promise resolver
|
|
410
|
+
* @param {IMQRPCRequest} req - the originating request message
|
|
411
|
+
* @param {IMQClient} client - the client the call belongs to
|
|
412
|
+
* @return {(data: any, res: IMQRPCResponse) => void} - a hook-aware resolver
|
|
268
413
|
*/
|
|
269
414
|
function imqCallResolver(resolve, req, client) {
|
|
270
415
|
return async (data, res) => {
|
|
@@ -282,12 +427,13 @@ function imqCallResolver(resolve, req, client) {
|
|
|
282
427
|
};
|
|
283
428
|
}
|
|
284
429
|
/**
|
|
285
|
-
* Builds
|
|
430
|
+
* Builds a call rejector that rejects the pending promise and then runs the
|
|
431
|
+
* optional after-call hook.
|
|
286
432
|
*
|
|
287
|
-
* @param {(err: any) => void} reject -
|
|
288
|
-
* @param {IMQRPCRequest} req -
|
|
289
|
-
* @param {IMQClient} client -
|
|
290
|
-
* @return {(err: any) => void} - hook-
|
|
433
|
+
* @param {(err: any) => void} reject - the underlying promise rejector
|
|
434
|
+
* @param {IMQRPCRequest} req - the originating request message
|
|
435
|
+
* @param {IMQClient} client - the client the call belongs to
|
|
436
|
+
* @return {(err: any, res?: IMQRPCResponse) => void} - a hook-aware rejector
|
|
291
437
|
*/
|
|
292
438
|
function imqCallRejector(reject, req, client) {
|
|
293
439
|
return async (err, res) => {
|
|
@@ -306,7 +452,6 @@ function imqCallRejector(reject, req, client) {
|
|
|
306
452
|
}
|
|
307
453
|
/**
|
|
308
454
|
* Class GeneratorClient - generator helper class implementation
|
|
309
|
-
* @access private
|
|
310
455
|
*/
|
|
311
456
|
class GeneratorClient extends IMQClient {
|
|
312
457
|
}
|
|
@@ -314,32 +459,31 @@ class GeneratorClient extends IMQClient {
|
|
|
314
459
|
* Fetches and returns service description using the timeout (to handle
|
|
315
460
|
* situations when the service is not started)
|
|
316
461
|
*
|
|
317
|
-
* @access private
|
|
318
462
|
* @param {string} name
|
|
319
463
|
* @param {IMQClientOptions} options
|
|
320
464
|
* @returns {Promise<Description>}
|
|
321
465
|
*/
|
|
322
466
|
async function getDescription(name, options) {
|
|
323
|
-
return new Promise(
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
467
|
+
return new Promise((resolve, reject) => {
|
|
468
|
+
void (async () => {
|
|
469
|
+
const client = new GeneratorClient(options, name, `${name}Client`);
|
|
470
|
+
await client.start();
|
|
471
|
+
const timeout = setTimeout(async () => {
|
|
472
|
+
await client.destroy();
|
|
473
|
+
timeout && clearTimeout(timeout);
|
|
474
|
+
reject(new EvalError('Generate client error: service remote ' +
|
|
475
|
+
`call timed-out! Is service "${name}" running?`));
|
|
476
|
+
}, options.timeout);
|
|
477
|
+
const description = await client.describe();
|
|
328
478
|
timeout && clearTimeout(timeout);
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
}
|
|
332
|
-
const description = await client.describe();
|
|
333
|
-
timeout && clearTimeout(timeout);
|
|
334
|
-
await client.destroy();
|
|
335
|
-
resolve(description);
|
|
479
|
+
await client.destroy();
|
|
480
|
+
resolve(description);
|
|
481
|
+
})();
|
|
336
482
|
});
|
|
337
483
|
}
|
|
338
|
-
// codebeat:disable[LOC,ABC]
|
|
339
484
|
/**
|
|
340
485
|
* Client generator helper function
|
|
341
486
|
*
|
|
342
|
-
* @access private
|
|
343
487
|
* @param {string} name
|
|
344
488
|
* @param {IMQClientOptions} options
|
|
345
489
|
* @returns {Promise<string>}
|
|
@@ -348,8 +492,7 @@ async function generator(name, options) {
|
|
|
348
492
|
const description = await getDescription(name, options);
|
|
349
493
|
const serviceName = description.service.name;
|
|
350
494
|
const clientName = serviceName.replace(/Service$|$/, 'Client');
|
|
351
|
-
const namespaceName = serviceName.charAt(0).toLowerCase() +
|
|
352
|
-
serviceName.substr(1);
|
|
495
|
+
const namespaceName = serviceName.charAt(0).toLowerCase() + serviceName.substr(1);
|
|
353
496
|
let src = `/*!
|
|
354
497
|
* IMQ-RPC Service Client: ${description.service.name}
|
|
355
498
|
*
|
|
@@ -408,21 +551,24 @@ export namespace ${namespaceName} {\n`;
|
|
|
408
551
|
const args = methods[methodName].arguments;
|
|
409
552
|
const description = methods[methodName].description;
|
|
410
553
|
const ret = methods[methodName].returns;
|
|
411
|
-
const addArgs = [
|
|
554
|
+
const addArgs = [
|
|
555
|
+
{
|
|
412
556
|
description: 'if passed, will deliver given metadata to ' +
|
|
413
557
|
'service, and will initiate trace handler calls',
|
|
414
558
|
name: 'imqMetadata',
|
|
415
559
|
type: 'IMQMetadata',
|
|
416
560
|
tsType: 'IMQMetadata',
|
|
417
561
|
isOptional: true,
|
|
418
|
-
},
|
|
562
|
+
},
|
|
563
|
+
{
|
|
419
564
|
description: 'if passed the method will be called with ' +
|
|
420
565
|
'the specified delay over message queue',
|
|
421
566
|
name: 'imqDelay',
|
|
422
567
|
type: 'IMQDelay',
|
|
423
568
|
tsType: 'IMQDelay',
|
|
424
|
-
isOptional: true
|
|
425
|
-
}
|
|
569
|
+
isOptional: true,
|
|
570
|
+
},
|
|
571
|
+
];
|
|
426
572
|
let retType = ret.tsType.replace(/\r?\n/g, ' ').replace(/\s{2,}/g, ' ');
|
|
427
573
|
for (let i = 1; i <= 2; i++) {
|
|
428
574
|
const arg = args[args.length - i];
|
|
@@ -431,15 +577,16 @@ export namespace ${namespaceName} {\n`;
|
|
|
431
577
|
}
|
|
432
578
|
}
|
|
433
579
|
args.push(...addArgs); // make sure client expect them
|
|
434
|
-
// istanbul ignore if
|
|
435
580
|
if (retType === 'Promise') {
|
|
436
581
|
retType = 'Promise<any>';
|
|
437
582
|
}
|
|
438
583
|
src += ' /**\n';
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
584
|
+
src += description
|
|
585
|
+
? description
|
|
586
|
+
.split(/\r?\n/)
|
|
587
|
+
.map(line => ` * ${line}`)
|
|
588
|
+
.join('\n') + '\n *\n'
|
|
589
|
+
: '';
|
|
443
590
|
for (let i = 0, s = args.length; i < s; i++) {
|
|
444
591
|
const arg = args[i];
|
|
445
592
|
src += ` * @param {${toComment(arg.tsType)}} `;
|
|
@@ -454,9 +601,12 @@ export namespace ${namespaceName} {\n`;
|
|
|
454
601
|
src += ` public async ${methodName}(`;
|
|
455
602
|
for (let i = 0, s = args.length; i < s; i++) {
|
|
456
603
|
const arg = args[i];
|
|
457
|
-
src +=
|
|
458
|
-
|
|
459
|
-
|
|
604
|
+
src +=
|
|
605
|
+
arg.name +
|
|
606
|
+
(arg.isOptional ? '?' : '') +
|
|
607
|
+
': ' +
|
|
608
|
+
arg.tsType.replace(/\s{2,}/g, ' ') +
|
|
609
|
+
(i === s - 1 ? '' : ', ');
|
|
460
610
|
}
|
|
461
611
|
src += `): ${promisedType(retType)} {\n`;
|
|
462
612
|
src += ' '.repeat(12);
|
|
@@ -467,17 +617,14 @@ export namespace ${namespaceName} {\n`;
|
|
|
467
617
|
const module = await compile(name, src, options);
|
|
468
618
|
return module ? module[namespaceName] : /* istanbul ignore next */ null;
|
|
469
619
|
}
|
|
470
|
-
// codebeat:enable[LOC,ABC]
|
|
471
620
|
/**
|
|
472
|
-
* Return promised typedef of a given type if its missing
|
|
621
|
+
* Return the promised typedef of a given type if its missing
|
|
473
622
|
*
|
|
474
|
-
*c @access private
|
|
475
623
|
* @param {string} typedef
|
|
476
624
|
* @returns {string}
|
|
477
625
|
*/
|
|
478
626
|
function promisedType(typedef) {
|
|
479
|
-
|
|
480
|
-
if (!/^Promise</.test(typedef)) {
|
|
627
|
+
if (!typedef.startsWith('Promise<')) {
|
|
481
628
|
typedef = `Promise<${typedef}>`;
|
|
482
629
|
}
|
|
483
630
|
return typedef;
|
|
@@ -485,7 +632,6 @@ function promisedType(typedef) {
|
|
|
485
632
|
/**
|
|
486
633
|
* Removes Promise from type definition if any
|
|
487
634
|
*
|
|
488
|
-
* @access private
|
|
489
635
|
* @param {string} typedef
|
|
490
636
|
* @returns {string}
|
|
491
637
|
*/
|
|
@@ -495,7 +641,6 @@ function cleanType(typedef) {
|
|
|
495
641
|
/**
|
|
496
642
|
* Type to comment
|
|
497
643
|
*
|
|
498
|
-
* @access private
|
|
499
644
|
* @param {string} typedef
|
|
500
645
|
* @param {boolean} [promised]
|
|
501
646
|
* @returns {string}
|
|
@@ -504,15 +649,72 @@ function toComment(typedef, promised = false) {
|
|
|
504
649
|
if (promised) {
|
|
505
650
|
typedef = promisedType(typedef);
|
|
506
651
|
}
|
|
507
|
-
|
|
508
|
-
|
|
652
|
+
return typedef
|
|
653
|
+
.split(/\r?\n/)
|
|
509
654
|
.map((line, lineNum) => (lineNum ? ' * ' : '') + line)
|
|
510
655
|
.join('\n');
|
|
511
656
|
}
|
|
657
|
+
/**
|
|
658
|
+
* Transpiles generated client TypeScript source to CommonJS JavaScript.
|
|
659
|
+
*
|
|
660
|
+
* TypeScript 7 (native port) removed the in-process `transpile()`/`transpileModule()`
|
|
661
|
+
* API; its `typescript/unstable/*` replacement is not a stable runtime contract.
|
|
662
|
+
* Instead this shells out to the bundled `tsc` CLI in transform-only mode
|
|
663
|
+
* (`noCheck`, `noEmitOnError:false`) — the same "emit regardless of type or
|
|
664
|
+
* module-resolution errors" behaviour the old single-file transpile provided,
|
|
665
|
+
* built on the stable CLI rather than the unstable programmatic API.
|
|
666
|
+
*
|
|
667
|
+
* @param {string} src - generated client source
|
|
668
|
+
* @returns {string} - emitted CommonJS JavaScript
|
|
669
|
+
*/
|
|
670
|
+
function transpileClient(src) {
|
|
671
|
+
const dir = (0, node_fs_1.mkdtempSync)((0, node_path_1.join)((0, node_os_1.tmpdir)(), 'imq-client-'));
|
|
672
|
+
try {
|
|
673
|
+
const tsFile = (0, node_path_1.join)(dir, '__client__.ts');
|
|
674
|
+
const jsFile = (0, node_path_1.join)(dir, '__client__.js');
|
|
675
|
+
const cfgFile = (0, node_path_1.join)(dir, 'tsconfig.json');
|
|
676
|
+
(0, node_fs_1.writeFileSync)(tsFile, src);
|
|
677
|
+
(0, node_fs_1.writeFileSync)(cfgFile, JSON.stringify({
|
|
678
|
+
compilerOptions: {
|
|
679
|
+
...tsOptions,
|
|
680
|
+
// transform-only: always emit, ignoring type and
|
|
681
|
+
// module-resolution errors (the generated client references
|
|
682
|
+
// `@imqueue/rpc` types that need not resolve in this temp
|
|
683
|
+
// dir)
|
|
684
|
+
noCheck: true,
|
|
685
|
+
noEmitOnError: false,
|
|
686
|
+
skipLibCheck: true,
|
|
687
|
+
declaration: false,
|
|
688
|
+
declarationMap: false,
|
|
689
|
+
sourceMap: false,
|
|
690
|
+
inlineSources: false,
|
|
691
|
+
types: [],
|
|
692
|
+
rootDir: dir,
|
|
693
|
+
outDir: dir,
|
|
694
|
+
},
|
|
695
|
+
files: ['__client__.ts'],
|
|
696
|
+
}));
|
|
697
|
+
// resolve the compiler entry via the package root (its `exports` map
|
|
698
|
+
// blocks `typescript/lib/*`, so build a raw path that Node runs
|
|
699
|
+
// directly)
|
|
700
|
+
const tscJs = (0, node_path_1.join)((0, node_path_1.dirname)(require.resolve('typescript/package.json')), 'lib', 'tsc.js');
|
|
701
|
+
const result = (0, node_child_process_1.spawnSync)(process.execPath, [tscJs, '-p', cfgFile], {
|
|
702
|
+
encoding: 'utf8',
|
|
703
|
+
});
|
|
704
|
+
if (!(0, node_fs_1.existsSync)(jsFile)) {
|
|
705
|
+
throw new Error('IMQClient: client transpilation produced no output' +
|
|
706
|
+
(result.stdout ? `\n${result.stdout}` : '') +
|
|
707
|
+
(result.stderr ? `\n${result.stderr}` : ''));
|
|
708
|
+
}
|
|
709
|
+
return (0, node_fs_1.readFileSync)(jsFile, 'utf8');
|
|
710
|
+
}
|
|
711
|
+
finally {
|
|
712
|
+
(0, node_fs_1.rmSync)(dir, { recursive: true, force: true });
|
|
713
|
+
}
|
|
714
|
+
}
|
|
512
715
|
/**
|
|
513
716
|
* Compiles client source code and returns loaded module
|
|
514
717
|
*
|
|
515
|
-
* @access private
|
|
516
718
|
* @param {string} name
|
|
517
719
|
* @param {string} src
|
|
518
720
|
* @param {IMQClientOptions} options
|
|
@@ -522,25 +724,19 @@ async function compile(name, src, options) {
|
|
|
522
724
|
const path = options.path;
|
|
523
725
|
const srcFile = `${path}/${name}.ts`;
|
|
524
726
|
const jsFile = `${path}/${name}.js`;
|
|
525
|
-
const js =
|
|
727
|
+
const js = transpileClient(src);
|
|
526
728
|
if (options.write) {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
await (0, _1.mkdir)(path);
|
|
729
|
+
if (!(await (0, helpers_1.fileExists)(path))) {
|
|
730
|
+
await (0, helpers_1.mkdir)(path);
|
|
530
731
|
}
|
|
531
|
-
await Promise.all([
|
|
532
|
-
(0, _1.writeFile)(srcFile, src),
|
|
533
|
-
(0, _1.writeFile)(jsFile, js),
|
|
534
|
-
]);
|
|
732
|
+
await Promise.all([(0, helpers_1.writeFile)(srcFile, src), (0, helpers_1.writeFile)(jsFile, js)]);
|
|
535
733
|
}
|
|
536
|
-
// istanbul ignore else
|
|
537
734
|
if (options.compile) {
|
|
538
|
-
const script = new
|
|
735
|
+
const script = new node_vm_1.Script(js);
|
|
539
736
|
const context = { exports: {}, require };
|
|
540
737
|
script.runInNewContext(context, { filename: jsFile });
|
|
541
738
|
return context.exports;
|
|
542
739
|
}
|
|
543
|
-
// istanbul ignore next
|
|
544
740
|
return null;
|
|
545
741
|
}
|
|
546
742
|
//# sourceMappingURL=IMQClient.js.map
|