@resolveio/server-lib 20.8.6 → 20.9.1
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/managers/mongo.manager.js +18 -2
- package/managers/mongo.manager.js.map +1 -1
- package/managers/subscription.manager.js +11 -6
- package/managers/subscription.manager.js.map +1 -1
- package/managers/websocket.manager.d.ts +1 -0
- package/managers/websocket.manager.js +69 -10
- package/managers/websocket.manager.js.map +1 -1
- package/managers/worker-dispatcher.manager.d.ts +1 -1
- package/managers/worker-dispatcher.manager.js +68 -42
- package/managers/worker-dispatcher.manager.js.map +1 -1
- package/managers/worker-server.manager.js +47 -13
- package/managers/worker-server.manager.js.map +1 -1
- package/models/subscription.model.d.ts +1 -0
- package/models/subscription.model.js.map +1 -1
- package/package.json +3 -1
- package/server-app.js +61 -18
- package/server-app.js.map +1 -1
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.WorkerDispatcherManager = void 0;
|
|
4
4
|
var common_1 = require("../util/common");
|
|
5
|
+
var msgpackr_1 = require("msgpackr");
|
|
5
6
|
var WorkerDispatcherManager = /** @class */ (function () {
|
|
6
7
|
function WorkerDispatcherManager() {
|
|
7
8
|
this._workers = [];
|
|
@@ -229,13 +230,33 @@ var WorkerDispatcherManager = /** @class */ (function () {
|
|
|
229
230
|
/**
|
|
230
231
|
* Handle messages coming back from a worker (like 'taskComplete').
|
|
231
232
|
*/
|
|
232
|
-
WorkerDispatcherManager.prototype.handleWorkerMessage = function (workerId,
|
|
233
|
+
WorkerDispatcherManager.prototype.handleWorkerMessage = function (workerId, rawMessage) {
|
|
233
234
|
var data;
|
|
234
235
|
try {
|
|
235
|
-
|
|
236
|
+
if (typeof rawMessage === 'string') {
|
|
237
|
+
data = JSON.parse(rawMessage, common_1.dateReviver);
|
|
238
|
+
}
|
|
239
|
+
else if (Buffer.isBuffer(rawMessage)) {
|
|
240
|
+
data = (0, msgpackr_1.unpack)(rawMessage);
|
|
241
|
+
}
|
|
242
|
+
else if (Array.isArray(rawMessage)) {
|
|
243
|
+
var chunks = rawMessage;
|
|
244
|
+
data = (0, msgpackr_1.unpack)(Buffer.concat(chunks));
|
|
245
|
+
}
|
|
246
|
+
else if (rawMessage instanceof ArrayBuffer) {
|
|
247
|
+
data = (0, msgpackr_1.unpack)(Buffer.from(rawMessage));
|
|
248
|
+
}
|
|
249
|
+
else if (ArrayBuffer.isView(rawMessage)) {
|
|
250
|
+
var view = rawMessage;
|
|
251
|
+
data = (0, msgpackr_1.unpack)(Buffer.from(view.buffer, view.byteOffset, view.byteLength));
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
console.error('Unsupported worker message type received:', typeof rawMessage);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
236
257
|
}
|
|
237
|
-
catch (
|
|
238
|
-
console.error('Failed to parse worker message:',
|
|
258
|
+
catch (err) {
|
|
259
|
+
console.error('Failed to parse worker message:', err);
|
|
239
260
|
return;
|
|
240
261
|
}
|
|
241
262
|
if (data.type === 'taskComplete') {
|
|
@@ -289,50 +310,20 @@ var WorkerDispatcherManager = /** @class */ (function () {
|
|
|
289
310
|
}
|
|
290
311
|
};
|
|
291
312
|
WorkerDispatcherManager.prototype.sendWorkerPayload = function (ws, payload) {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
if (ws && ws.readyState === ws.OPEN) {
|
|
295
|
-
try {
|
|
296
|
-
ws.send(payloadStr);
|
|
297
|
-
}
|
|
298
|
-
catch (err) {
|
|
299
|
-
if (!isStringPayload) {
|
|
300
|
-
var task = JSON.parse(payloadStr, common_1.dateReviver);
|
|
301
|
-
this._taskQueue.unshift(task);
|
|
302
|
-
this.dispatchQueue();
|
|
303
|
-
if (this._methodManager.getEnableDebug()) {
|
|
304
|
-
console.log(new Date(), 'Sending to Server', task);
|
|
305
|
-
}
|
|
306
|
-
this.disconnectWorker(ws['id_worker']);
|
|
307
|
-
ws.close();
|
|
308
|
-
console.error('Failed to send worker response:', err);
|
|
309
|
-
var pendingTask = this._pendingTasks.get(task.taskId);
|
|
310
|
-
if (pendingTask) {
|
|
311
|
-
clearTimeout(pendingTask.timeout);
|
|
312
|
-
this._pendingTasks.delete(task.taskId);
|
|
313
|
-
if (pendingTask.promise) {
|
|
314
|
-
pendingTask.promise.reject('Failed to send worker response: ' + (err === null || err === void 0 ? void 0 : err.toString()));
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
else {
|
|
319
|
-
this.disconnectWorker(ws['id_worker']);
|
|
320
|
-
ws.close();
|
|
321
|
-
console.error('Failed to send worker payload:', err);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
313
|
+
if (!ws) {
|
|
314
|
+
return;
|
|
324
315
|
}
|
|
325
|
-
|
|
326
|
-
if (
|
|
327
|
-
var
|
|
328
|
-
this._taskQueue.unshift(
|
|
316
|
+
if (ws.readyState !== ws.OPEN) {
|
|
317
|
+
if (typeof payload !== 'string') {
|
|
318
|
+
var task_1 = payload;
|
|
319
|
+
this._taskQueue.unshift(task_1);
|
|
329
320
|
this.dispatchQueue();
|
|
330
321
|
this.disconnectWorker(ws['id_worker']);
|
|
331
322
|
ws.close();
|
|
332
|
-
var pendingTask = this._pendingTasks.get(
|
|
323
|
+
var pendingTask = this._pendingTasks.get(task_1.taskId);
|
|
333
324
|
if (pendingTask) {
|
|
334
325
|
clearTimeout(pendingTask.timeout);
|
|
335
|
-
this._pendingTasks.delete(
|
|
326
|
+
this._pendingTasks.delete(task_1.taskId);
|
|
336
327
|
if (pendingTask.promise) {
|
|
337
328
|
pendingTask.promise.reject('Worker socket not open.');
|
|
338
329
|
}
|
|
@@ -342,6 +333,41 @@ var WorkerDispatcherManager = /** @class */ (function () {
|
|
|
342
333
|
this.disconnectWorker(ws['id_worker']);
|
|
343
334
|
ws.close();
|
|
344
335
|
}
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (typeof payload === 'string') {
|
|
339
|
+
try {
|
|
340
|
+
ws.send(payload);
|
|
341
|
+
}
|
|
342
|
+
catch (err) {
|
|
343
|
+
this.disconnectWorker(ws['id_worker']);
|
|
344
|
+
ws.close();
|
|
345
|
+
console.error('Failed to send worker payload:', err);
|
|
346
|
+
}
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
var task = payload;
|
|
350
|
+
var payloadBuffer = (0, msgpackr_1.pack)(task);
|
|
351
|
+
try {
|
|
352
|
+
ws.send(payloadBuffer);
|
|
353
|
+
}
|
|
354
|
+
catch (err) {
|
|
355
|
+
this._taskQueue.unshift(task);
|
|
356
|
+
this.dispatchQueue();
|
|
357
|
+
if (this._methodManager.getEnableDebug()) {
|
|
358
|
+
console.log(new Date(), 'Sending to Server', task);
|
|
359
|
+
}
|
|
360
|
+
this.disconnectWorker(ws['id_worker']);
|
|
361
|
+
ws.close();
|
|
362
|
+
console.error('Failed to send worker response:', err);
|
|
363
|
+
var pendingTask = this._pendingTasks.get(task.taskId);
|
|
364
|
+
if (pendingTask) {
|
|
365
|
+
clearTimeout(pendingTask.timeout);
|
|
366
|
+
this._pendingTasks.delete(task.taskId);
|
|
367
|
+
if (pendingTask.promise) {
|
|
368
|
+
pendingTask.promise.reject('Failed to send worker response: ' + (err === null || err === void 0 ? void 0 : err.toString()));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
345
371
|
}
|
|
346
372
|
};
|
|
347
373
|
return WorkerDispatcherManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/worker-dispatcher.manager.ts"],"names":[],"mappings":";;;AAEA,yCAAgE;AAoBhE;IAUC;QAPQ,aAAQ,GAAuB,EAAE,CAAC;QAClC,eAAU,GAAkB,EAAE,CAAC;QAC/B,oBAAe,GAAiC,EAAE,CAAC;QACnD,kBAAa,GAA6B,IAAI,GAAG,EAAE,CAAC;QAEpD,oBAAe,GAAG,EAAE,CAAC;IAEd,CAAC;IAET,8BAAM,GAAb,UAA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IAAI,CAAC,gBAAgB,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;gBACvC,EAAE,CAAC,KAAK,EAAE,CAAC;gBAEX,IAAI,WAAW,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAEtD,IAAI,WAAW,EAAE;oBAChB,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;oBAClC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;oBAEvC,IAAI,WAAW,CAAC,OAAO,EAAE;wBACxB,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,yBAAyB,CAAC,CAAC;qBACtD;iBACD;aACD;iBACI;gBACJ,IAAI,CAAC,gBAAgB,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;gBACvC,EAAE,CAAC,KAAK,EAAE,CAAC;aACX;SACD;IACI,CAAC;IACT,8BAAC;AAAD,CAjaA,AAiaC,IAAA;AAjaY,0DAAuB","file":"worker-dispatcher.manager.js","sourcesContent":["import * as WebSocket from 'ws';\nimport { ServerResponseModel, TaskPayload, TaskResponse } from '../models/server-message.model';\nimport { dateReviver, objectIdHexString } from '../util/common';\nimport { MethodManager } from './method.manager';\nimport { WebSocketManager } from './websocket.manager';\n\nexport interface WorkerConnection {\n\tid: string;\n\tws: WebSocket.WebSocket;\n\tactiveTasks: { taskId: string; weight: number }[];\n}\n\ninterface PendingTask {\n\ttimeout: NodeJS.Timeout;\n\tpromise?: {\n\t\t// eslint-disable-next-line no-unused-vars\n\t\tresolve: (value: any) => void;\n\t\t// eslint-disable-next-line no-unused-vars\n\t\treject: (reason?: any) => void;\n\t};\n}\n\nexport class WorkerDispatcherManager {\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskPayload[] = [];\n\tprivate _clientRequests: { [taskId: string]: string } = {};\n\tprivate _pendingTasks: Map<string, PendingTask> = new Map();\n\n\tprivate MAX_CONCURRENCY = 10;\n\n\tconstructor() {}\n\n\tstatic create(websocketManager: WebSocketManager, methodManager: MethodManager) {\n\t\tconst workerDispatcherManager = new WorkerDispatcherManager();\n\t\tworkerDispatcherManager.initialize(websocketManager, methodManager);\n\t\treturn workerDispatcherManager;\n\t}\n\n\tpublic initialize(websocketManager: WebSocketManager, methodManager: MethodManager) {\n\t\tthis._websocketManager = websocketManager;\n\t\tthis._methodManager = methodManager;\n\t}\n\n\tpublic isSafeShutdown() {\n\t\treturn !this._taskQueue.length && !this._pendingTasks.size;\n\t}\n\n\tpublic addWorker(ws: WebSocket.WebSocket) {\n\t\tthis._workers.push({\n\t\t\tid: ws['id_worker'],\n\t\t\tws: ws,\n\t\t\tactiveTasks: []\n\t\t});\n\n\t\tsetInterval(() => {\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(JSON.stringify(this._workers.map(a => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: a.id,\n\t\t\t\t\t\tactiveTasks: a.activeTasks\n\t\t\t\t\t}\n\t\t\t\t}), null, 2));\n\t\t\t}\n\t\t}, 5000);\n\n\t\tif (this._taskQueue.length) {\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\tpublic disconnectWorker(workerId: string) {\n\t\tthis._workers = this._workers.filter(w => w.id !== workerId);\n\t}\n\n\tpublic hasWorkers() {\n\t\treturn this._workers.length > 0;\n\t}\n\n\t/**\n\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tpublic sendClientTask(messageId: number, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\tthis._taskQueue.push({\n\t\t\ttype: 'task',\n\t\t\ttaskId,\n\t\t\tmessageId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\n\n\t\tif (userContext && userContext.id_ws) {\n\t\t\tthis._clientRequests[taskId] = userContext.id_ws;\n\t\t}\n\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * Same as sendInternalTask but returns a Promise so you can `await` it.\n\t */\n\tpublic sendInternalPromise(method: string, params: any[] = []): Promise<any> {\n\t\tif (!Array.isArray(params)) {\n\t\t\tparams = [params];\n\t\t}\n\n\t\t// eslint-disable-next-line no-restricted-syntax\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\tthis._taskQueue.push({\n\t\t\t\ttype: 'task',\n\t\t\t\ttaskId,\n\t\t\t\tmethod,\n\t\t\t\tparams,\n\t\t\t\tmessageId: 0,\n\t\t\t\tuserContext: {\n\t\t\t\t\tuser: 'Internal System'\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tthis._pendingTasks.set(taskId, {\n\t\t\t\ttimeout: null,\n\t\t\t\tpromise: { resolve, reject }\n\t\t\t});\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Send Internal Promise', this._taskQueue);\n\t\t\t}\n\n\t\t\tthis.dispatchQueue();\n\t\t});\n\t}\n\n\t/**\n\t * Send a task internally without returning a promise.\n\t */\n\tpublic sendInternalTask(method: string, params = []) {\n\t\tif (!Array.isArray(params)) {\n\t\t\tparams = [params];\n\t\t}\n\n\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\tthis._taskQueue.push({\n\t\t\ttype: 'task',\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tmessageId: 0,\n\t\t\tuserContext: {\n\t\t\t\tuser: 'Internal System'\n\t\t\t}\n\t\t});\n\n\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Send Internal Task', this._taskQueue);\n\t\t}\n\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * The main loop that assigns tasks from _taskQueue to any worker that has capacity.\n\t */\n\tprivate dispatchQueue() {\n\t\tif (!this._taskQueue.length) {\n\t\t\treturn;\n\t\t}\n\n\t\twhile (this._taskQueue.length > 0) {\n\t\t\tlet worker = this.findAvailableWorker();\n\n\t\t\tif (!worker) {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.dispatchQueue();\n\t\t\t\t}, 25);\n\n\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'No Worker Available', JSON.stringify(this._workers, null, 2));\n\t\t\t\t}\n\n\t\t\t\treturn; // no worker can take more tasks right now\n\t\t\t}\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Worker Available', worker.id, worker.activeTasks);\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tlet task = this._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(worker, task);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks.length < this.MAX_CONCURRENCY);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\tcandidates.sort((x, y) => {\n\t\t\tlet totalX = x.activeTasks.map(a => a.weight).reduce((a, b) => a + b, 0);\n\t\t\tlet totalY = y.activeTasks.map(a => a.weight).reduce((a, b) => a + b, 0);\n\t\t\treturn totalX - totalY;\n\t\t});\n\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskPayload) {\n\t\tlet method = this._methodManager.getMethod(task.method);\n\n\t\tif (!method) {\n\t\t\tconsole.error('Failed to send task to worker - Could not find method:', task.method);\n\t\t\treturn;\n\t\t}\n\n\t\tworker.activeTasks.push({\n\t\t\ttaskId: task.taskId,\n\t\t\tweight: method && method.workerTaskWeight ? method.workerTaskWeight : 1\n\t\t});\n\n\t\tlet payload: TaskPayload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmessageId: task.messageId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext || {}\n\t\t};\n\n\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\tlet pending = this._pendingTasks.get(task.taskId);\n\t\t\t\n\t\t\tif (pending) {\n\t\t\t\tif (pending.promise) {\n\t\t\t\t\tpending.promise.reject('Task timed out after 2m in WorkerDispatcherManager for method: ' + task.method);\n\t\t\t\t}\n\n\t\t\t\tthis._pendingTasks.delete(task.taskId);\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'TIMEOUT HIT', 'task', task.taskId, task.messageId, task.method, JSON.stringify(this._workers.map(a => a.activeTasks)));\n\n\t\t\tworker.activeTasks = worker.activeTasks.filter(a => a.taskId !== task.taskId);\n\n\t\t\tif (task.userContext && task.userContext.id_ws) {\n\t\t\t\tlet timeoutRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: task.messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Task timed out after 2m in WorkerDispatcherManager for method: ' + task.method\n\t\t\t\t};\n\n\t\t\t\tlet clientWS = this._websocketManager.getWebSocket(task.userContext.id_ws);\n\n\t\t\t\tif (clientWS) {\n\t\t\t\t\tthis._websocketManager.send(clientWS, timeoutRes);\n\t\t\t\t}\n\t\t\t}\n\t\t}, method.timeoutOverride || (1000 * 60 * 2));\n\n\t\t// If we already stored a promise for this task (from sendInternalPromise), add the timeout now\n\t\tlet existing = this._pendingTasks.get(task.taskId);\n\t\tif (!existing) {\n\t\t\texisting = { timeout: null };\n\t\t}\n\n\t\texisting.timeout = timeoutHandle;\n\t\tthis._pendingTasks.set(task.taskId, existing);\n\n\t\ttry {\n\t\t\tthis.sendWorkerPayload(worker.ws, payload);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\n\t\t\tclearTimeout(timeoutHandle);\n\t\t\tworker.activeTasks = worker.activeTasks.filter(a => a.taskId !== task.taskId);\n\n\t\t\t// Put task back in front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tpublic handleWorkerMessage(workerId: string, messageStr: string) {\n\t\tlet data: TaskResponse;\n\n\t\ttry {\n\t\t\tdata = JSON.parse(messageStr, dateReviver);\n\t\t}\n\t\tcatch {\n\t\t\tconsole.error('Failed to parse worker message:', messageStr);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet worker = this._workers.find(x => x.id === workerId);\n\n\t\t\tif (!worker) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet { taskId, messageId, error, result } = data;\n\t\t\tworker.activeTasks = worker.activeTasks.filter(a => a.taskId !== taskId);\n\n\t\t\tlet pendingTask = this._pendingTasks.get(taskId);\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Recv from Worker Server', data);\n\t\t\t}\n\n\t\t\tif (pendingTask) {\n\t\t\t\tif (pendingTask.promise) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tpendingTask.promise.reject(result);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tpendingTask.promise.resolve(result);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tclearTimeout(pendingTask.timeout);\n\t\t\t\tthis._pendingTasks.delete(taskId);\n\t\t\t}\n\n\t\t\t// Look up original request if it came from a client\n\t\t\tlet clientReqId = this._clientRequests[taskId];\n\n\t\t\tif (clientReqId) {\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: result\n\t\t\t\t};\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.hasError = true;\n\t\t\t\t\tres.data = result;\n\t\t\t\t}\n\n\t\t\t\tlet clientReqWS = this._websocketManager.getWebSocket(clientReqId);\n\n\t\t\t\tif (clientReqWS) {\n\t\t\t\t\tthis._websocketManager.send(clientReqWS, res);\n\t\t\t\t}\n\n\t\t\t\tif (this._clientRequests[taskId]) {\n\t\t\t\t\tdelete this._clientRequests[taskId];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tif (this._taskQueue.length) {\n\t\t\t\tthis.dispatchQueue();\n\t\t\t}\n\t\t}\n\t}\n\n public sendWorkerPayload(ws: WebSocket.WebSocket, payload: TaskPayload | string) {\n\t\t\tconst isStringPayload = typeof payload === 'string';\n\t\t\tconst payloadStr = isStringPayload ? payload : JSON.stringify(payload);\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\ttry {\n\t\t\t\t\tws.send(payloadStr);\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tif (!isStringPayload) {\n\t\t\t\t\t\tlet task = JSON.parse(payloadStr, dateReviver);\n\n\t\t\t\t\t\tthis._taskQueue.unshift(task);\n\t\t\t\t\t\tthis.dispatchQueue();\n\n\t\t\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\t\t\tconsole.log(new Date(), 'Sending to Server', task);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t\tconsole.error('Failed to send worker response:', err);\n\n\t\t\t\t\t\tlet pendingTask = this._pendingTasks.get(task.taskId);\n\n\t\t\t\t\t\tif (pendingTask) {\n\t\t\t\t\t\t\tclearTimeout(pendingTask.timeout);\n\t\t\t\t\t\t\tthis._pendingTasks.delete(task.taskId);\n\n\t\t\t\t\t\t\tif (pendingTask.promise) {\n\t\t\t\t\t\t\t\tpendingTask.promise.reject('Failed to send worker response: ' + err?.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\t\t\t\tws.close();\n\t\t\t\t\t\tconsole.error('Failed to send worker payload:', err);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (ws) {\n\t\t\t\tif (!isStringPayload) {\n\t\t\t\t\tlet task = JSON.parse(payloadStr, dateReviver);\n\n\t\t\t\t\tthis._taskQueue.unshift(task);\n\t\t\t\t\tthis.dispatchQueue();\n\n\t\t\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\t\t\tws.close();\n\n\t\t\t\t\tlet pendingTask = this._pendingTasks.get(task.taskId);\n\n\t\t\t\t\tif (pendingTask) {\n\t\t\t\t\t\tclearTimeout(pendingTask.timeout);\n\t\t\t\t\t\tthis._pendingTasks.delete(task.taskId);\n\n\t\t\t\t\t\tif (pendingTask.promise) {\n\t\t\t\t\t\t\tpendingTask.promise.reject('Worker socket not open.');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\t\t\tws.close();\n\t\t\t\t}\n\t\t\t}\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/worker-dispatcher.manager.ts"],"names":[],"mappings":";;;AAEA,yCAAgE;AAGhE,qCAAwC;AAkBxC;IAUC;QAPQ,aAAQ,GAAuB,EAAE,CAAC;QAClC,eAAU,GAAkB,EAAE,CAAC;QAC/B,oBAAe,GAAiC,EAAE,CAAC;QACnD,kBAAa,GAA6B,IAAI,GAAG,EAAE,CAAC;QAEpD,oBAAe,GAAG,EAAE,CAAC;IAEd,CAAC;IAET,8BAAM,GAAb,UAAc,gBAAkC,EAAE,aAA4B;QAC7E,IAAM,uBAAuB,GAAG,IAAI,uBAAuB,EAAE,CAAC;QAC9D,uBAAuB,CAAC,UAAU,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;QACp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IAAA;AA9bY,0DAAuB","file":"worker-dispatcher.manager.js","sourcesContent":["import * as WebSocket from 'ws';\nimport { ServerResponseModel, TaskPayload, TaskResponse } from '../models/server-message.model';\nimport { dateReviver, objectIdHexString } from '../util/common';\nimport { MethodManager } from './method.manager';\nimport { WebSocketManager } from './websocket.manager';\nimport { pack, unpack } from 'msgpackr';\n\nexport interface WorkerConnection {\n\tid: string;\n\tws: WebSocket.WebSocket;\n\tactiveTasks: { taskId: string; weight: number }[];\n}\n\ninterface PendingTask {\n\ttimeout: NodeJS.Timeout;\n\tpromise?: {\n\t\t// eslint-disable-next-line no-unused-vars\n\t\tresolve: (value: any) => void;\n\t\t// eslint-disable-next-line no-unused-vars\n\t\treject: (reason?: any) => void;\n\t};\n}\n\nexport class WorkerDispatcherManager {\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _workers: WorkerConnection[] = [];\n\tprivate _taskQueue: TaskPayload[] = [];\n\tprivate _clientRequests: { [taskId: string]: string } = {};\n\tprivate _pendingTasks: Map<string, PendingTask> = new Map();\n\n\tprivate MAX_CONCURRENCY = 10;\n\n\tconstructor() {}\n\n\tstatic create(websocketManager: WebSocketManager, methodManager: MethodManager) {\n\t\tconst workerDispatcherManager = new WorkerDispatcherManager();\n\t\tworkerDispatcherManager.initialize(websocketManager, methodManager);\n\t\treturn workerDispatcherManager;\n\t}\n\n\tpublic initialize(websocketManager: WebSocketManager, methodManager: MethodManager) {\n\t\tthis._websocketManager = websocketManager;\n\t\tthis._methodManager = methodManager;\n\t}\n\n\tpublic isSafeShutdown() {\n\t\treturn !this._taskQueue.length && !this._pendingTasks.size;\n\t}\n\n\tpublic addWorker(ws: WebSocket.WebSocket) {\n\t\tthis._workers.push({\n\t\t\tid: ws['id_worker'],\n\t\t\tws: ws,\n\t\t\tactiveTasks: []\n\t\t});\n\n\t\tsetInterval(() => {\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(JSON.stringify(this._workers.map(a => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: a.id,\n\t\t\t\t\t\tactiveTasks: a.activeTasks\n\t\t\t\t\t}\n\t\t\t\t}), null, 2));\n\t\t\t}\n\t\t}, 5000);\n\n\t\tif (this._taskQueue.length) {\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\tpublic disconnectWorker(workerId: string) {\n\t\tthis._workers = this._workers.filter(w => w.id !== workerId);\n\t}\n\n\tpublic hasWorkers() {\n\t\treturn this._workers.length > 0;\n\t}\n\n\t/**\n\t * Add a new task to our in-memory queue and try to dispatch.\n\t */\n\tpublic sendClientTask(messageId: number, method: string, params: any[], userContext?: { id_user?: string; user?: string; id_ws?: string }) {\n\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\tthis._taskQueue.push({\n\t\t\ttype: 'task',\n\t\t\ttaskId,\n\t\t\tmessageId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tuserContext\n\t\t});\n\n\t\tif (userContext && userContext.id_ws) {\n\t\t\tthis._clientRequests[taskId] = userContext.id_ws;\n\t\t}\n\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * Same as sendInternalTask but returns a Promise so you can `await` it.\n\t */\n\tpublic sendInternalPromise(method: string, params: any[] = []): Promise<any> {\n\t\tif (!Array.isArray(params)) {\n\t\t\tparams = [params];\n\t\t}\n\n\t\t// eslint-disable-next-line no-restricted-syntax\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\t\tthis._taskQueue.push({\n\t\t\t\ttype: 'task',\n\t\t\t\ttaskId,\n\t\t\t\tmethod,\n\t\t\t\tparams,\n\t\t\t\tmessageId: 0,\n\t\t\t\tuserContext: {\n\t\t\t\t\tuser: 'Internal System'\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tthis._pendingTasks.set(taskId, {\n\t\t\t\ttimeout: null,\n\t\t\t\tpromise: { resolve, reject }\n\t\t\t});\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Send Internal Promise', this._taskQueue);\n\t\t\t}\n\n\t\t\tthis.dispatchQueue();\n\t\t});\n\t}\n\n\t/**\n\t * Send a task internally without returning a promise.\n\t */\n\tpublic sendInternalTask(method: string, params = []) {\n\t\tif (!Array.isArray(params)) {\n\t\t\tparams = [params];\n\t\t}\n\n\t\tlet taskId = 'task-' + objectIdHexString();\n\n\t\tthis._taskQueue.push({\n\t\t\ttype: 'task',\n\t\t\ttaskId,\n\t\t\tmethod,\n\t\t\tparams,\n\t\t\tmessageId: 0,\n\t\t\tuserContext: {\n\t\t\t\tuser: 'Internal System'\n\t\t\t}\n\t\t});\n\n\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Send Internal Task', this._taskQueue);\n\t\t}\n\n\t\tthis.dispatchQueue();\n\t}\n\n\t/**\n\t * The main loop that assigns tasks from _taskQueue to any worker that has capacity.\n\t */\n\tprivate dispatchQueue() {\n\t\tif (!this._taskQueue.length) {\n\t\t\treturn;\n\t\t}\n\n\t\twhile (this._taskQueue.length > 0) {\n\t\t\tlet worker = this.findAvailableWorker();\n\n\t\t\tif (!worker) {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.dispatchQueue();\n\t\t\t\t}, 25);\n\n\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'No Worker Available', JSON.stringify(this._workers, null, 2));\n\t\t\t\t}\n\n\t\t\t\treturn; // no worker can take more tasks right now\n\t\t\t}\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Worker Available', worker.id, worker.activeTasks);\n\t\t\t}\n\n\t\t\t// Remove from queue\n\t\t\tlet task = this._taskQueue.shift();\n\t\t\tthis.assignTaskToWorker(worker, task);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the worker with the fewest activeTasks that is under maxConcurrency. Or null if none.\n\t */\n\tprivate findAvailableWorker(): WorkerConnection | null {\n\t\tlet candidates = this._workers.filter(x => x.activeTasks.length < this.MAX_CONCURRENCY);\n\t\tif (!candidates.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\tcandidates.sort((x, y) => {\n\t\t\tlet totalX = x.activeTasks.map(a => a.weight).reduce((a, b) => a + b, 0);\n\t\t\tlet totalY = y.activeTasks.map(a => a.weight).reduce((a, b) => a + b, 0);\n\t\t\treturn totalX - totalY;\n\t\t});\n\n\t\treturn candidates[0];\n\t}\n\n\tprivate assignTaskToWorker(worker: WorkerConnection, task: TaskPayload) {\n\t\tlet method = this._methodManager.getMethod(task.method);\n\n\t\tif (!method) {\n\t\t\tconsole.error('Failed to send task to worker - Could not find method:', task.method);\n\t\t\treturn;\n\t\t}\n\n\t\tworker.activeTasks.push({\n\t\t\ttaskId: task.taskId,\n\t\t\tweight: method && method.workerTaskWeight ? method.workerTaskWeight : 1\n\t\t});\n\n\t\tlet payload: TaskPayload = {\n\t\t\ttype: 'task',\n\t\t\ttaskId: task.taskId,\n\t\t\tmessageId: task.messageId,\n\t\t\tmethod: task.method,\n\t\t\tparams: task.params,\n\t\t\tuserContext: task.userContext || {}\n\t\t};\n\n\t\tlet timeoutHandle = setTimeout(() => {\n\t\t\tlet pending = this._pendingTasks.get(task.taskId);\n\t\t\t\n\t\t\tif (pending) {\n\t\t\t\tif (pending.promise) {\n\t\t\t\t\tpending.promise.reject('Task timed out after 2m in WorkerDispatcherManager for method: ' + task.method);\n\t\t\t\t}\n\n\t\t\t\tthis._pendingTasks.delete(task.taskId);\n\t\t\t}\n\n\t\t\tconsole.log(new Date(), 'TIMEOUT HIT', 'task', task.taskId, task.messageId, task.method, JSON.stringify(this._workers.map(a => a.activeTasks)));\n\n\t\t\tworker.activeTasks = worker.activeTasks.filter(a => a.taskId !== task.taskId);\n\n\t\t\tif (task.userContext && task.userContext.id_ws) {\n\t\t\t\tlet timeoutRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: task.messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Task timed out after 2m in WorkerDispatcherManager for method: ' + task.method\n\t\t\t\t};\n\n\t\t\t\tlet clientWS = this._websocketManager.getWebSocket(task.userContext.id_ws);\n\n\t\t\t\tif (clientWS) {\n\t\t\t\t\tthis._websocketManager.send(clientWS, timeoutRes);\n\t\t\t\t}\n\t\t\t}\n\t\t}, method.timeoutOverride || (1000 * 60 * 2));\n\n\t\t// If we already stored a promise for this task (from sendInternalPromise), add the timeout now\n\t\tlet existing = this._pendingTasks.get(task.taskId);\n\t\tif (!existing) {\n\t\t\texisting = { timeout: null };\n\t\t}\n\n\t\texisting.timeout = timeoutHandle;\n\t\tthis._pendingTasks.set(task.taskId, existing);\n\n\t\ttry {\n\t\t\tthis.sendWorkerPayload(worker.ws, payload);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to send task to worker:', err);\n\n\t\t\tclearTimeout(timeoutHandle);\n\t\t\tworker.activeTasks = worker.activeTasks.filter(a => a.taskId !== task.taskId);\n\n\t\t\t// Put task back in front\n\t\t\tthis._taskQueue.unshift(task);\n\t\t\tthis.dispatchQueue();\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages coming back from a worker (like 'taskComplete').\n\t */\n\tpublic handleWorkerMessage(workerId: string, rawMessage: WebSocket.RawData) {\n\t\tlet data: TaskResponse;\n\n\t\ttry {\n\t\t\tif (typeof rawMessage === 'string') {\n\t\t\t\tdata = JSON.parse(rawMessage, dateReviver);\n\t\t\t}\n\t\t\telse if (Buffer.isBuffer(rawMessage)) {\n\t\t\t\tdata = unpack(rawMessage);\n\t\t\t}\n\t\t\telse if (Array.isArray(rawMessage)) {\n\t\t\t\tconst chunks = rawMessage as unknown as ReadonlyArray<Uint8Array>;\n\t\t\t\tdata = unpack(Buffer.concat(chunks));\n\t\t\t}\n\t\t\telse if (rawMessage instanceof ArrayBuffer) {\n\t\t\t\tdata = unpack(Buffer.from(rawMessage));\n\t\t\t}\n\t\t\telse if (ArrayBuffer.isView(rawMessage)) {\n\t\t\t\tconst view = rawMessage as NodeJS.ArrayBufferView;\n\t\t\t\tdata = unpack(Buffer.from(view.buffer, view.byteOffset, view.byteLength));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.error('Unsupported worker message type received:', typeof rawMessage);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.error('Failed to parse worker message:', err);\n\t\t\treturn;\n\t\t}\n\n\t\tif (data.type === 'taskComplete') {\n\t\t\tlet worker = this._workers.find(x => x.id === workerId);\n\n\t\t\tif (!worker) {\n\t\t\t\tconsole.error('Unknown worker for taskComplete:', workerId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet { taskId, messageId, error, result } = data;\n\t\t\tworker.activeTasks = worker.activeTasks.filter(a => a.taskId !== taskId);\n\n\t\t\tlet pendingTask = this._pendingTasks.get(taskId);\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Recv from Worker Server', data);\n\t\t\t}\n\n\t\t\tif (pendingTask) {\n\t\t\t\tif (pendingTask.promise) {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\tpendingTask.promise.reject(result);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tpendingTask.promise.resolve(result);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tclearTimeout(pendingTask.timeout);\n\t\t\t\tthis._pendingTasks.delete(taskId);\n\t\t\t}\n\n\t\t\t// Look up original request if it came from a client\n\t\t\tlet clientReqId = this._clientRequests[taskId];\n\n\t\t\tif (clientReqId) {\n\t\t\t\tlet res: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: result\n\t\t\t\t};\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.hasError = true;\n\t\t\t\t\tres.data = result;\n\t\t\t\t}\n\n\t\t\t\tlet clientReqWS = this._websocketManager.getWebSocket(clientReqId);\n\n\t\t\t\tif (clientReqWS) {\n\t\t\t\t\tthis._websocketManager.send(clientReqWS, res);\n\t\t\t\t}\n\n\t\t\t\tif (this._clientRequests[taskId]) {\n\t\t\t\t\tdelete this._clientRequests[taskId];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to dispatch more from the queue\n\t\t\tif (this._taskQueue.length) {\n\t\t\t\tthis.dispatchQueue();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic sendWorkerPayload(ws: WebSocket.WebSocket, payload: TaskPayload | string) {\n\t\tif (!ws) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (ws.readyState !== ws.OPEN) {\n\t\t\tif (typeof payload !== 'string') {\n\t\t\t\tconst task = payload;\n\n\t\t\t\tthis._taskQueue.unshift(task);\n\t\t\t\tthis.dispatchQueue();\n\n\t\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\t\tws.close();\n\n\t\t\t\tlet pendingTask = this._pendingTasks.get(task.taskId);\n\n\t\t\t\tif (pendingTask) {\n\t\t\t\t\tclearTimeout(pendingTask.timeout);\n\t\t\t\t\tthis._pendingTasks.delete(task.taskId);\n\n\t\t\t\t\tif (pendingTask.promise) {\n\t\t\t\t\t\tpendingTask.promise.reject('Worker socket not open.');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\t\tws.close();\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (typeof payload === 'string') {\n\t\t\ttry {\n\t\t\t\tws.send(payload);\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\t\tws.close();\n\t\t\t\tconsole.error('Failed to send worker payload:', err);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst task = payload;\n\t\tconst payloadBuffer = pack(task);\n\n\t\ttry {\n\t\t\tws.send(payloadBuffer);\n\t\t}\n\t\tcatch (err) {\n\t\t\tthis._taskQueue.unshift(task);\n\t\t\tthis.dispatchQueue();\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Sending to Server', task);\n\t\t\t}\n\n\t\t\tthis.disconnectWorker(ws['id_worker']);\n\t\t\tws.close();\n\t\t\tconsole.error('Failed to send worker response:', err);\n\n\t\t\tlet pendingTask = this._pendingTasks.get(task.taskId);\n\n\t\t\tif (pendingTask) {\n\t\t\t\tclearTimeout(pendingTask.timeout);\n\t\t\t\tthis._pendingTasks.delete(task.taskId);\n\n\t\t\t\tif (pendingTask.promise) {\n\t\t\t\t\tpendingTask.promise.reject('Failed to send worker response: ' + err?.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|
|
@@ -63,6 +63,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
|
63
63
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
64
64
|
exports.WorkerServerManager = void 0;
|
|
65
65
|
var WebSocket = require("ws");
|
|
66
|
+
var msgpackr_1 = require("msgpackr");
|
|
66
67
|
var common_1 = require("../util/common");
|
|
67
68
|
var method_manager_1 = require("./method.manager");
|
|
68
69
|
var WorkerServerManager = /** @class */ (function () {
|
|
@@ -113,16 +114,14 @@ var WorkerServerManager = /** @class */ (function () {
|
|
|
113
114
|
}, 15000);
|
|
114
115
|
});
|
|
115
116
|
ws.on('message', function (rawData) { return __awaiter(_this, void 0, void 0, function () {
|
|
116
|
-
var msg;
|
|
117
|
+
var msg_1, messageBuffer, chunks, view, msg;
|
|
117
118
|
return __generator(this, function (_a) {
|
|
118
119
|
switch (_a.label) {
|
|
119
120
|
case 0:
|
|
121
|
+
if (!(typeof rawData === 'string')) return [3 /*break*/, 5];
|
|
120
122
|
if (this._methodManager.getEnableDebug()) {
|
|
121
123
|
console.log(new Date(), 'Message Recv', rawData);
|
|
122
124
|
}
|
|
123
|
-
if (typeof rawData !== 'string') {
|
|
124
|
-
rawData = rawData.toString();
|
|
125
|
-
}
|
|
126
125
|
if (!(rawData === 'ping')) return [3 /*break*/, 1];
|
|
127
126
|
if (this._methodManager.getEnableDebug()) {
|
|
128
127
|
console.log(new Date(), 'Recv Ping, Sending Pong');
|
|
@@ -137,20 +136,53 @@ var WorkerServerManager = /** @class */ (function () {
|
|
|
137
136
|
lastComm = new Date();
|
|
138
137
|
return [3 /*break*/, 4];
|
|
139
138
|
case 2:
|
|
140
|
-
msg = void 0;
|
|
141
139
|
try {
|
|
142
|
-
|
|
140
|
+
msg_1 = JSON.parse(rawData, common_1.dateReviver);
|
|
143
141
|
}
|
|
144
142
|
catch (e) {
|
|
145
143
|
console.error('Worker parse error', e);
|
|
146
144
|
return [2 /*return*/];
|
|
147
145
|
}
|
|
148
|
-
if (!(
|
|
149
|
-
return [4 /*yield*/, this.handleIncomingTask(ws,
|
|
146
|
+
if (!(msg_1.type === 'task')) return [3 /*break*/, 4];
|
|
147
|
+
return [4 /*yield*/, this.handleIncomingTask(ws, msg_1)];
|
|
150
148
|
case 3:
|
|
151
149
|
_a.sent();
|
|
152
150
|
_a.label = 4;
|
|
153
151
|
case 4: return [2 /*return*/];
|
|
152
|
+
case 5:
|
|
153
|
+
if (Buffer.isBuffer(rawData)) {
|
|
154
|
+
messageBuffer = rawData;
|
|
155
|
+
}
|
|
156
|
+
else if (Array.isArray(rawData)) {
|
|
157
|
+
chunks = rawData;
|
|
158
|
+
messageBuffer = Buffer.concat(chunks);
|
|
159
|
+
}
|
|
160
|
+
else if (rawData instanceof ArrayBuffer) {
|
|
161
|
+
messageBuffer = Buffer.from(rawData);
|
|
162
|
+
}
|
|
163
|
+
else if (ArrayBuffer.isView(rawData)) {
|
|
164
|
+
view = rawData;
|
|
165
|
+
messageBuffer = Buffer.from(view.buffer, view.byteOffset, view.byteLength);
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
messageBuffer = Buffer.from(rawData);
|
|
169
|
+
}
|
|
170
|
+
if (this._methodManager.getEnableDebug()) {
|
|
171
|
+
console.log(new Date(), 'Message Recv (binary)', messageBuffer.length);
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
msg = (0, msgpackr_1.unpack)(messageBuffer);
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
console.error('Worker binary parse error', e);
|
|
178
|
+
return [2 /*return*/];
|
|
179
|
+
}
|
|
180
|
+
if (!(msg.type === 'task')) return [3 /*break*/, 7];
|
|
181
|
+
return [4 /*yield*/, this.handleIncomingTask(ws, msg)];
|
|
182
|
+
case 6:
|
|
183
|
+
_a.sent();
|
|
184
|
+
_a.label = 7;
|
|
185
|
+
case 7: return [2 /*return*/];
|
|
154
186
|
}
|
|
155
187
|
});
|
|
156
188
|
}); });
|
|
@@ -278,15 +310,17 @@ var WorkerServerManager = /** @class */ (function () {
|
|
|
278
310
|
});
|
|
279
311
|
};
|
|
280
312
|
WorkerServerManager.prototype.sendWorkerResponse = function (ws, payload) {
|
|
281
|
-
if (typeof payload !== 'string') {
|
|
282
|
-
payload = JSON.stringify(payload);
|
|
283
|
-
}
|
|
284
313
|
if (this._methodManager.getEnableDebug()) {
|
|
285
|
-
console.log(new Date(), 'Sending', payload);
|
|
314
|
+
console.log(new Date(), 'Sending', typeof payload === 'string' ? payload : '[binary]');
|
|
286
315
|
}
|
|
287
316
|
if (ws && ws.readyState === ws.OPEN) {
|
|
288
317
|
try {
|
|
289
|
-
|
|
318
|
+
if (typeof payload === 'string') {
|
|
319
|
+
ws.send(payload);
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
ws.send((0, msgpackr_1.pack)(payload));
|
|
323
|
+
}
|
|
290
324
|
}
|
|
291
325
|
catch (err) {
|
|
292
326
|
console.error('Failed to send worker response:', err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/managers/worker-server.manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;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AAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAE,CAAC,CAAC;wBAE5F,qBAAM,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,gBAAgB,EAAE,2BAAoB,MAAM,gBAAM,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAE,CAAC,EAAA;;wBAAvH,SAAuH,CAAC;wBAExH,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,KAAK,MAAM,EAAZ,CAAY,CAAC,CAAC;;;;;;KAEzE;IAEM,gDAAkB,GAAzB,UAA0B,EAAE,EAAE,OAA8B;QACxD,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;YAC7B,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;SACrC;QAED,IAAI,IAAI,CAAC,cAAc,CAAC,cAAc,EAAE,EAAE;YACtC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;SAC/C;QAED,IAAI,EAAE,IAAI,EAAE,CAAC,UAAU,KAAK,EAAE,CAAC,IAAI,EAAE;YACjC,IAAI;gBACA,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;aACpB;YACD,OAAO,GAAG,EAAE;gBACR,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,GAAG,CAAC,CAAC;aACzD;SACJ;aACI,IAAI,EAAE,EAAE;YACT,EAAE,CAAC,KAAK,EAAE,CAAC;SACd;IACL,CAAC;IACL,0BAAC;AAAD,CArOA,AAqOC,IAAA;AArOY,kDAAmB","file":"worker-server.manager.js","sourcesContent":["import * as WebSocket from 'ws';\nimport { TaskPayload, TaskResponse } from '../models/server-message.model';\nimport { dateReviver } from '../util/common';\nimport { MethodManager } from './method.manager';\n\nexport class WorkerServerManager {\n private _methodManager: MethodManager;\n private _serverConfig;\n private _runningTasks = [];\n\n constructor() {}\n \n static create(methodManager: MethodManager, serverConfig) {\n const workerServerManager = new WorkerServerManager();\n workerServerManager.initialize(methodManager, serverConfig);\n return workerServerManager;\n }\n\n public initialize(methodManager: MethodManager, serverConfig) {\n this._methodManager = methodManager;\n this._serverConfig = serverConfig;\n this.startWorkerInstance();\n }\n\n private startWorkerInstance() {\n console.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n \n // Internal is NOT working\n // let wsUrl = (this._serverConfig['SERVER_URL_INTERNAL'] ? this._serverConfig['SERVER_URL_INTERNAL'] : this._serverConfig['SERVER_URL']) + '/websocket?workerToken=' + this._serverConfig['WORKER_TOKEN'];\n let wsUrl = this._serverConfig['SERVER_URL'] + '/websocket?workerToken=' + this._serverConfig['WORKER_TOKEN'] + '&workerIndex=' + process.env.WORKER_INDEX;\n const ws = new WebSocket(wsUrl);\n \n let lastComm = null;\n let interval = null;\n let openTimeout = null;\n let opened = false;\n \n // Set timeout if the socket never opens\n openTimeout = setTimeout(() => {\n if (!opened) {\n console.error(new Date(), 'WebSocket connection timeout. Retrying...');\n ws.terminate(); // force close if still connecting\n }\n }, 10000); // 10 seconds timeout\n \n ws.on('open', () => {\n opened = true;\n clearTimeout(openTimeout);\n \n console.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n this.sendWorkerResponse(ws, 'ping');\n \n interval = setInterval(() => {\n if (!lastComm) {\n ws.close();\n }\n else {\n lastComm = null;\n this.sendWorkerResponse(ws, 'ping');\n }\n }, 15000);\n });\n \n ws.on('message', async (rawData: any) => {\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Message Recv', rawData);\n }\n \n if (typeof rawData !== 'string') {\n rawData = rawData.toString();\n }\n \n if (rawData === 'ping') {\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Recv Ping, Sending Pong');\n }\n \n this.sendWorkerResponse(ws, 'pong');\n }\n else if (rawData === 'pong') {\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Recv Pong');\n }\n lastComm = new Date();\n }\n else {\n let msg: any;\n try {\n msg = JSON.parse(rawData, dateReviver);\n }\n catch (e) {\n console.error('Worker parse error', e);\n return;\n }\n \n if (msg.type === 'task') {\n await this.handleIncomingTask(ws, msg);\n }\n }\n });\n \n ws.on('close', () => {\n console.log(new Date(), 'Disconnected from main server. Reconnecting in 1s...');\n setTimeout(() => {\n this.startWorkerInstance();\n }, 1000);\n \n if (interval) {\n clearInterval(interval);\n }\n clearTimeout(openTimeout);\n });\n \n ws.on('error', (err) => {\n console.error(new Date(), 'Worker WS error:', err);\n ws.close();\n });\n }\n\n private async handleIncomingTask(ws: WebSocket.WebSocket, data: TaskPayload) {\n let { taskId, messageId, method, params, userContext } = data;\n this._runningTasks.push(taskId);\n if (!taskId || !method || !this._methodManager.getMethod(method)) {\n if (!this._methodManager.getMethod(method)) {\n console.error(new Date(), 'No method in method manager for handleIncomingTask worker server', method);\n await this._methodManager.callMethod('insertErrorLog', `No Method in worker server handleIncomingTask: ${method} - ${JSON.stringify(data, null, 2)}`);\n }\n\n // console.log('Invalid task message received', data);\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: true,\n result: 'Invalid task'\n });\n\n return;\n }\n\n let timedOut = false;\n let timeoutHandle = setTimeout(async () => {\n timedOut = true;\n console.error(new Date(), 'Worker timed out on task:', taskId, 'Method:', method);\n\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: true,\n result: 'Task timed out'\n });\n\n await this._methodManager.callMethod('insertErrorLog', `Timeout in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n }, this._methodManager.getMethod(method)?.timeoutOverride || (1000 * 60 * 2));\n\n try {\n let managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n id_user: userContext?.id_user || '',\n user: userContext?.user || '',\n id_ws: userContext?.id_ws || ''\n });\n\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Running method', method);\n }\n\n let result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Finished method', method);\n }\n\n if (!timedOut) {\n clearTimeout(timeoutHandle);\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: false,\n result\n });\n }\n\n this._runningTasks = this._runningTasks.filter(a => a !== taskId);\n \n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Done with Task', JSON.stringify(this._runningTasks, null, 2));\n }\n }\n catch (err) {\n if (!timedOut) {\n clearTimeout(timeoutHandle);\n console.error('Worker failed task:', taskId, 'Method:', method, err);\n err.message = 'Worker failed task:' + taskId + ' Method:' + method + ' - ' + err.message;\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: true,\n result: err || 'Unknown error'\n });\n throw err;\n }\n\n console.error(new Date(), `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n \n await this._methodManager.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n \n this._runningTasks = this._runningTasks.filter(a => a !== taskId);\n }\n }\n\n public sendWorkerResponse(ws, payload: TaskResponse | string) {\n if (typeof payload !== 'string') {\n payload = JSON.stringify(payload);\n }\n\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Sending', payload);\n }\n\n if (ws && ws.readyState === ws.OPEN) {\n try {\n ws.send(payload);\n }\n catch (err) {\n console.error('Failed to send worker response:', err);\n }\n }\n else if (ws) {\n ws.close();\n }\n }\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/managers/worker-server.manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8BAAgC;AAChC,qCAAwC;AAExC,yCAA6C;AAC7C,mDAAiD;AAEjD;IAKI;QAFQ,kBAAa,GAAG,EAAE,CAAC;I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,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,KAAK,MAAM,EAAZ,CAAY,CAAC,CAAC;;;;;;KAEzE;IAEG,gDAAkB,GAAzB,UAA0B,EAAE,EAAE,OAA8B;QAC3D,IAAI,IAAI,CAAC,cAAc,CAAC,cAAc,EAAE,EAAE;YACzC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,SAAS,EAAE,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;SACvF;QAED,IAAI,EAAE,IAAI,EAAE,CAAC,UAAU,KAAK,EAAE,CAAC,IAAI,EAAE;YACpC,IAAI;gBACH,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;oBAChC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;iBACjB;qBACI;oBACJ,EAAE,CAAC,IAAI,CAAC,IAAA,eAAI,EAAC,OAAO,CAAC,CAAC,CAAC;iBACvB;aACD;YACD,OAAO,GAAG,EAAE;gBACX,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,GAAG,CAAC,CAAC;aACtD;SACD;aACI,IAAI,EAAE,EAAE;YACZ,EAAE,CAAC,KAAK,EAAE,CAAC;SACX;IACF,CAAC;IACF,0BAAC;AAAD,CA5QA,AA4QC,IAAA;AA5QY,kDAAmB","file":"worker-server.manager.js","sourcesContent":["import * as WebSocket from 'ws';\nimport { pack, unpack } from 'msgpackr';\nimport { TaskPayload, TaskResponse } from '../models/server-message.model';\nimport { dateReviver } from '../util/common';\nimport { MethodManager } from './method.manager';\n\nexport class WorkerServerManager {\n private _methodManager: MethodManager;\n private _serverConfig;\n private _runningTasks = [];\n\n constructor() {}\n \n static create(methodManager: MethodManager, serverConfig) {\n const workerServerManager = new WorkerServerManager();\n workerServerManager.initialize(methodManager, serverConfig);\n return workerServerManager;\n }\n\n public initialize(methodManager: MethodManager, serverConfig) {\n this._methodManager = methodManager;\n this._serverConfig = serverConfig;\n this.startWorkerInstance();\n }\n\n private startWorkerInstance() {\n console.log(new Date(), 'Worker instance started, connecting to main server via WebSocket...');\n \n // Internal is NOT working\n // let wsUrl = (this._serverConfig['SERVER_URL_INTERNAL'] ? this._serverConfig['SERVER_URL_INTERNAL'] : this._serverConfig['SERVER_URL']) + '/websocket?workerToken=' + this._serverConfig['WORKER_TOKEN'];\n let wsUrl = this._serverConfig['SERVER_URL'] + '/websocket?workerToken=' + this._serverConfig['WORKER_TOKEN'] + '&workerIndex=' + process.env.WORKER_INDEX;\n const ws = new WebSocket(wsUrl);\n \n let lastComm = null;\n let interval = null;\n let openTimeout = null;\n let opened = false;\n \n // Set timeout if the socket never opens\n openTimeout = setTimeout(() => {\n if (!opened) {\n console.error(new Date(), 'WebSocket connection timeout. Retrying...');\n ws.terminate(); // force close if still connecting\n }\n }, 10000); // 10 seconds timeout\n \n ws.on('open', () => {\n opened = true;\n clearTimeout(openTimeout);\n \n console.log(new Date(), 'Connected to main server as worker', process.env.WORKER_INDEX, process.env.NODE_APP_INSTANCE);\n this.sendWorkerResponse(ws, 'ping');\n \n interval = setInterval(() => {\n if (!lastComm) {\n ws.close();\n }\n else {\n lastComm = null;\n this.sendWorkerResponse(ws, 'ping');\n }\n }, 15000);\n });\n \n\t\tws.on('message', async (rawData: WebSocket.RawData) => {\n\t\t\tif (typeof rawData === 'string') {\n\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Message Recv', rawData);\n\t\t\t\t}\n\n\t\t\t\tif (rawData === 'ping') {\n\t\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Recv Ping, Sending Pong');\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis.sendWorkerResponse(ws, 'pong');\n\t\t\t\t}\n\t\t\t\telse if (rawData === 'pong') {\n\t\t\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Recv Pong');\n\t\t\t\t\t}\n\t\t\t\t\tlastComm = new Date();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlet msg: any;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmsg = JSON.parse(rawData, dateReviver);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (e) {\n\t\t\t\t\t\tconsole.error('Worker parse error', e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\n\t\t\t\t\tif (msg.type === 'task') {\n\t\t\t\t\t\tawait this.handleIncomingTask(ws, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet messageBuffer: Buffer;\n\n\t\t\tif (Buffer.isBuffer(rawData)) {\n\t\t\t\tmessageBuffer = rawData;\n\t\t\t}\n\t\t\telse if (Array.isArray(rawData)) {\n\t\t\t\tconst chunks = rawData as unknown as ReadonlyArray<Uint8Array>;\n\t\t\t\tmessageBuffer = Buffer.concat(chunks);\n\t\t\t}\n\t\t\telse if (rawData instanceof ArrayBuffer) {\n\t\t\t\tmessageBuffer = Buffer.from(rawData);\n\t\t\t}\n\t\t\telse if (ArrayBuffer.isView(rawData)) {\n\t\t\t\tconst view = rawData as NodeJS.ArrayBufferView;\n\t\t\t\tmessageBuffer = Buffer.from(view.buffer, view.byteOffset, view.byteLength);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmessageBuffer = Buffer.from(rawData as any);\n\t\t\t}\n\n\t\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Message Recv (binary)', messageBuffer.length);\n\t\t\t}\n\n\t\t\tlet msg: TaskPayload;\n\n\t\t\ttry {\n\t\t\t\tmsg = unpack(messageBuffer);\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tconsole.error('Worker binary parse error', e);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (msg.type === 'task') {\n\t\t\t\tawait this.handleIncomingTask(ws, msg);\n\t\t\t}\n\t\t});\n \n ws.on('close', () => {\n console.log(new Date(), 'Disconnected from main server. Reconnecting in 1s...');\n setTimeout(() => {\n this.startWorkerInstance();\n }, 1000);\n \n if (interval) {\n clearInterval(interval);\n }\n clearTimeout(openTimeout);\n });\n \n ws.on('error', (err) => {\n console.error(new Date(), 'Worker WS error:', err);\n ws.close();\n });\n }\n\n private async handleIncomingTask(ws: WebSocket.WebSocket, data: TaskPayload) {\n let { taskId, messageId, method, params, userContext } = data;\n this._runningTasks.push(taskId);\n if (!taskId || !method || !this._methodManager.getMethod(method)) {\n if (!this._methodManager.getMethod(method)) {\n console.error(new Date(), 'No method in method manager for handleIncomingTask worker server', method);\n await this._methodManager.callMethod('insertErrorLog', `No Method in worker server handleIncomingTask: ${method} - ${JSON.stringify(data, null, 2)}`);\n }\n\n // console.log('Invalid task message received', data);\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: true,\n result: 'Invalid task'\n });\n\n return;\n }\n\n let timedOut = false;\n let timeoutHandle = setTimeout(async () => {\n timedOut = true;\n console.error(new Date(), 'Worker timed out on task:', taskId, 'Method:', method);\n\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: true,\n result: 'Task timed out'\n });\n\n await this._methodManager.callMethod('insertErrorLog', `Timeout in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n }, this._methodManager.getMethod(method)?.timeoutOverride || (1000 * 60 * 2));\n\n try {\n let managerThis = Object.assign({}, this._methodManager, MethodManager.prototype, {\n id_user: userContext?.id_user || '',\n user: userContext?.user || '',\n id_ws: userContext?.id_ws || ''\n });\n\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Running method', method);\n }\n\n let result = await this._methodManager.callMethod.call(managerThis, method, ...params);\n\n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Finished method', method);\n }\n\n if (!timedOut) {\n clearTimeout(timeoutHandle);\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: false,\n result\n });\n }\n\n this._runningTasks = this._runningTasks.filter(a => a !== taskId);\n \n if (this._methodManager.getEnableDebug()) {\n console.log(new Date(), 'Done with Task', JSON.stringify(this._runningTasks, null, 2));\n }\n }\n catch (err) {\n if (!timedOut) {\n clearTimeout(timeoutHandle);\n console.error('Worker failed task:', taskId, 'Method:', method, err);\n err.message = 'Worker failed task:' + taskId + ' Method:' + method + ' - ' + err.message;\n this.sendWorkerResponse(ws, {\n type: 'taskComplete',\n taskId,\n messageId,\n error: true,\n result: err || 'Unknown error'\n });\n throw err;\n }\n\n console.error(new Date(), `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n \n await this._methodManager.callMethod('insertErrorLog', `Error in Method: ${method} - ${JSON.stringify(data, null, 2)}`);\n \n this._runningTasks = this._runningTasks.filter(a => a !== taskId);\n }\n }\n\n\tpublic sendWorkerResponse(ws, payload: TaskResponse | string) {\n\t\tif (this._methodManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Sending', typeof payload === 'string' ? payload : '[binary]');\n\t\t}\n\n\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\ttry {\n\t\t\t\tif (typeof payload === 'string') {\n\t\t\t\t\tws.send(payload);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tws.send(pack(payload));\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (err) {\n\t\t\t\tconsole.error('Failed to send worker response:', err);\n\t\t\t}\n\t\t}\n\t\telse if (ws) {\n\t\t\tws.close();\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/models/subscription.model.ts"],"names":[],"mappings":"","file":"subscription.model.js","sourcesContent":["import SimpleSchema from 'simpl-schema';\n\n\nexport interface SubscriptionModel {\n\t[key: string]: SubscriptionPubModel;\n}\n\nexport interface SubscriptionPubModel {\n\t/* \n\t\tName: check\n\t\tType: SimpleSchema\n\t\tInputs: N/A\n\t\tOutputs: N/A\n\t\tReason: Define schema - Checks publication parameters to make sure all are valid\n\t\tRequired: Only if function has publication parameters\n\t*/\n\tcheck?: SimpleSchema;\n\n\t/* \n\t\tName: function\n\t\tType: Function\n\t\tInputs: 0 or more publication parameters (ie: id_bulktank: string)\n\t\tOutputs: Promise<any | any[]>\n\t\tReason: Runs publication query to get data to send to client\n\t\tRequired: Always\n\t*/\n\t// eslint-disable-next-line no-unused-vars\n\tfunction: (...parameters: any[]) => Promise<any | any[]>;\n\n\t/* \n\t\tName: collections\n\t\tType: Array\n\t\tInputs: N/A\n\t\tOutputs: N/A\n\t\tReason: All collections which will be watching oplog to re-run this pub\n\t\tRequired: Always\n\t*/\n\tcollections: string[];\n\n\t/* \n\t\tName: user_specific\n\t\tType: Boolean\n\t\tInputs: N/A\n\t\tOutputs: N/A\n\t\tReason: Use if user is needed (ie 'users' publication, only send 'Admin' if 'super-admin' role)\n\t\tRequired: Only if function has parameter/s\n\t\t- Low performance as if runs pub for each user, only use if needed\n\t*/\n\tuser_specific?: boolean;\n}\n\nexport interface ActiveSubscriptionModel {\n\tpublication: string;\n\tsubscriptionData: any[];\n\tcollections: string[];\n\tclients: ActiveSubscriptionClientModel[];\n\tcacheId: number;\n\trunning: boolean;\n\trunAgain: boolean;\n}\n\nexport interface ActiveSubscriptionClientModel {\n\tid_user: string;\n\tmessageId: number;\n\tid_socket: string;\n\tmessageRoute: string;\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/models/subscription.model.ts"],"names":[],"mappings":"","file":"subscription.model.js","sourcesContent":["import SimpleSchema from 'simpl-schema';\n\n\nexport interface SubscriptionModel {\n\t[key: string]: SubscriptionPubModel;\n}\n\nexport interface SubscriptionPubModel {\n\t/* \n\t\tName: check\n\t\tType: SimpleSchema\n\t\tInputs: N/A\n\t\tOutputs: N/A\n\t\tReason: Define schema - Checks publication parameters to make sure all are valid\n\t\tRequired: Only if function has publication parameters\n\t*/\n\tcheck?: SimpleSchema;\n\n\t/* \n\t\tName: function\n\t\tType: Function\n\t\tInputs: 0 or more publication parameters (ie: id_bulktank: string)\n\t\tOutputs: Promise<any | any[]>\n\t\tReason: Runs publication query to get data to send to client\n\t\tRequired: Always\n\t*/\n\t// eslint-disable-next-line no-unused-vars\n\tfunction: (...parameters: any[]) => Promise<any | any[]>;\n\n\t/* \n\t\tName: collections\n\t\tType: Array\n\t\tInputs: N/A\n\t\tOutputs: N/A\n\t\tReason: All collections which will be watching oplog to re-run this pub\n\t\tRequired: Always\n\t*/\n\tcollections: string[];\n\n\t/* \n\t\tName: user_specific\n\t\tType: Boolean\n\t\tInputs: N/A\n\t\tOutputs: N/A\n\t\tReason: Use if user is needed (ie 'users' publication, only send 'Admin' if 'super-admin' role)\n\t\tRequired: Only if function has parameter/s\n\t\t- Low performance as if runs pub for each user, only use if needed\n\t*/\n\tuser_specific?: boolean;\n}\n\nexport interface ActiveSubscriptionModel {\n\tpublication: string;\n\tsubscriptionKey: string;\n\tsubscriptionData: any[];\n\tcollections: string[];\n\tclients: ActiveSubscriptionClientModel[];\n\tcacheId: number;\n\trunning: boolean;\n\trunAgain: boolean;\n}\n\nexport interface ActiveSubscriptionClientModel {\n\tid_user: string;\n\tmessageId: number;\n\tid_socket: string;\n\tmessageRoute: string;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@resolveio/server-lib",
|
|
3
|
-
"version": "20.
|
|
3
|
+
"version": "20.9.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"package": "./build_package.sh",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
"jsonwebtoken": "8.5.1",
|
|
31
31
|
"jwt-decode": "3.1.2",
|
|
32
32
|
"moment-timezone": "0.5.43",
|
|
33
|
+
"msgpackr": "1.11.5",
|
|
33
34
|
"mongodb": "4.12.1",
|
|
34
35
|
"node-cache": "5.1.2",
|
|
35
36
|
"node-google-timezone": "0.1.1",
|
|
@@ -93,6 +94,7 @@
|
|
|
93
94
|
"jsonwebtoken": "8.5.1",
|
|
94
95
|
"jwt-decode": "3.1.2",
|
|
95
96
|
"moment-timezone": "0.5.43",
|
|
97
|
+
"msgpackr": "1.12.2",
|
|
96
98
|
"mongodb": "4.12.1",
|
|
97
99
|
"node-cache": "5.1.2",
|
|
98
100
|
"node-google-timezone": "0.1.1",
|
package/server-app.js
CHANGED
|
@@ -81,6 +81,7 @@ var jwt = require("jsonwebtoken");
|
|
|
81
81
|
var moment = require("moment-timezone");
|
|
82
82
|
var url_1 = require("url");
|
|
83
83
|
var WebSocket = require("ws");
|
|
84
|
+
var msgpackr_1 = require("msgpackr");
|
|
84
85
|
var log_collection_1 = require("./collections/log.collection");
|
|
85
86
|
var user_collection_1 = require("./collections/user.collection");
|
|
86
87
|
var cron_manager_1 = require("./managers/cron.manager");
|
|
@@ -616,22 +617,37 @@ var ResolveIOMainServer = /** @class */ (function () {
|
|
|
616
617
|
}
|
|
617
618
|
}, 30000);
|
|
618
619
|
ws.on('message', function (message) {
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
620
|
+
if (typeof message === 'string') {
|
|
621
|
+
if (message === 'ping') {
|
|
622
|
+
_this._workerDispatcherManager.sendWorkerPayload(ws, 'pong');
|
|
623
|
+
}
|
|
624
|
+
else if (message === 'pong') {
|
|
625
|
+
lastComm_1 = new Date();
|
|
626
|
+
}
|
|
627
|
+
else {
|
|
628
|
+
_this._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], message);
|
|
629
|
+
}
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
var buffer;
|
|
633
|
+
if (Buffer.isBuffer(message)) {
|
|
634
|
+
buffer = message;
|
|
622
635
|
}
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
_this._workerDispatcherManager.sendWorkerPayload(ws, 'pong');
|
|
636
|
+
else if (Array.isArray(message)) {
|
|
637
|
+
var chunks = message;
|
|
638
|
+
buffer = Buffer.concat(chunks);
|
|
627
639
|
}
|
|
628
|
-
else if (message
|
|
629
|
-
|
|
630
|
-
|
|
640
|
+
else if (message instanceof ArrayBuffer) {
|
|
641
|
+
buffer = Buffer.from(message);
|
|
642
|
+
}
|
|
643
|
+
else if (ArrayBuffer.isView(message)) {
|
|
644
|
+
var view = message;
|
|
645
|
+
buffer = Buffer.from(view.buffer, view.byteOffset, view.byteLength);
|
|
631
646
|
}
|
|
632
647
|
else {
|
|
633
|
-
|
|
648
|
+
buffer = Buffer.from(message);
|
|
634
649
|
}
|
|
650
|
+
_this._workerDispatcherManager.handleWorkerMessage(ws['id_worker'], buffer);
|
|
635
651
|
});
|
|
636
652
|
ws.on('close', function () {
|
|
637
653
|
_this._workerDispatcherManager.disconnectWorker(ws['id_worker']);
|
|
@@ -682,27 +698,54 @@ var ResolveIOMainServer = /** @class */ (function () {
|
|
|
682
698
|
ws['isAlive'] = true;
|
|
683
699
|
ws['retryCnt'] = 0;
|
|
684
700
|
ws.on('message', function (message) { return __awaiter(_this, void 0, void 0, function () {
|
|
685
|
-
var socketData, e_1;
|
|
701
|
+
var socketData, usedBinary, buffer, view, e_1;
|
|
686
702
|
return __generator(this, function (_a) {
|
|
687
703
|
switch (_a.label) {
|
|
688
704
|
case 0:
|
|
689
705
|
this._debugMsgRecv += 1;
|
|
690
706
|
socketData = [];
|
|
707
|
+
usedBinary = false;
|
|
691
708
|
_a.label = 1;
|
|
692
709
|
case 1:
|
|
693
710
|
_a.trys.push([1, 2, , 4]);
|
|
694
|
-
|
|
711
|
+
if (typeof message === 'string') {
|
|
712
|
+
socketData = JSON.parse(message, common_1.dateReviver);
|
|
713
|
+
}
|
|
714
|
+
else if (Buffer.isBuffer(message)) {
|
|
715
|
+
socketData = (0, msgpackr_1.unpack)(message);
|
|
716
|
+
usedBinary = true;
|
|
717
|
+
}
|
|
718
|
+
else if (Array.isArray(message)) {
|
|
719
|
+
buffer = Buffer.concat(message);
|
|
720
|
+
socketData = (0, msgpackr_1.unpack)(buffer);
|
|
721
|
+
usedBinary = true;
|
|
722
|
+
}
|
|
723
|
+
else if (message instanceof ArrayBuffer) {
|
|
724
|
+
socketData = (0, msgpackr_1.unpack)(Buffer.from(message));
|
|
725
|
+
usedBinary = true;
|
|
726
|
+
}
|
|
727
|
+
else if (ArrayBuffer.isView(message)) {
|
|
728
|
+
view = message;
|
|
729
|
+
socketData = (0, msgpackr_1.unpack)(Buffer.from(view.buffer, view.byteOffset, view.byteLength));
|
|
730
|
+
usedBinary = true;
|
|
731
|
+
}
|
|
732
|
+
else {
|
|
733
|
+
throw new Error('Unsupported WebSocket message type: ' + typeof message);
|
|
734
|
+
}
|
|
695
735
|
return [3 /*break*/, 4];
|
|
696
736
|
case 2:
|
|
697
737
|
e_1 = _a.sent();
|
|
698
|
-
console.log('Error -
|
|
699
|
-
return [4 /*yield*/, this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + resolveio_server_app_1.ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([message, e_1]))];
|
|
738
|
+
console.log('Error - WS message parse', e_1);
|
|
739
|
+
return [4 /*yield*/, this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + resolveio_server_app_1.ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([(Buffer.isBuffer(message) ? message.toString('base64') : message), e_1]))];
|
|
700
740
|
case 3:
|
|
701
741
|
_a.sent();
|
|
702
742
|
return [2 /*return*/];
|
|
703
|
-
case 4:
|
|
704
|
-
|
|
705
|
-
|
|
743
|
+
case 4:
|
|
744
|
+
if (usedBinary) {
|
|
745
|
+
ws['supportsBinary'] = true;
|
|
746
|
+
}
|
|
747
|
+
// call our existing processSocketMessage
|
|
748
|
+
return [4 /*yield*/, this.processSocketMessage(ws, socketData)];
|
|
706
749
|
case 5:
|
|
707
750
|
// call our existing processSocketMessage
|
|
708
751
|
_a.sent();
|